Programs & Examples On #Ordinal indicator

Print a string as hex bytes?

Print a string as hex bytes?

The accepted answer gives:

s = "Hello world !!"
":".join("{:02x}".format(ord(c)) for c in s)

returns:

'48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21'

The accepted answer works only so long as you use bytes (mostly ascii characters). But if you use unicode, e.g.:

a_string = u"?????? ???!!" # "Prevyet mir", or "Hello World" in Russian.

You need to convert to bytes somehow.

If your terminal doesn't accept these characters, you can decode from UTF-8 or use the names (so you can paste and run the code along with me):

a_string = (
    "\N{CYRILLIC CAPITAL LETTER PE}"
    "\N{CYRILLIC SMALL LETTER ER}"
    "\N{CYRILLIC SMALL LETTER I}"
    "\N{CYRILLIC SMALL LETTER VE}"
    "\N{CYRILLIC SMALL LETTER IE}"
    "\N{CYRILLIC SMALL LETTER TE}"
    "\N{SPACE}"
    "\N{CYRILLIC SMALL LETTER EM}"
    "\N{CYRILLIC SMALL LETTER I}"
    "\N{CYRILLIC SMALL LETTER ER}"
    "\N{EXCLAMATION MARK}"
    "\N{EXCLAMATION MARK}"
)

So we see that:

":".join("{:02x}".format(ord(c)) for c in a_string)

returns

'41f:440:438:432:435:442:20:43c:438:440:21:21'

a poor/unexpected result - these are the code points that combine to make the graphemes we see in Unicode, from the Unicode Consortium - representing languages all over the world. This is not how we actually store this information so it can be interpreted by other sources, though.

To allow another source to use this data, we would usually need to convert to UTF-8 encoding, for example, to save this string in bytes to disk or to publish to html. So we need that encoding to convert the code points to the code units of UTF-8 - in Python 3, ord is not needed because bytes are iterables of integers:

>>> ":".join("{:02x}".format(c) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

Or perhaps more elegantly, using the new f-strings (only available in Python 3):

>>> ":".join(f'{c:02x}' for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

In Python 2, pass c to ord first, i.e. ord(c) - more examples:

>>> ":".join("{:02x}".format(ord(c)) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'
>>> ":".join(format(ord(c), '02x') for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

Convert RGB to Black & White in OpenCV

Simple binary threshold method is sufficient.

include

#include <string>
#include "opencv/highgui.h"
#include "opencv2/imgproc/imgproc.hpp"

using namespace std;
using namespace cv;

int main()
{
    Mat img = imread("./img.jpg",0);//loading gray scale image
    threshold(img, img, 128, 255, CV_THRESH_BINARY);//threshold binary, you can change threshold 128 to your convenient threshold
    imwrite("./black-white.jpg",img);
    return 0;
}

You can use GaussianBlur to get a smooth black and white image.

How to delete a folder with files using Java

This works, and while it looks inefficient to skip the directory test, it's not: the test happens right away in listFiles().

void deleteDir(File file) {
    File[] contents = file.listFiles();
    if (contents != null) {
        for (File f : contents) {
            deleteDir(f);
        }
    }
    file.delete();
}

Update, to avoid following symbolic links:

void deleteDir(File file) {
    File[] contents = file.listFiles();
    if (contents != null) {
        for (File f : contents) {
            if (! Files.isSymbolicLink(f.toPath())) {
                deleteDir(f);
            }
        }
    }
    file.delete();
}

How to run Gulp tasks sequentially one after the other

I generated a node/gulp app using the generator-gulp-webapp Yeoman generator. It handled the "clean conundrum" this way (translating to the original tasks mentioned in the question):

gulp.task('develop', ['clean'], function () {
  gulp.start('coffee');
});

Beginner Python: AttributeError: 'list' object has no attribute

Consider:

class Bike(object):
    def __init__(self, name, weight, cost):
        self.name = name
        self.weight = weight
        self.cost = cost

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),      # <--
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165),    # <--
    }

# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
    profit = bike.cost * margin
    print(profit)

Output:

33.0
20.0

The difference is that in your bikes dictionary, you're initializing the values as lists [...]. Instead, it looks like the rest of your code wants Bike instances. So create Bike instances: Bike(...).

As for your error

AttributeError: 'list' object has no attribute 'cost'

this will occur when you try to call .cost on a list object. Pretty straightforward, but we can figure out what happened by looking at where you call .cost -- in this line:

profit = bike.cost * margin

This indicates that at least one bike (that is, a member of bikes.values() is a list). If you look at where you defined bikes you can see that the values were, in fact, lists. So this error makes sense.

But since your class has a cost attribute, it looked like you were trying to use Bike instances as values, so I made that little change:

[...] -> Bike(...)

and you're all set.

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

I had a similar issue but I was unable to use the UserAgent class inside the fake_useragent module. I was running the code inside a docker container

import requests
import ujson
import random

response = requests.get('https://fake-useragent.herokuapp.com/browsers/0.1.11')
agents_dictionary = ujson.loads(response.text)
random_browser_number = str(random.randint(0, len(agents_dictionary['randomize'])))
random_browser = agents_dictionary['randomize'][random_browser_number]
user_agents_list = agents_dictionary['browsers'][random_browser]
user_agent = user_agents_list[random.randint(0, len(user_agents_list)-1)]

I targeted the endpoint used in the module. This solution still gave me a random user agent however there is the possibility that the data structure at the endpoint could change.

Create a directory if it doesn't exist

OpenCV Specific

Opencv supports filesystem, probably through its dependency Boost.

#include <opencv2/core/utils/filesystem.hpp>
cv::utils::fs::createDirectory(outputDir);

How do I center a window onscreen in C#?

Use Location property of the form. Set it to the desired top left point

desired x = (desktop_width - form_witdh)/2

desired y = (desktop_height - from_height)/2

Get Maven artifact version at runtime

I spent some time on the two main approaches here and they didn't work-out for me. I am using Netbeans for the builds, may be there's more going on there. I had some errors and warnings from Maven 3 with some constructs, but I think those were easy to correct. No biggie.

I did find an answer that looks maintainable and simple to implement in this article on DZone:

I already have a resources/config sub-folder, and I named my file: app.properties, to better reflect the kind of stuff we may keep there (like a support URL, etc.).

The only caveat is that Netbeans gives a warning that the IDE needs filtering off. Not sure where/how. It has no effect at this point. Perhaps there's a work around for that if I need to cross that bridge. Best of luck.

Get value of input field inside an iframe

document.getElementById("idframe").contentWindow.document.getElementById("idelement").value;

Replace last occurrence of character in string

Another super clear way of doing this could be as follows:

let modifiedString = originalString
   .split('').reverse().join('')
   .replace('_', '')
   .split('').reverse().join('')

php implode (101) with quotes

I think this is what you are trying to do

$array = array('lastname', 'email', 'phone');
echo "'" . implode("','", explode(',', $array)) . "'";

How to fix "ImportError: No module named ..." error in Python?

In my mind I have to consider that the foo folder is a stand-alone library. I might want to consider moving it to the Lib\site-packages folder within a python installation. I might want to consider adding a foo.pth file there.

I know it's a library since the ./programs/my_python_program.py contains the following line:

from foo.tasks import my_function

So it doesn't matter that ./programs is a sibling folder to ./foo. It's the fact that my_python_program.py is run as a script like this:

python ./programs/my_python_program.py

How can I set the opacity or transparency of a Panel in WinForms?

Based on information found at http://www.windows-tech.info/3/53ee08e46d9cb138.php, I was able to achieve a translucent panel control using the following code.

public class TransparentPanel : Panel
{
    protected override CreateParams CreateParams
    {
        get
        {
            var cp = base.CreateParams;
            cp.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT

            return cp;
        }
    }

    protected override void OnPaint(PaintEventArgs e) =>
        e.Graphics.FillRectangle(new SolidBrush(this.BackColor), this.ClientRectangle);
}

The caveat is that any controls that are added to the panel have an opaque background. Nonetheless, the translucent panel was useful for me to block off parts of my WinForms application so that users focus was shifted to the appropriate area of the application.

How to get value of selected radio button?

You can also loop through the buttons with a forEach-loop on the elements

    var elements = document.getElementsByName('radioButton');
    var checkedButton;
    console.log(elements);
    elements.forEach(e => {
        if (e.checked) {
            //if radio button is checked, set sort style
            checkedButton = e.value;
        }
    });

UPDATE if exists else INSERT in SQL Server 2008

Many people will suggest you use MERGE, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:

http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/

Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;

A lot of folks will suggest this way:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
  UPDATE ...
END
ELSE
BEGIN
  INSERT ...
END
COMMIT TRANSACTION;

But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)

Others will suggest this way:

BEGIN TRY
  INSERT ...
END TRY
BEGIN CATCH
  IF ERROR_NUMBER() = 2627
    UPDATE ...
END CATCH

However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:

Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.

Make UINavigationBar transparent

If anybody is wondering how to achieve this in iOS 7+, here's a solution (iOS 6 compatible too)

In Objective-C

[self.navigationBar setBackgroundImage:[UIImage new]
                         forBarMetrics:UIBarMetricsDefault];
self.navigationBar.shadowImage = [UIImage new];
self.navigationBar.translucent = YES;

In swift 3 (iOS 10)

self.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.isTranslucent = true

In swift 2

self.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.translucent = true

Discussion

Setting translucent to YES on the navigation bar does the trick, due to a behavior discussed in the UINavigationBar documentation. I'll report here the relevant fragment:

If you set this property to YES on a navigation bar with an opaque custom background image, the navigation bar will apply a system opacity less than 1.0 to the image.

Cannot overwrite model once compiled Mongoose

The error is occurring because you already have a schema defined, and then you are defining the schema again. Generally what you should do is instantiate the schema once, and then have a global object call it when it needs it.

For example:

user_model.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var userSchema = new Schema({
   name:String,
   email:String,
   password:String,
   phone:Number,
   _enabled:Boolean
});
module.exports = mongoose.model('users', userSchema);          

check.js

var mongoose = require('mongoose');
var User = require('./user_model.js');

var db = mongoose.createConnection('localhost', 'event-db');
db.on('error', console.error.bind(console, 'connection error:'));
var a1= db.once('open',function(){
  User.find({},{},function (err, users) {
    mongoose.connection.close();
    console.log("Username supplied"+username);
    //doSomethingHere 
  })
});

insert.js

var mongoose = require('mongoose');
var User = require('./user_model.js');

mongoose.connect('mongodb://localhost/event-db');
var new_user = new User({
    name:req.body.name
  , email: req.body.email
  , password: req.body.password
  , phone: req.body.phone
  , _enabled:false 
});
new_user.save(function(err){
  if(err) console.log(err); 
});

Centering a canvas

Tested only on Firefox:

<script>
window.onload = window.onresize = function() {
    var C = 0.8;        // canvas width to viewport width ratio
    var W_TO_H = 2/1;   // canvas width to canvas height ratio
    var el = document.getElementById("a");

    // For IE compatibility http://www.google.com/search?q=get+viewport+size+js
    var viewportWidth = window.innerWidth;
    var viewportHeight = window.innerHeight;

    var canvasWidth = viewportWidth * C;
    var canvasHeight = canvasWidth / W_TO_H;
    el.style.position = "fixed";
    el.setAttribute("width", canvasWidth);
    el.setAttribute("height", canvasHeight);
    el.style.top = (viewportHeight - canvasHeight) / 2;
    el.style.left = (viewportWidth - canvasWidth) / 2;

    window.ctx = el.getContext("2d");
    ctx.clearRect(0,0,canvasWidth,canvasHeight);
    ctx.fillStyle = 'yellow';
    ctx.moveTo(0, canvasHeight/2);
    ctx.lineTo(canvasWidth/2, 0);
    ctx.lineTo(canvasWidth, canvasHeight/2);
    ctx.lineTo(canvasWidth/2, canvasHeight);
    ctx.lineTo(0, canvasHeight/2);
    ctx.fill()
}
</script>

<body>
<canvas id="a" style="background: black">
</canvas>
</body>

Printing variables in Python 3.4

You can also format the string like so:

>>> print ("{index}. {word} appears {count} times".format(index=1, word='Hello', count=42))

Which outputs

1. Hello appears 42 times.

Because the values are named, their order does not matter. Making the example below output the same as the above example.

>>> print ("{index}. {word} appears {count} times".format(count=42, index=1, word='Hello'))

Formatting string this way allows you to do this.

>>> data = {'count':42, 'index':1, 'word':'Hello'}
>>> print ("{index}. {word} appears {count} times.".format(**data))
1. Hello appears 42 times.

How to quickly and conveniently disable all console.log statements in my code?

I developed a library for this usecase: https://github.com/sunnykgupta/jsLogger

Features:

  1. It safely overrides the console.log.
  2. Takes care if the console is not available (oh yes, you need to factor that too.)
  3. Stores all logs (even if they are suppressed) for later retrieval.
  4. Handles major console functions like log, warn, error, info.

Is open for modifications and will be updated whenever new suggestions come up.

Convert Map to JSON using Jackson

You should prefer Object Mapper instead. Here is the link for the same : Object Mapper - Spring MVC way of Obect to JSON

read subprocess stdout line by line

Indeed, if you sorted out the iterator then buffering could now be your problem. You could tell the python in the sub-process not to buffer its output.

proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)

becomes

proc = subprocess.Popen(['python','-u', 'fake_utility.py'],stdout=subprocess.PIPE)

I have needed this when calling python from within python.

jquery .on() method with load event

As the other have mentioned, the load event does not bubble. Instead you can manually trigger a load-like event with a custom event:

$('#item').on('namespace/onload', handleOnload).trigger('namespace/onload')

If your element is already listening to a change event:

$('#item').on('change', handleChange).trigger('change')

I find this works well. Though, I stick to custom events to be more explicit and avoid side effects.

Finding which process was killed by Linux OOM killer

Try this out:

grep -i 'killed process' /var/log/messages

Convert date to day name e.g. Mon, Tue, Wed

For other language use day of week to recognize day name

For example for Persian use below code

$dayName = getDayName(date('w', strtotime('2019-11-14')));

    function getDayName($dayOfWeek) {

        switch ($dayOfWeek){
            case 6:
                return '????';
            case 0:
                return '?? ????';
            case 1:
                return '?? ????';
            case 2:
                return '?? ????';
            case 3:
                return '???? ????';
            case 4:
                return '??? ????';
            case 5:
                return '????';
            default:
                return '';
        }

    }

More info : https://www.php.net/manual/en/function.date.php

Application_Start not firing?

Had the same problem in a Project we had taken over after another vendor built it. The problem was that while there were a number of commands written by the previous vendor in Global.asax.cs, which might lead you to believe it was in use, it was actually being ignored entirely. Global.asax wasn't inheriting from it, and it's easy to never see this file if the .cs file is present - you have to right-click Global.asax and click View Markup to actually see it.

Global.asax:

<%@ Application Language="C#" %>

Needed to be changed to:

<%@ Application Codebehind="Global.asax.cs" Inherits="ProjectNamespace.MvcApplication" Language="C#" %>

Where ProjectNamespace is whatever the namespace is of your Global.asax.cs class (usually the name of your Project).

In our case the file contained a bunch of inline code, some of which was copy-pasted from the .cs file, some not. We just dumped the inline code over to the .cs file and gradually merged our changes back in.

How to construct a set out of list items in python?

You can do

my_set = set(my_list)

or, in Python 3,

my_set = {*my_list}

to create a set from a list. Conversely, you can also do

my_list = list(my_set)

or, in Python 3,

my_list = [*my_set]

to create a list from a set.

Just note that the order of the elements in a list is generally lost when converting the list to a set since a set is inherently unordered. (One exception in CPython, though, seems to be if the list consists only of non-negative integers, but I assume this is a consequence of the implementation of sets in CPython and that this behavior can vary between different Python implementations.)

Maintain image aspect ratio when changing height

Actually I found out that the container of the image tag need to have a height in order to keep the ratio of the image. for example>

.container{display:flex; height:100%;} img{width:100%;height:auto;}

then in your html your container will wrap the tag image

<div class="container"><img src="image.jpg" alt="image" /></div>

this work for IE and other browsers

How Do I Convert an Integer to a String in Excel VBA?

The accepted answer is good for smaller numbers, most importantly while you are taking data from excel sheets. as the bigger numbers will automatically converted to scientific numbers i.e. e+10.
So I think this will give you more general answer. I didn't check if it have any downfall or not.

CStr(CDbl(#yourNumber#))

this will work for e+ converted numbers! as the just CStr(7.7685099559e+11) will be shown as "7.7685099559e+11" not as expected: "776850995590" So I rather to say my answer will be more generic result.

Regards, M

Singleton: How should it be used

I use Singletons as an interview test.

When I ask a developer to name some design patterns, if all they can name is Singleton, they're not hired.

Format date with Moment.js

May be this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly. Please find the code: I am using moment.js format function on a current date as (today is 29-06-2020) var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20

what happening is it retains only the year part :20 as "06/28/20", after If I run the statement : new Date(startDate) The result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)",

Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in google chrome and firefox browsers it gives correct date on second attempt as: 06-28-2020. But in IE it is having issues, from this I understood we can apply one dateformat on the given date, If we want second date format, it should be apply on the fresh date not on the first date format result. And also observe that for first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in IE. For clear understanding please find my question in the link: Date went wrong when using Momentjs date format in IE 11

How can Perl's print add a newline by default?

Perl 6 has the say function that automatically appends \n.

You can also use say in Perl 5.10 or 5.12 if you add

use feature qw(say);

to the beginning of your program. Or you can use Modern::Perl to get this and other features.

See perldoc feature for more details.

Minimal web server using netcat

If you're using Apline Linux, the BusyBox netcat is slightly different:

while true; do nc -l -p 8080 -e sh -c 'echo -e "HTTP/1.1 200 OK\n\n$(date)"'; done

And another way using printf:

while true; do nc -l -p 8080 -e sh -c "printf 'HTTP/1.1 200 OK\n\n%s' \"$(date)\""; done

Html.fromHtml deprecated in Android N

If you are lucky enough to develop on Kotlin, just create an extension function:

fun String.toSpanned(): Spanned {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)
    } else {
        @Suppress("DEPRECATION")
        return Html.fromHtml(this)
    }
}

And then it's so sweet to use it everywhere:

yourTextView.text = anyString.toSpanned()

How to select records from last 24 hours using SQL?

Which SQL was not specified, SQL 2005 / 2008

SELECT yourfields from yourTable WHERE yourfieldWithDate > dateadd(dd,-1,getdate())

If you are on the 2008 increased accuracy date types, then use the new sysdatetime() function instead, equally if using UTC times internally swap to the UTC calls.

Wait Until File Is Completely Written

I would like to add an answer here, because this worked for me. I used time delays, while loops, everything I could think of.

I had the Windows Explorer window of the output folder open. I closed it, and everything worked like a charm.

I hope this helps someone.

Using a RegEx to match IP addresses in Python

import re
ipv=raw_input("Enter an ip address")
a=ipv.split('.')
s=str(bin(int(a[0]))+bin(int(a[1]))+bin(int(a[2]))+bin(int(a[3])))
s=s.replace("0b",".")
m=re.search('\.[0,1]{1,8}\.[0,1]{1,8}\.[0,1]{1,8}\.[0,1]{1,8}$',s)
if m is not None:
    print "Valid sequence of input"
else :
    print "Invalid input sequence"

Just to keep it simple I have used this approach. Simple as in to explain how really ipv4 address is evaluated. Checking whether its a binary number is although not required. Hope you like this.

"unrecognized import path" with go get

Because GFW forbidden you to access golang.org ! And when i use the proxy , it can work well.

you can look at the information using command go get -v -u golang.org/x/oauth2

Search in all files in a project in Sublime Text 3

You can search a directory using Find ? Find in files. This also includes all opened tabs.

The keyboard shortcut is Ctrl?+F on non-Mac (regular) keyboards, and ??+F on a Mac.

You'll be presented with three boxes: Find, Where and Replace. It's a regular Find/Find-replace search where Where specifies a file or directory to search. I for example often use a file name or . for searching the current directory. There are also a few special constructs that can be used within the Where field:

<project>,<current file>,<open files>,<open folders>,-*.doc,*.txt

Note that these are not placeholders, you type these verbatim. Most of them are self-explanatory (e.g. -*.doc excludes files with a .doc extension).

Pressing the ... to the right will present you with all available options.

After searching you'll be presented with a Find results page with all of your matching results. To jump to specific lines and files from it you simply double-click on a line.

How to pad a string with leading zeros in Python 3

Since python 3.6 you can use fstring :

>>> length = 1
>>> print(f'length = {length:03}')
length = 001

gitbash command quick reference

Git command Quick Reference

git [command] -help

Git command Manual Pages

git help [command]
git [command] --help

Autocomplete

git <tab>

Cheat Sheets

SQL Server 2008 - Help writing simple INSERT Trigger

You want to take advantage of the inserted logical table that is available in the context of a trigger. It matches the schema for the table that is being inserted to and includes the row(s) that will be inserted (in an update trigger you have access to the inserted and deleted logical tables which represent the the new and original data respectively.)

So to insert Employee / Department pairs that do not currently exist you might try something like the following.

CREATE TRIGGER trig_Update_Employee
ON [EmployeeResult]
FOR INSERT
AS
Begin
    Insert into Employee (Name, Department) 
    Select Distinct i.Name, i.Department 
    from Inserted i
    Left Join Employee e
    on i.Name = e.Name and i.Department = e.Department
    where e.Name is null
End

How to make Bootstrap 4 cards the same height in card-columns?

Most minimal way to achieve this (that I know of):

  • Apply .text-monospace to all texts in in the card.
  • Limit all texts in the cards to same number of characters.

UPDATE

Add .text-truncate in the card's title and or other texts. This forces texts to a single line. Making the cards have same height.

How do I monitor the computer's CPU, memory, and disk usage in Java?

/* YOU CAN TRY THIS TOO */

import java.io.File;
 import java.lang.management.ManagementFactory;
// import java.lang.management.OperatingSystemMXBean;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.lang.management.RuntimeMXBean;
 import java.io.*;
 import java.net.*;
 import java.util.*;
 import java.io.LineNumberReader;
 import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;
import java.util.Random;



 public class Pragati
 {

     public static void printUsage(Runtime runtime)
     {
     long total, free, used;
     int mb = 1024*1024;

     total = runtime.totalMemory();
     free = runtime.freeMemory();
     used = total - free;
     System.out.println("\nTotal Memory: " + total / mb + "MB");
     System.out.println(" Memory Used: " + used / mb + "MB");
     System.out.println(" Memory Free: " + free / mb + "MB");
     System.out.println("Percent Used: " + ((double)used/(double)total)*100 + "%");
     System.out.println("Percent Free: " + ((double)free/(double)total)*100 + "%");
    }
    public static void log(Object message)
         {
            System.out.println(message);
         }

        public static int calcCPU(long cpuStartTime, long elapsedStartTime, int cpuCount)
        {
             long end = System.nanoTime();
             long totalAvailCPUTime = cpuCount * (end-elapsedStartTime);
             long totalUsedCPUTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime()-cpuStartTime;
             //log("Total CPU Time:" + totalUsedCPUTime + " ns.");
             //log("Total Avail CPU Time:" + totalAvailCPUTime + " ns.");
             float per = ((float)totalUsedCPUTime*100)/(float)totalAvailCPUTime;
             log( per);
             return (int)per;
        }

        static boolean isPrime(int n)
        {
     // 2 is the smallest prime
            if (n <= 2)
            {
                return n == 2;
            }
     // even numbers other than 2 are not prime
            if (n % 2 == 0)
            {
                return false;
            }
     // check odd divisors from 3
     // to the square root of n
         for (int i = 3, end = (int)Math.sqrt(n); i <= end; i += 2)
         {
            if (n % i == 0)
         {
         return false;
        }
        }
 return true;
}
    public static void main(String [] args)
    {
            int mb = 1024*1024;
            int gb = 1024*1024*1024;
             /* PHYSICAL MEMORY USAGE */
             System.out.println("\n**** Sizes in Mega Bytes ****\n");
            com.sun.management.OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean();
            //RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
            //operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
            com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean)
            java.lang.management.ManagementFactory.getOperatingSystemMXBean();
            long physicalMemorySize = os.getTotalPhysicalMemorySize();
            System.out.println("PHYSICAL MEMORY DETAILS \n");
            System.out.println("total physical memory : " + physicalMemorySize / mb + "MB ");
            long physicalfreeMemorySize = os.getFreePhysicalMemorySize();
            System.out.println("total free physical memory : " + physicalfreeMemorySize / mb + "MB");
            /* DISC SPACE DETAILS */
            File diskPartition = new File("C:");
            File diskPartition1 = new File("D:");
            File diskPartition2 = new File("E:");
            long totalCapacity = diskPartition.getTotalSpace() / gb;
            long totalCapacity1 = diskPartition1.getTotalSpace() / gb;
            double freePartitionSpace = diskPartition.getFreeSpace() / gb;
            double freePartitionSpace1 = diskPartition1.getFreeSpace() / gb;
            double freePartitionSpace2 = diskPartition2.getFreeSpace() / gb;
            double usablePatitionSpace = diskPartition.getUsableSpace() / gb;
            System.out.println("\n**** Sizes in Giga Bytes ****\n");
            System.out.println("DISC SPACE DETAILS \n");
            //System.out.println("Total C partition size : " + totalCapacity + "GB");
            //System.out.println("Usable Space : " + usablePatitionSpace + "GB");
            System.out.println("Free Space in drive C: : " + freePartitionSpace + "GB");
            System.out.println("Free Space in drive D:  : " + freePartitionSpace1 + "GB");
            System.out.println("Free Space in drive E: " + freePartitionSpace2 + "GB");
            if(freePartitionSpace <= totalCapacity%10 || freePartitionSpace1 <= totalCapacity1%10)
            {
                System.out.println(" !!!alert!!!!");
            }
            else
                System.out.println("no alert");

            Runtime runtime;
            byte[] bytes;
            System.out.println("\n \n**MEMORY DETAILS  ** \n");
            // Print initial memory usage.
            runtime = Runtime.getRuntime();
            printUsage(runtime);

            // Allocate a 1 Megabyte and print memory usage
            bytes = new byte[1024*1024];
            printUsage(runtime);

            bytes = null;
            // Invoke garbage collector to reclaim the allocated memory.
            runtime.gc();

            // Wait 5 seconds to give garbage collector a chance to run
            try {
            Thread.sleep(5000);
            } catch(InterruptedException e) {
            e.printStackTrace();
            return;
            }

            // Total memory will probably be the same as the second printUsage call,
            // but the free memory should be about 1 Megabyte larger if garbage
            // collection kicked in.
            printUsage(runtime);
            for(int i = 0; i < 30; i++)
                     {
                         long start = System.nanoTime();
                        // log(start);
                        //number of available processors;
                         int cpuCount = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
                         Random random = new Random(start);
                         int seed = Math.abs(random.nextInt());
                         log("\n \n CPU USAGE DETAILS \n\n");
                         log("Starting Test with " + cpuCount + " CPUs and random number:" + seed);
                         int primes = 10000;
                         //
                         long startCPUTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();
                         start = System.nanoTime();
                         while(primes != 0)
                         {
                            if(isPrime(seed))
                            {
                                primes--;
                            }
                            seed++;

                        }
                         float cpuPercent = calcCPU(startCPUTime, start, cpuCount);
                         log("CPU USAGE : " + cpuPercent + " % ");


                         try
                         {
                             Thread.sleep(1000);
                         }
                         catch (InterruptedException e) {}
        }

            try
            {
                Thread.sleep(500);
            }`enter code here`
            catch (Exception ignored) { }
        }
    }

How do you format code on save in VS Code

If you would like to auto format on save just with Javascript source, add this one into Users Setting (press Cmd, or Ctrl,):

"[javascript]": { "editor.formatOnSave": true }

How often does python flush to a file?

You can also check the default buffer size by calling the read only DEFAULT_BUFFER_SIZE attribute from io module.

import io
print (io.DEFAULT_BUFFER_SIZE)

Set height 100% on absolute div

Another solution without using any height but still fills 100% available height. Checkout this e.g on the codepen. http://codepen.io/gauravshankar/pen/PqoLLZ

For this html and body should have 100% height. This height is equal to the viewport height.

Make inner div position absolute and give top and bottom 0. This fills the div to available height. (height equal to body.)

html code:

<head></head>

<body>
  <div></div>
</body>

</html>

css code:

* {
  margin: 0;
  padding: 0;
}

html,
body {
  height: 100%;
  position: relative;
}

html {
  background-color: red;
}

body {
  background-color: green;
}

body> div {
  position: absolute;
  background-color: teal;
  width: 300px;
  top: 0;
  bottom: 0;
}

How to run .sql file in Oracle SQL developer tool to import database?

As others recommend, you can use Oracle SQL Developer. You can point to the location of the script to run it, as described. A slightly simpler method, though, is to just use drag-and-drop:

  • Click and drag your .sql file over to Oracle SQL Developer
  • The contents will appear in a "SQL Worksheet"
  • Click "Run Script" button, or hit F5, to run

enter image description here

How can I check whether a numpy array is empty or not?

Why would we want to check if an array is empty? Arrays don't grow or shrink in the same that lists do. Starting with a 'empty' array, and growing with np.append is a frequent novice error.

Using a list in if alist: hinges on its boolean value:

In [102]: bool([])                                                                       
Out[102]: False
In [103]: bool([1])                                                                      
Out[103]: True

But trying to do the same with an array produces (in version 1.18):

In [104]: bool(np.array([]))                                                             
/usr/local/bin/ipython3:1: DeprecationWarning: The truth value 
   of an empty array is ambiguous. Returning False, but in 
   future this will result in an error. Use `array.size > 0` to 
   check that an array is not empty.
  #!/usr/bin/python3
Out[104]: False

In [105]: bool(np.array([1]))                                                            
Out[105]: True

and bool(np.array([1,2]) produces the infamous ambiguity error.

edit

The accepted answer suggests size:

In [11]: x = np.array([])
In [12]: x.size
Out[12]: 0

But I (and most others) check the shape more than the size:

In [13]: x.shape
Out[13]: (0,)

Another thing in its favor is that it 'maps' on to an empty list:

In [14]: x.tolist()
Out[14]: []

But there are other other arrays with 0 size, that aren't 'empty' in that last sense:

In [15]: x = np.array([[]])
In [16]: x.size
Out[16]: 0
In [17]: x.shape
Out[17]: (1, 0)
In [18]: x.tolist()
Out[18]: [[]]
In [19]: bool(x.tolist())
Out[19]: True

np.array([[],[]]) is also size 0, but shape (2,0) and len 2.

While the concept of an empty list is well defined, an empty array is not well defined. One empty list is equal to another. The same can't be said for a size 0 array.

The answer really depends on

  • what do you mean by 'empty'?
  • what are you really test for?

Regex match text between tags

Try

str.match(/<b>(.*?)<\/b>/g);

React Js conditionally applying class attributes

<div className={['foo', condition && 'bar'].filter(Boolean).join(' ')} />

.filter(Boolean) removes "falsey" values from the array. Since class names must be strings, anything other than that would not be included in the new filtered array.

_x000D_
_x000D_
console.log(  ['foo', true  && 'bar'].filter(Boolean).join(' ')  )
console.log(  ['foo', false && 'bar'].filter(Boolean).join(' ')  )
_x000D_
_x000D_
_x000D_

Above written as a function:

const cx = (...list) => list.filter(Boolean).join(' ')

// usage:
<div className={cx('foo', condition && 'bar')} />

_x000D_
_x000D_
var cx = (...list) => list.filter(Boolean).join(' ')
console.log(  cx('foo', 1 && 'bar', 1 && 'baz')  )
console.log(  cx('foo', 0 && 'bar', 1 && 'baz')  )
console.log(  cx('foo', 0 && 'bar', 0 && 'baz')  )
_x000D_
_x000D_
_x000D_

Javascript dynamic array of strings

Just initialize an array and push the element on the array. It will automatic scale the array.

var a = [ ];

a.push('Some string'); console.log(a); // ['Some string'] 
a.push('another string'); console.log(a); // ['Some string', 'another string'] 
a.push('Some string'); console.log(a); // ['Some string', 'another string', 'Some string']

Facebook development in localhost

With the new development center it is now easier:

1) Leave app domains blank.
2) Click Add Platform
3) Site URL should equal the full path of your local host.
4) Save Changes

Xcode 6.1 Missing required architecture X86_64 in file

If you are having this problem in react-native projects with one of the external library. You should remove the project and use react-native link <package-name> again. That should solve the problem.

How to filter a RecyclerView with a SearchView

This is my take on expanding @klimat answer to not losing filtering animation.

public void filter(String query){
    int completeListIndex = 0;
    int filteredListIndex = 0;
    while (completeListIndex < completeList.size()){
        Movie item = completeList.get(completeListIndex);
        if(item.getName().toLowerCase().contains(query)){
            if(filteredListIndex < filteredList.size()) {
                Movie filter = filteredList.get(filteredListIndex);
                if (!item.getName().equals(filter.getName())) {
                    filteredList.add(filteredListIndex, item);
                    notifyItemInserted(filteredListIndex);
                }
            }else{
                filteredList.add(filteredListIndex, item);
                notifyItemInserted(filteredListIndex);
            }
            filteredListIndex++;
        }
        else if(filteredListIndex < filteredList.size()){
            Movie filter = filteredList.get(filteredListIndex);
            if (item.getName().equals(filter.getName())) {
                filteredList.remove(filteredListIndex);
                notifyItemRemoved(filteredListIndex);
            }
        }
        completeListIndex++;
    }
}

Basically what it does is looking through a complete list and adding/removing items to a filtered list one by one.

Windows Batch: How to add Host-Entries?

Sometime I have to work from home and connect to office through vpn. Internal domain names should be resolved to different IPs at home. There are several names that have to be changed between office and home. For example:

At office, a => 192.168.0.3, b => 192.168.0.52. 
At home, a => 10.6.1.7, b => 10.4.5.23. 

My solution is to create two files: C:\WINDOWS\system32\drivers\etc\hosts-home and C:\WINDOWS\system32\drivers\etc\hosts-office. Each of them contains set of name-to-IP mapping. From Administrator PowerShell, When I work at the office, execute

C:\WINDOWS\system32> cp .\drivers\etc\hosts-office .\drivers\etc\hosts

When I arrive at home, execute

C:\WINDOWS\system32> cp .\drivers\etc\hosts-home .\drivers\etc\hosts

Uncaught ReferenceError: jQuery is not defined

In my case, the error occurred because I was using the wrong version of jquery.

<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

I changed it to:

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

Java java.sql.SQLException: Invalid column index on preparing statement

As @TechSpellBound suggested remove the quotes around the ? signs. Then add a space character at the end of each row in your concatenated string. Otherwise the entire query will be sent as (using only part of it as an example) : .... WHERE bookings.booking_end < date ?OR bookings.booking_start > date ?GROUP BY ....

The ? and the OR needs to be seperated by a space character. Do it wherever needed in the query string.

Finding rows that don't contain numeric data in Oracle

I've found this useful:

 select translate('your string','_0123456789','_') from dual

If the result is NULL, it's numeric (ignoring floating point numbers.)

However, I'm a bit baffled why the underscore is needed. Without it the following also returns null:

 select translate('s123','0123456789', '') from dual

There is also one of my favorite tricks - not perfect if the string contains stuff like "*" or "#":

 SELECT 'is a number' FROM dual WHERE UPPER('123') = LOWER('123')

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

How to deserialize xml to object

Your classes should look like this

[XmlRoot("StepList")]
public class StepList
{
    [XmlElement("Step")]
    public List<Step> Steps { get; set; }
}

public class Step
{
    [XmlElement("Name")]
    public string Name { get; set; }
    [XmlElement("Desc")]
    public string Desc { get; set; }
}

Here is my testcode.

string testData = @"<StepList>
                        <Step>
                            <Name>Name1</Name>
                            <Desc>Desc1</Desc>
                        </Step>
                        <Step>
                            <Name>Name2</Name>
                            <Desc>Desc2</Desc>
                        </Step>
                    </StepList>";

XmlSerializer serializer = new XmlSerializer(typeof(StepList));
using (TextReader reader = new StringReader(testData))
{
    StepList result = (StepList) serializer.Deserialize(reader);
}

If you want to read a text file you should load the file into a FileStream and deserialize this.

using (FileStream fileStream = new FileStream("<PathToYourFile>", FileMode.Open)) 
{
    StepList result = (StepList) serializer.Deserialize(fileStream);
}

Using IF ELSE in Oracle

IF is a PL/SQL construct. If you are executing a query, you are using SQL not PL/SQL.

In SQL, you can use a CASE statement in the query itself

SELECT DISTINCT a.item, 
                (CASE WHEN b.salesman = 'VIKKIE'
                      THEN 'ICKY'
                      ELSE b.salesman
                  END), 
                NVL(a.manufacturer,'Not Set') Manufacturer
  FROM inv_items a, 
       arv_sales b
 WHERE  a.co = '100'
   AND a.co = b.co
   AND A.ITEM_KEY = b.item_key   
   AND a.item LIKE 'BX%'
   AND b.salesman in ('01','15')
   AND trans_date BETWEEN to_date('010113','mmddrr')
                      and to_date('011713','mmddrr')
ORDER BY a.item

Since you aren't doing any aggregation, you don't want a GROUP BY in your query. Are you really sure that you need the DISTINCT? People often throw that in haphazardly or add it when they are missing a join condition rather than considering whether it is really necessary to do the extra work to identify and remove duplicates.

What should be the values of GOPATH and GOROOT?

Once Go lang is installed, GOROOT is the root directory of the installation.

When I exploded Go Lang binary in Windows C:\ directory, my GOROOT should be C:\go. If Installed with Windows installer, it may be C:\Program Files\go (or C:\Program Files (x86)\go, for 64-bit packages)

 GOROOT = C:\go

while my GOPATH is location of Go lang source code or workspace.

If my Go lang source code is located at C:\Users\\GO_Workspace, your GOPATH would be as below:

 GOPATH = C:\Users\<xyz>\GO_Workspace

Most useful NLog configurations

Some of these fall into the category of general NLog (or logging) tips rather than strictly configuration suggestions.

Here are some general logging links from here at SO (you might have seen some or all of these already):

log4net vs. Nlog

Logging best practices

What's the point of a logging facade?

Why do loggers recommend using a logger per class?

Use the common pattern of naming your logger based on the class Logger logger = LogManager.GetCurrentClassLogger(). This gives you a high degree of granularity in your loggers and gives you great flexibility in the configuration of the loggers (control globally, by namespace, by specific logger name, etc).

Use non-classname-based loggers where appropriate. Maybe you have one function for which you really want to control the logging separately. Maybe you have some cross-cutting logging concerns (performance logging).

If you don't use classname-based logging, consider naming your loggers in some kind of hierarchical structure (maybe by functional area) so that you can maintain greater flexibility in your configuration. For example, you might have a "database" functional area, an "analysis" FA, and a "ui" FA. Each of these might have sub-areas. So, you might request loggers like this:

Logger logger = LogManager.GetLogger("Database.Connect");
Logger logger = LogManager.GetLogger("Database.Query");
Logger logger = LogManager.GetLogger("Database.SQL");
Logger logger = LogManager.GetLogger("Analysis.Financial");
Logger logger = LogManager.GetLogger("Analysis.Personnel");
Logger logger = LogManager.GetLogger("Analysis.Inventory");

And so on. With hierarchical loggers, you can configure logging globally (the "*" or root logger), by FA (Database, Analysis, UI), or by subarea (Database.Connect, etc).

Loggers have many configuration options:

<logger name="Name.Space.Class1" minlevel="Debug" writeTo="f1" /> 
<logger name="Name.Space.Class1" levels="Debug,Error" writeTo="f1" /> 
<logger name="Name.Space.*" writeTo="f3,f4" />
<logger name="Name.Space.*" minlevel="Debug" maxlevel="Error" final="true" /> 

See the NLog help for more info on exactly what each of the options means. Probably the most notable items here are the ability to wildcard logger rules, the concept that multiple logger rules can "execute" for a single logging statement, and that a logger rule can be marked as "final" so subsequent rules will not execute for a given logging statement.

Use the GlobalDiagnosticContext, MappedDiagnosticContext, and NestedDiagnosticContext to add additional context to your output.

Use "variable" in your config file to simplify. For example, you might define variables for your layouts and then reference the variable in the target configuration rather than specify the layout directly.

  <variable name="brief" value="${longdate} | ${level} | ${logger} | ${message}"/>
  <variable name="verbose" value="${longdate} | ${machinename} | ${processid} | ${processname} | ${level} | ${logger} | ${message}"/>
  <targets>
    <target name="file" xsi:type="File" layout="${verbose}" fileName="${basedir}/${shortdate}.log" />
    <target name="console" xsi:type="ColoredConsole" layout="${brief}" />
  </targets>

Or, you could create a "custom" set of properties to add to a layout.

  <variable name="mycontext" value="${gdc:item=appname} , ${mdc:item=threadprop}"/>
  <variable name="fmt1withcontext" value="${longdate} | ${level} | ${logger} | [${mycontext}] |${message}"/>
  <variable name="fmt2withcontext" value="${shortdate} | ${level} | ${logger} | [${mycontext}] |${message}"/>

Or, you can do stuff like create "day" or "month" layout renderers strictly via configuration:

  <variable name="day" value="${date:format=dddd}"/>
  <variable name="month" value="${date:format=MMMM}"/>
  <variable name="fmt" value="${longdate} | ${level} | ${logger} | ${day} | ${month} | ${message}"/>
  <targets>
    <target name="console" xsi:type="ColoredConsole" layout="${fmt}" />
  </targets>

You can also use layout renders to define your filename:

  <variable name="day" value="${date:format=dddd}"/>
  <targets>
    <target name="file" xsi:type="File" layout="${verbose}" fileName="${basedir}/${day}.log" />
  </targets>

If you roll your file daily, each file could be named "Monday.log", "Tuesday.log", etc.

Don't be afraid to write your own layout renderer. It is easy and allows you to add your own context information to the log file via configuration. For example, here is a layout renderer (based on NLog 1.x, not 2.0) that can add the Trace.CorrelationManager.ActivityId to the log:

  [LayoutRenderer("ActivityId")]
  class ActivityIdLayoutRenderer : LayoutRenderer
  {
    int estimatedSize = Guid.Empty.ToString().Length;

    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
      builder.Append(Trace.CorrelationManager.ActivityId);
    }

    protected override int GetEstimatedBufferSize(LogEventInfo logEvent)
    {
      return estimatedSize;
    }
  }

Tell NLog where your NLog extensions (what assembly) like this:

  <extensions>
    <add assembly="MyNLogExtensions"/>
  </extensions>

Use the custom layout renderer like this:

  <variable name="fmt" value="${longdate} | ${ActivityId} | ${message}"/>

Use async targets:

<nlog>
  <targets async="true">
    <!-- all targets in this section will automatically be asynchronous -->
  </targets>
</nlog>

And default target wrappers:

<nlog>  
  <targets>  
    <default-wrapper xsi:type="BufferingWrapper" bufferSize="100"/>  
    <target name="f1" xsi:type="File" fileName="f1.txt"/>  
    <target name="f2" xsi:type="File" fileName="f2.txt"/>  
  </targets>  
  <targets>  
    <default-wrapper xsi:type="AsyncWrapper">  
      <wrapper xsi:type="RetryingWrapper"/>  
    </default-wrapper>  
    <target name="n1" xsi:type="Network" address="tcp://localhost:4001"/>  
    <target name="n2" xsi:type="Network" address="tcp://localhost:4002"/>  
    <target name="n3" xsi:type="Network" address="tcp://localhost:4003"/>  
  </targets>  
</nlog>

where appropriate. See the NLog docs for more info on those.

Tell NLog to watch and automatically reload the configuration if it changes:

<nlog autoReload="true" /> 

There are several configuration options to help with troubleshooting NLog

<nlog throwExceptions="true" />
<nlog internalLogFile="file.txt" />
<nlog internalLogLevel="Trace|Debug|Info|Warn|Error|Fatal" />
<nlog internalLogToConsole="false|true" />
<nlog internalLogToConsoleError="false|true" />

See NLog Help for more info.

NLog 2.0 adds LayoutRenderer wrappers that allow additional processing to be performed on the output of a layout renderer (such as trimming whitespace, uppercasing, lowercasing, etc).

Don't be afraid to wrap the logger if you want insulate your code from a hard dependency on NLog, but wrap correctly. There are examples of how to wrap in the NLog's github repository. Another reason to wrap might be that you want to automatically add specific context information to each logged message (by putting it into LogEventInfo.Context).

There are pros and cons to wrapping (or abstracting) NLog (or any other logging framework for that matter). With a little effort, you can find plenty of info here on SO presenting both sides.

If you are considering wrapping, consider using Common.Logging. It works pretty well and allows you to easily switch to another logging framework if you desire to do so. Also if you are considering wrapping, think about how you will handle the context objects (GDC, MDC, NDC). Common.Logging does not currently support an abstraction for them, but it is supposedly in the queue of capabilities to add.

How to insert &nbsp; in XSLT

When you use the following (without disable-output-escaping!) you'll get a single non-breaking space:

<xsl:text>&#160;</xsl:text>

How do you know a variable type in java?

I would like to expand on Martin's answer there...

His solution is rather nice, but it can be tweaked so any "variable type" can be printed like that.(It's actually Value Type, more on the topic). That said, "tweaked" may be a strong word for this. Regardless, it may be helpful.

Martins Solution:

a.getClass().getName()

However, If you want it to work with anything you can do this:

((Object) myVar).getClass().getName()
//OR
((Object) myInt).getClass().getSimpleName()

In this case, the primitive will simply be wrapped in a Wrapper. You will get the Object of the primitive in that case.

I myself used it like this:

private static String nameOf(Object o) {
    return o.getClass().getSimpleName();
}

Using Generics:

public static <T> String nameOf(T o) {
    return o.getClass().getSimpleName();
}

Text blinking jQuery

You can also use the standard CSS way (no need for JQuery plugin, but compatible with all browsers):

// Start blinking
$(".myblink").css("text-decoration", "blink");

// Stop blinking
$(".myblink").css("text-decoration", "none");

W3C Link

Git: Pull from other remote

upstream in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add. Depending on what you select for this name, your git pull usage will change. For example, if you use:

git remote add upstream git://github.com/somename/original-project.git

then you would use this to pull changes:

git pull upstream master

But, if you choose origin for the name of the remote repo, your commands would be:

To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git

And to pull: git pull origin master

difference between width auto and width 100 percent

When we say

width:auto;

width will never exceed the total width of parent element. Maximum width is it's parent width. Even if we add border, padding and margin, content of element itself will become smaller in order to give space for border, padding and margin. In case if space required for border + padding + margin is greater than total width of parent element then width of content will become zero.

When we say

width:100%;

width of content of element will become 100% of parent element and from now if we add border, padding or margin then it will cause child element to exceed parent element's width and it will starts overflowing out of parent element.

Create a button with rounded border

Use StadiumBorder shape

              OutlineButton(
                onPressed: () {},
                child: Text("Follow"),
                borderSide: BorderSide(color: Colors.blue),
                shape: StadiumBorder(),
              )

How to use onClick event on react Link component?

I don't believe this is a good pattern to use in general. Link will run your onClick event and then navigate to the route, so there will be a slight delay navigating to the new route. A better strategy is to navigate to the new route with the 'to' prop as you have done, and in the new component's componentDidMount() function you can fire your hello function or any other function. It will give you the same result, but with a much smoother transition between routes.

For context, I noticed this while updating my redux store with an onClick event on Link like you have here, and it caused a ~.3 second blank-white-screen delay before mounting the new route's component. There was no api call involved, so I was surprised the delay was so big. However, if you're just console logging 'hello' the delay might not be noticeable.

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:

BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib

MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)

Replace whole line containing a string using Sed

Below command is working for me. Which is working with variables

sed -i "/\<$E\>/c $D" "$B"

Runtime vs. Compile time

Compile-time: the time period in which you, the developer, are compiling your code.

Run-time: the time period which a user is running your piece of software.

Do you need any clearer definition?

Java - Abstract class to contain variables?

Sure.. Why not?
Abstract base classes are just a convenience to house behavior and data common to 2 or more classes in a single place for efficiency of storage and maintenance. Its an implementation detail.
Take care however that you are not using an abstract base class where you should be using an interface. Refer to Interface vs Base class

How to Generate a random number of fixed length using JavaScript?

I use randojs to make the randomness simpler and more readable. you can pick a random int between 100000 and 999999 like this with randojs:

_x000D_
_x000D_
console.log(rando(100000, 999999));
_x000D_
<script src="https://randojs.com/1.0.0.js"></script>
_x000D_
_x000D_
_x000D_

Possible to perform cross-database queries with PostgreSQL?

Yes, you can by using DBlink (postgresql only) and DBI-Link (allows foreign cross database queriers) and TDS_LInk which allows queries to be run against MS SQL server.

I have used DB-Link and TDS-link before with great success.

How to extract an assembly from the GAC?

From a Powershell script, you can try this. I only had a single version of the assembly in the GAC so this worked just fine.

cd "c:\Windows\Microsoft.NET\assembly\GAC_MSIL\"
Get-ChildItem assemblypath -Recurse -Include *.dll |  Copy-Item -Destination "c:\folder to copy to"

where the assembly path can use wildcards.

How to convert seconds to time format?

Maybe the simplest way is:

gmdate('H:i:s', $your_time_in_seconds);

Stop fixed position at footer

Here is the @Sang solution but without Jquery.

_x000D_
_x000D_
var socialFloat = document.querySelector('#social-float');_x000D_
var footer = document.querySelector('#footer');_x000D_
_x000D_
function checkOffset() {_x000D_
  function getRectTop(el){_x000D_
    var rect = el.getBoundingClientRect();_x000D_
    return rect.top;_x000D_
  }_x000D_
  _x000D_
  if((getRectTop(socialFloat) + document.body.scrollTop) + socialFloat.offsetHeight >= (getRectTop(footer) + document.body.scrollTop) - 10)_x000D_
    socialFloat.style.position = 'absolute';_x000D_
  if(document.body.scrollTop + window.innerHeight < (getRectTop(footer) + document.body.scrollTop))_x000D_
    socialFloat.style.position = 'fixed'; // restore when you scroll up_x000D_
  _x000D_
  socialFloat.innerHTML = document.body.scrollTop + window.innerHeight;_x000D_
}_x000D_
_x000D_
document.addEventListener("scroll", function(){_x000D_
  checkOffset();_x000D_
});
_x000D_
div.social-float-parent { width: 100%; height: 1000px; background: #f8f8f8; position: relative; }_x000D_
div#social-float { width: 200px; position: fixed; bottom: 10px; background: #777; }_x000D_
div#footer { width: 100%; height: 200px; background: #eee; }
_x000D_
<div class="social-float-parent">_x000D_
    <div id="social-float">_x000D_
        float..._x000D_
    </div>_x000D_
</div>_x000D_
<div id="footer">_x000D_
</div>
_x000D_
_x000D_
_x000D_

What's the advantage of a Java enum versus a class with public static final fields?

The biggest advantage is enum Singletons are easy to write and thread-safe :

public enum EasySingleton{
    INSTANCE;
}

and

/**
* Singleton pattern example with Double checked Locking
*/
public class DoubleCheckedLockingSingleton{
     private volatile DoubleCheckedLockingSingleton INSTANCE;

     private DoubleCheckedLockingSingleton(){}

     public DoubleCheckedLockingSingleton getInstance(){
         if(INSTANCE == null){
            synchronized(DoubleCheckedLockingSingleton.class){
                //double checking Singleton instance
                if(INSTANCE == null){
                    INSTANCE = new DoubleCheckedLockingSingleton();
                }
            }
         }
         return INSTANCE;
     }
}

both are similar and it handled Serialization by themselves by implementing

//readResolve to prevent another instance of Singleton
    private Object readResolve(){
        return INSTANCE;
    }

more

How to set the part of the text view is clickable

To add a linked text in a text view, you can use the "footer_text" string resource example below and also edit your onCreate method for your activity, you can use the example below

string.xml

<?xml version="1.0" charset="utf-8"?>
<resources>
     <string name="app_name">Name of My Application</string>

    <string name="footer_text">
        <a href="https://www.google.com/tos">Terms of Service</a>
        <a href="https://www.google.com/contact">Contact</a>
        <a href="https://www.google.com/privacy">Privacy Policy</a>
    </string>
</resources>

MainActivity.java

...

@Override
public void onCreate(Bundle savedInstance) {
    super.onCreate(savedInstance);
    setContentView(R.layout.activity_main);

    TextView textView = findViewById(R.id.textViewLink);
    textView.setMovementMethod(LinkMovermentMethod.getInstance());
}

....

How to animate a View with Translate Animation in Android

In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.

You can try this sample code:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" android:id="@+id/rootLayout">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MOVE" android:layout_centerHorizontal="true"/>

    <ImageView
        android:id="@+id/img1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
    <ImageView
        android:id="@+id/img2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
    <ImageView
        android:id="@+id/img3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">

        <ImageView
            android:id="@+id/img4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
    </LinearLayout>

</RelativeLayout>

Your activity

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            ImageView img = (ImageView) findViewById( R.id.img1 );              
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img2 );
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img3 );                
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img4 );
            moveViewToScreenCenter( img );
        }
    });
}

private void moveViewToScreenCenter( View view )
{
    RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
    DisplayMetrics dm = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics( dm );
    int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();

    int originalPos[] = new int[2];
    view.getLocationOnScreen( originalPos );

    int xDest = dm.widthPixels/2;
    xDest -= (view.getMeasuredWidth()/2);
    int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;

    TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
    anim.setDuration(1000);
    anim.setFillAfter( true );
    view.startAnimation(anim);
}

The method moveViewToScreenCenter gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset variable measures the status bar height.

I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.

How to open an Excel file in C#?

Is this a commercial application or some hobbyist / open source software?

I'm asking this because in my experience, all free .NET Excel handling alternatives have serious problems, for different reasons. For hobbyist things, I usually end up porting jExcelApi from Java to C# and using it.

But if this is a commercial application, you would be better off by purchasing a third party library, like Aspose.Cells. Believe me, it totally worths it as it saves a lot of time and time ain't free.

Select row with most recent date per user

Query:

SQLFIDDLEExample

SELECT t1.*
FROM lms_attendance t1
WHERE t1.time = (SELECT MAX(t2.time)
                 FROM lms_attendance t2
                 WHERE t2.user = t1.user)

Result:

| ID | USER |       TIME |  IO |
--------------------------------
|  2 |    9 | 1370931664 | out |
|  3 |    6 | 1370932128 | out |
|  5 |   12 | 1370933037 |  in |

Solution which gonna work everytime:

SQLFIDDLEExample

SELECT t1.*
FROM lms_attendance t1
WHERE t1.id = (SELECT t2.id
                 FROM lms_attendance t2
                 WHERE t2.user = t1.user            
                 ORDER BY t2.id DESC
                 LIMIT 1)

Remove quotes from a character vector in R

There are no quotes in the return value, only in the default output from print() when you display the value. Try

> print(char[1], quote=FALSE)
[1] one

or

> cat(char[1], "\n")
one

to see the value without quotes.

I want to use CASE statement to update some records in sql server 2005

Add a WHERE clause

UPDATE dbo.TestStudents  
SET     LASTNAME =  CASE  
                        WHEN LASTNAME = 'AAA' THEN 'BBB' 
                        WHEN LASTNAME = 'CCC' THEN 'DDD' 
                        WHEN LASTNAME = 'EEE' THEN 'FFF' 
                        ELSE LASTNAME
                    END 
WHERE   LASTNAME IN ('AAA', 'CCC', 'EEE')

Subset data to contain only columns whose names match a condition

Using dplyr you can:

df <- df %>% dplyr:: select(grep("ABC", names(df)), grep("XYZ", names(df)))

correct way to define class variables in Python

Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:

  • Elements outside the __init__ method are static elements; they belong to the class.
  • Elements inside the __init__ method are elements of the object (self); they don't belong to the class.

You'll see it more clearly with some code:

class MyClass:
    static_elem = 123

    def __init__(self):
        self.object_elem = 456

c1 = MyClass()
c2 = MyClass()

# Initial values of both elements
>>> print c1.static_elem, c1.object_elem 
123 456
>>> print c2.static_elem, c2.object_elem
123 456

# Nothing new so far ...

# Let's try changing the static element
MyClass.static_elem = 999

>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456

# Now, let's try changing the object element
c1.object_elem = 888

>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456

As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.

Is there any difference between "!=" and "<>" in Oracle Sql?

No there is no difference at all in functionality.
(The same is true for all other DBMS - most of them support both styles):

Here is the current SQL reference: https://docs.oracle.com/database/121/SQLRF/conditions002.htm#CJAGAABC

The SQL standard only defines a single operator for "not equals" and that is <>

Why I get 'list' object has no attribute 'items'?

More generic way in case qs has more than one dictionaries:

[int(v) for lst in qs for k, v in lst.items()]

--

>>> qs = [{u'a': 15L, u'b': 9L, u'a': 16L}, {u'a': 20, u'b': 35}]
>>> result_list = [int(v) for lst in qs for k, v in lst.items()]
>>> result_list
[16, 9, 20, 35]

IIS 7, HttpHandler and HTTP Error 500.21

It's not possible to configure an IIS managed handler to run in classic mode. You should be running IIS in integrated mode if you want to do that.

You can learn more about modules, handlers and IIS modes in the following blog post:

IIS 7.0, ASP.NET, pipelines, modules, handlers, and preconditions

For handlers, if you set preCondition="integratedMode" in the mapping, the handler will only run in integrated mode. On the other hand, if you set preCondition="classicMode" the handler will only run in classic mode. And if you omit both of these, the handler can run in both modes, although this is not possible for a managed handler.

Convert all first letter to upper case, rest lower for each word

One of the possible solution you might be interested in. Traversing an array of chars from right to left and vise versa in one loop.

public static string WordsToCapitalLetter(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            throw new ArgumentException("value");
        }

        int inputValueCharLength = value.Length;
        var valueAsCharArray = value.ToCharArray();

        int min = 0;
        int max = inputValueCharLength - 1;

        while (max > min)
        {
            char left = value[min];
            char previousLeft = (min == 0) ? left : value[min - 1];

            char right = value[max];
            char nextRight = (max == inputValueCharLength - 1) ? right : value[max - 1];

            if (char.IsLetter(left) && !char.IsUpper(left) && char.IsWhiteSpace(previousLeft))
            {
                valueAsCharArray[min] = char.ToUpper(left);
            }

            if (char.IsLetter(right) && !char.IsUpper(right) && char.IsWhiteSpace(nextRight))
            {
                valueAsCharArray[max] = char.ToUpper(right);
            }

            min++;
            max--;
        }

        return new string(valueAsCharArray);
    }

Adding a directory to PATH in Ubuntu

you can set it in .bashrc

PATH=$PATH:/opt/ActiveTcl-8.5/bin;export PATH;

How to iterate over a JavaScript object?

If you want the key and value when iterating, you can use a for...of loop with Object.entries.

const myObj = {a: 1, b: 2}

for (let [key, value] of Object.entries(myObj)) {
    console.log(`key=${key} value=${value}`)
}

// output: 
// key=a value=1
// key=b value=2

m2eclipse not finding maven dependencies, artifacts not found

Okay I fixed this thing. Had to first convert the projects to Maven Projects, then remove them from the Eclipse workspace, and then re-import them.

Spring MVC: how to create a default controller for index page?

The redirect is one option. One thing you can try is to create a very simple index page that you place at the root of the WAR which does nothing else but redirecting to your controller like

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:redirect url="/welcome.html"/>

Then you map your controller with that URL with something like

@Controller("loginController")
@RequestMapping(value = "/welcome.html")
public class LoginController{
...
}

Finally, in web.xml, to have your (new) index JSP accessible, declare

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

Simply cleaning the project solved it for me.

My project is a C++ application (not a shared library). I randomly got this error after a lot of successful builds.

How to get the currently logged in user's user id in Django?

First make sure you have SessionMiddleware and AuthenticationMiddleware middlewares added to your MIDDLEWARE_CLASSES setting.

The current user is in request object, you can get it by:

def sample_view(request):
    current_user = request.user
    print current_user.id

request.user will give you a User object representing the currently logged-in user. If a user isn't currently logged in, request.user will be set to an instance of AnonymousUser. You can tell them apart with the field is_authenticated, like so:

if request.user.is_authenticated:
    # Do something for authenticated users.
else:
    # Do something for anonymous users.

Getting attributes of Enum's value

Alternatively, you could do the following:

Dictionary<FunkyAttributesEnum, string> description = new Dictionary<FunkyAttributesEnum, string>()
    {
      { FunkyAttributesEnum.NameWithoutSpaces1, "Name With Spaces1" },
      { FunkyAttributesEnum.NameWithoutSpaces2, "Name With Spaces2" },
    };

And get the description with the following:

string s = description[FunkyAttributesEnum.NameWithoutSpaces1];

In my opinion this is a more efficient way of doing what you want to accomplish, as no reflection is needed..

React js change child component's state from parent component

The parent component can manage child state passing a prop to child and the child convert this prop in state using componentWillReceiveProps.

class ParentComponent extends Component {
  state = { drawerOpen: false }
  toggleChildMenu = () => {
    this.setState({ drawerOpen: !this.state.drawerOpen })
  }
  render() {
    return (
      <div>
        <button onClick={this.toggleChildMenu}>Toggle Menu from Parent</button>
        <ChildComponent drawerOpen={this.state.drawerOpen} />
      </div>
    )
  }
}

class ChildComponent extends Component {
  constructor(props) {
    super(props)
    this.state = {
      open: false
    }
  }

  componentWillReceiveProps(props) {
    this.setState({ open: props.drawerOpen })
  }

  toggleMenu() {
    this.setState({
      open: !this.state.open
    })
  }

  render() {
    return <Drawer open={this.state.open} />
  }
}

JUnit Testing private variables?

Reflection e.g.:

public class PrivateObject {

  private String privateString = null;

  public PrivateObject(String privateString) {
    this.privateString = privateString;
  }
}
PrivateObject privateObject = new PrivateObject("The Private Value");

Field privateStringField = PrivateObject.class.
            getDeclaredField("privateString");

privateStringField.setAccessible(true);

String fieldValue = (String) privateStringField.get(privateObject);
System.out.println("fieldValue = " + fieldValue);

Vertically center text in a 100% height div?

just wrap your content with a table like this:

  <table width="100%" height="100%">
         <tr align="center">
               <th align="center">
                 text
               </th>
          </tr>
  </table><

How do you copy a record in a SQL table but swap out the unique id of the new row?

I know my answer is late to the party. But the way i solved is bit different than all the answers.

I had a situation, i need to clone a row in a table except few columns. Those few will have new values. This process should support automatically for future changes to the table. This implies, clone the record without specifying any column names.

My approach is to,

  1. Query Sys.Columns to get the full list of columns for the table and include the names of columns to skip in where clause.
  2. Convert that in to CSV as column names.
  3. Build Select ... Insert into script based on this.


declare @columnsToCopyValues varchar(max), @query varchar(max)
SET @columnsToCopyValues = ''

--Get all the columns execpt Identity columns and Other columns to be excluded. Say IndentityColumn, Column1, Column2 Select @columnsToCopyValues = @columnsToCopyValues + [name] + ', ' from sys.columns c where c.object_id = OBJECT_ID('YourTableName') and name not in ('IndentityColumn','Column1','Column2') Select @columnsToCopyValues = SUBSTRING(@columnsToCopyValues, 0, LEN(@columnsToCopyValues)) print @columnsToCopyValues

Select @query = CONCAT('insert into YourTableName (',@columnsToCopyValues,', Column1, Column2) select ', @columnsToCopyValues, ',''Value1'',''Value2'',', ' from YourTableName where IndentityColumn =''' , @searchVariable,'''')

print @query exec (@query)

C char array initialization

I'm not sure but I commonly initialize an array to "" in that case I don't need worry about the null end of the string.

main() {
    void something(char[]);
    char s[100] = "";

    something(s);
    printf("%s", s);
}

void something(char s[]) {
    // ... do something, pass the output to s
    // no need to add s[i] = '\0'; because all unused slot is already set to '\0'
}

What are the advantages of Sublime Text over Notepad++ and vice-versa?

One thing that should be considered is licensing.

Notepad++ is free (as in speech and as in beer) for perpetual use, released under the GPL license, whereas Sublime Text 2 requires a license.

To quote the Sublime Text 2 website:

..a license must be purchased for continued use. There is currently no enforced time limit for the evaluation.

The same is now true of Sublime Text 3, and a paid upgrade will be needed for future versions.

Upgrade Policy A license is valid for Sublime Text 3, and includes all point updates, as well as access to prior versions (e.g., Sublime Text 2). Future major versions, such as Sublime Text 4, will be a paid upgrade.

This licensing requirement is still correct as of Dec 2019.

How to check which PHP extensions have been enabled/disabled in Ubuntu Linux 12.04 LTS?

Checking for installed php modules and packages

In addition to running

php -m

to get the list of installed php modules, you will probably find it helpful to get the list of the currently installed php packages in Ubuntu:

sudo dpkg --get-selections | grep -v deinstall | grep php

This is helpful since Ubuntu makes php modules available via packages.

You can then install the needed modules by selecting from the available Ubuntu php packages, which you can view by running:

sudo apt-cache search php | grep "^php5-"

Or, for Ubuntu 16.04 and higher:

sudo apt-cache search php | grep "^php7"

As you have mentioned, there is plenty of information available on the actual installation of the packages that you might require, so I won't go into detail about that here.

Related: Enabling / disabling installed php modules

It is possible that an installed module has been disabled. In that case, it won't show up when running php -m, but it will show up in the list of installed Ubuntu packages.

Modules can be enabled/disabled via the php5enmod tool (phpenmod on later distros) which is part of the php-common package.

Ubuntu 12.04:

Enabled modules are symlinked in /etc/php5/conf.d

Ubuntu 12.04: (with PHP 5.4+)

To enable an installed module:

php5enmod <modulename>

To disable an installed module:

php5dismod <modulename>

Ubuntu 16.04 (php7) and higher:

To enable an installed module:

phpenmod <modulename>

To disable an installed module:

phpdismod <modulename>

Reload Apache

Remember to reload Apache2 after enabling/disabling:

service apache2 reload

Best practices for adding .gitignore file for Python projects?

Github has a great boilerplate .gitignore

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]

# C extensions
*.so

# Distribution / packaging
bin/
build/
develop-eggs/
dist/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
.tox/
.coverage
.cache
nosetests.xml
coverage.xml

# Translations
*.mo

# Mr Developer
.mr.developer.cfg
.project
.pydevproject

# Rope
.ropeproject

# Django stuff:
*.log
*.pot

# Sphinx documentation
docs/_build/

What is the dual table in Oracle?

It's a object to put in the from that return 1 empty row. For example: select 1 from dual; returns 1

select 21+44 from dual; returns 65

select [sequence].nextval from dual; returns the next value from the sequence.

What is the equivalent of Select Case in Access SQL?

You can use IIF for a similar result.

Note that you can nest the IIF statements to handle multiple cases. There is an example here: http://forums.devshed.com/database-management-46/query-ms-access-iif-statement-multiple-conditions-358130.html

SELECT IIf([Combinaison] = "Mike", 12, IIf([Combinaison] = "Steve", 13)) As Answer 
FROM MyTable;

How to populate options of h:selectOneMenu from database?

Based on your question history, you're using JSF 2.x. So, here's a JSF 2.x targeted answer. In JSF 1.x you would be forced to wrap item values/labels in ugly SelectItem instances. This is fortunately not needed anymore in JSF 2.x.


Basic example

To answer your question directly, just use <f:selectItems> whose value points to a List<T> property which you preserve from the DB during bean's (post)construction. Here's a basic kickoff example assuming that T actually represents a String.

<h:selectOneMenu value="#{bean.name}">
    <f:selectItems value="#{bean.names}" />
</h:selectOneMenu>

with

@ManagedBean
@RequestScoped
public class Bean {

    private String name;
    private List<String> names; 

    @EJB
    private NameService nameService;

    @PostConstruct
    public void init() {
        names = nameService.list();
    }

    // ... (getters, setters, etc)
}

Simple as that. Actually, the T's toString() will be used to represent both the dropdown item label and value. So, when you're instead of List<String> using a list of complex objects like List<SomeEntity> and you haven't overridden the class' toString() method, then you would see com.example.SomeEntity@hashcode as item values. See next section how to solve it properly.

Also note that the bean for <f:selectItems> value does not necessarily need to be the same bean as the bean for <h:selectOneMenu> value. This is useful whenever the values are actually applicationwide constants which you just have to load only once during application's startup. You could then just make it a property of an application scoped bean.

<h:selectOneMenu value="#{bean.name}">
    <f:selectItems value="#{data.names}" />
</h:selectOneMenu>

Complex objects as available items

Whenever T concerns a complex object (a javabean), such as User which has a String property of name, then you could use the var attribute to get hold of the iteration variable which you in turn can use in itemValue and/or itemLabel attribtues (if you omit the itemLabel, then the label becomes the same as the value).

Example #1:

<h:selectOneMenu value="#{bean.userName}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user.name}" />
</h:selectOneMenu>

with

private String userName;
private List<User> users;

@EJB
private UserService userService;

@PostConstruct
public void init() {
    users = userService.list();
}

// ... (getters, setters, etc)

Or when it has a Long property id which you would rather like to set as item value:

Example #2:

<h:selectOneMenu value="#{bean.userId}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user.id}" itemLabel="#{user.name}" />
</h:selectOneMenu>

with

private Long userId;
private List<User> users;

// ... (the same as in previous bean example)

Complex object as selected item

Whenever you would like to set it to a T property in the bean as well and T represents an User, then you would need to bake a custom Converter which converts between User and an unique string representation (which can be the id property). Do note that the itemValue must represent the complex object itself, exactly the type which needs to be set as selection component's value.

<h:selectOneMenu value="#{bean.user}" converter="#{userConverter}">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

with

private User user;
private List<User> users;

// ... (the same as in previous bean example)

and

@ManagedBean
@RequestScoped
public class UserConverter implements Converter {

    @EJB
    private UserService userService;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        if (submittedValue == null || submittedValue.isEmpty()) {
            return null;
        }

        try {
            return userService.find(Long.valueOf(submittedValue));
        } catch (NumberFormatException e) {
            throw new ConverterException(new FacesMessage(String.format("%s is not a valid User ID", submittedValue)), e);
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
        if (modelValue == null) {
            return "";
        }

        if (modelValue instanceof User) {
            return String.valueOf(((User) modelValue).getId());
        } else {
            throw new ConverterException(new FacesMessage(String.format("%s is not a valid User", modelValue)), e);
        }
    }

}

(please note that the Converter is a bit hacky in order to be able to inject an @EJB in a JSF converter; normally one would have annotated it as @FacesConverter(forClass=User.class), but that unfortunately doesn't allow @EJB injections)

Don't forget to make sure that the complex object class has equals() and hashCode() properly implemented, otherwise JSF will during render fail to show preselected item(s), and you'll on submit face Validation Error: Value is not valid.

public class User {

    private Long id;

    @Override
    public boolean equals(Object other) {
        return (other != null && getClass() == other.getClass() && id != null)
            ? id.equals(((User) other).id)
            : (other == this);
    }

    @Override
    public int hashCode() {
        return (id != null) 
            ? (getClass().hashCode() + id.hashCode())
            : super.hashCode();
    }

}

Complex objects with a generic converter

Head to this answer: Implement converters for entities with Java Generics.


Complex objects without a custom converter

The JSF utility library OmniFaces offers a special converter out the box which allows you to use complex objects in <h:selectOneMenu> without the need to create a custom converter. The SelectItemsConverter will simply do the conversion based on readily available items in <f:selectItem(s)>.

<h:selectOneMenu value="#{bean.user}" converter="omnifaces.SelectItemsConverter">
    <f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>

See also:

Maven: add a folder or jar file into current classpath

This might have been asked before. See Can I add jars to maven 2 build classpath without installing them?

In a nutshell: include your jar as dependency with system scope. This requires specifying the absolute path to the jar.

See also http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html

When to use std::size_t?

size_t is unsigned int. so whenever you want unsigned int you can use it.

I use it when i want to specify size of the array , counter ect...

void * operator new (size_t size); is a good use of it.

aspx page to redirect to a new page

You could also do this is plain in html with a meta tag:

<html>
<head>
  <meta http-equiv="refresh" content="0;url=new.aspx" />
</head>
<body>
</body>
</html>

How to implement the Android ActionBar back button?

Make sure your the ActionBar Home Button is enabled in the Activity:

Android, API 5+:

@Override
public void onBackPressed() {
     ...
     super.onBackPressed();
}

ActionBarSherlock and App-Compat, API 7+:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    ...
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

Android, API 11+:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    ...
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

Example MainActivity that extends ActionBarActivity:

public class MainActivity extends ActionBarActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Back button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home: 
            // API 5+ solution
            onBackPressed();
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

This way all the activities you want can have the backpress.

Android, API 16+:

http://developer.android.com/training/implementing-navigation/ancestral.html

AndroidManifest.xml:

<application ... >
    ...
    <!-- The main/home activity (it has no parent activity) -->
    <activity
        android:name="com.example.myfirstapp.MainActivity" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <!-- The meta-data element is needed for versions lower than 4.1 -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</application>

Example MainActivity that extends ActionBarActivity:

public class MainActivity extends ActionBarActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Back button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

How to get a list of column names

$<?
$db = sqlite_open('mysqlitedb');
$cols = sqlite_fetch_column_types('form name'$db, SQLITE_ASSOC);
foreach ($cols as $column => $type) {
  echo "Column: $column  Type: $type\n";
}

How to grep with a list of words

You need to use the option -f:

$ grep -f A B

The option -F does a fixed string search where as -f is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.

$ grep -Ff A B

You may also want the -w option for matching whole words only:

$ grep -wFf A B

Read man grep for a description of all the possible arguments and what they do.

Change input value onclick button - pure javascript or jQuery

using html5 data attribute...

try this

Html

Product price: $<span id="product_price">500</span>

<br>Total price: $500
<br>
<input type="button" data-quantity="2" value="2&#x00A;Qty">
<input type="button" data-quantity="4" class="mnozstvi_sleva" value="4&#x00A;Qty">
<br>Total
<input type="text" id="count" value="1">

JS

$(function(){
$('input:button').click(function () {
  $('#count').val($(this).data('quantity') * $('#product_price').text());
});
});

fiddle here

Using an HTTP PROXY - Python

Just wanted to mention, that you also may have to set the https_proxy OS environment variable in case https URLs need to be accessed. In my case it was not obvious to me and I tried for hours to discover this.

My use case: Win 7, jython-standalone-2.5.3.jar, setuptools installation via ez_setup.py

Using routes in Express-js

So, after I created my question, I got this related list on the right with a similar issue: Organize routes in Node.js.

The answer in that post linked to the Express repo on GitHub and suggests to look at the 'route-separation' example.

This helped me change my code, and I now have it working. - Thanks for your comments.

My implementation ended up looking like this;

I require my routes in the app.js:

var express = require('express')
  , site = require('./site')
  , wiki = require('./wiki');

And I add my routes like this:

app.get('/', site.index);
app.get('/wiki/:id', wiki.show);
app.get('/wiki/:id/edit', wiki.edit);

I have two files called wiki.js and site.js in the root of my app, containing this:

exports.edit = function(req, res) {

    var wiki_entry = req.params.id;

    res.render('wiki/edit', {
        title: 'Editing Wiki',
        wiki: wiki_entry
    })
}

Why does the 260 character path length limit exist in Windows?

This is not strictly true as the NTFS filesystem supports paths up to 32k characters. You can use the win32 api and "\\?\" prefix the path to use greater than 260 characters.

A detailed explanation of long path from the .Net BCL team blog.
A small excerpt highlights the issue with long paths

Another concern is inconsistent behavior that would result by exposing long path support. Long paths with the \\?\ prefix can be used in most of the file-related Windows APIs, but not all Windows APIs. For example, LoadLibrary, which maps a module into the address of the calling process, fails if the file name is longer than MAX_PATH. So this means MoveFile will let you move a DLL to a location such that its path is longer than 260 characters, but when you try to load the DLL, it would fail. There are similar examples throughout the Windows APIs; some workarounds exist, but they are on a case-by-case basis.

Removing "bullets" from unordered list <ul>

In your css file add following.

ul{
 list-style-type: none;
}

How to read a line from a text file in c/c++?

In C++, you can use the global function std::getline, it takes a string and a stream and an optional delimiter and reads 1 line until the delimiter specified is reached. An example:

#include <string>
#include <iostream>
#include <fstream>

int main() {
    std::ifstream input("filename.txt");
    std::string line;

    while( std::getline( input, line ) ) {
        std::cout<<line<<'\n';
    }

    return 0;
}

This program reads each line from a file and echos it to the console.

For C you're probably looking at using fgets, it has been a while since I used C, meaning I'm a bit rusty, but I believe you can use this to emulate the functionality of the above C++ program like so:

#include <stdio.h>

int main() {
    char line[1024];
    FILE *fp = fopen("filename.txt","r");

    //Checks if file is empty
    if( fp == NULL ) {                       
        return 1;
    }

    while( fgets(line,1024,fp) ) {
        printf("%s\n",line);
    }

    return 0;
}

With the limitation that the line can not be longer than the maximum length of the buffer that you're reading in to.

MySQL InnoDB not releasing disk space after deleting data rows from table

Year back i also faced same problem on mysql5.7 version and ibdata1 occupied 150 Gb. so i added undo tablespaces

Take Mysqldump backup
Stop mysql service
Remove all data from data dir
Add below undo tablespace parameter in current my.cnf

 #undo tablespace
  innodb_undo_directory =  /var/lib/mysql/
  innodb_rollback_segments = 128 
  innodb_undo_tablespaces = 3
  innodb_undo_logs = 128  
  innodb_max_undo_log_size=1G
  innodb_undo_log_truncate = ON

Start mysql service
store mysqldump backup

Problem resolved !!

Why isn't this code to plot a histogram on a continuous value Pandas column working?

EDIT:

After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).


A quick rerun of your data:

In [25]: df.hist(column='Trip_distance')

enter image description here

Prints out absolutely fine.

The df.hist function comes with an optional keyword argument bins=10 which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:

In [34]: df.hist(column='Trip_distance', bins=50)

enter image description here

How to store directory files listing into an array?

I'd use

files=(*)

And then if you need data about the file, such as size, use the stat command on each file.

Exploring Docker container's file system

None of the existing answers address the case of a container that exited (and can't be restarted) and/or doesn't have any shell installed (e.g. distroless ones). This one works as long has you have root access to the Docker host.

For a real manual inspection, find out the layer IDs first:

docker inspect my-container | jq '.[0].GraphDriver.Data'

In the output, you should see something like

"MergedDir": "/var/lib/docker/overlay2/03e8df748fab9526594cfdd0b6cf9f4b5160197e98fe580df0d36f19830308d9/merged"

Navigate into this folder (as root) to find the current visible state of the container filesystem.

how to concat two columns into one with the existing column name in mysql?

Instead of getting all the table columns using * in your sql statement, you use to specify the table columns you need.

You can use the SQL statement something like:

SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS FIRSTNAME FROM customer;

BTW, why couldn't you use FullName instead of FirstName? Like this:

SELECT CONCAT(FIRSTNAME, ' ', LASTNAME) AS 'CUSTOMER NAME' FROM customer;

Catching nullpointerexception in Java

NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it:

if(someVariable != null) someVariable.doSomething();
else
{
    // do something else
}

Display curl output in readable JSON format in Unix shell script

This is to add to of Gilles' Answer. There are many ways to get this done but personally I prefer something lightweight, easy to remember and universally available (e.g. come with standard LTS installations of your preferred Linux flavor or easy to install) on common *nix systems.

Here are the options in their preferred order:

Python Json.tool module

echo '{"foo": "lorem", "bar": "ipsum"}' | python -mjson.tool

pros: almost available everywhere; cons: no color coding


jq (may require one time installation)

echo '{"foo": "lorem", "bar": "ipsum"}' | jq

cons: needs to install jq; pros: color coding and versatile


json_pp (available in Ubuntu 16.04 LTS)

echo '{"foo": "lorem", "bar": "ipsum"}' | json_pp

For Ruby users

gem install jsonpretty
echo '{"foo": "lorem", "bar": "ipsum"}' | jsonpretty

What's the use of "enum" in Java?

Java programming language enums are far more powerful than their counterparts in other languages, which are little more than glorified integers. The new enum declaration defines a full-fledged class (dubbed an enum type). In addition to solving all the problems(Not typesafe, No namespace, Brittleness and Printed values are uninformative) that exists with following int Enum pattern which was used prior to java 5.0 :

public static final int SEASON_WINTER = 0;

it also allows you to add arbitrary methods and fields to an enum type, to implement arbitrary interfaces, and more. Enum types provide high-quality implementations of all the Object methods. They are Comparable and Serializable, and the serial form is designed to withstand arbitrary changes in the enum type. You can also use Enum in switch case.

Read the full article on Java Enums http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html for more details.

How do I launch a program from command line without opening a new cmd window?

I think if you closed a program

taskkill /f /im "winamp.exe" 
//....(winamp.exe is example)...

end, so if you want to start a program that you can use

start "" /normal winamp.exe 

(/norma,/max/min are that process value cpu)

ALSO

start "filepath"enter image description here

if you want command line without openning an new window you write that

start /b "filepath"enter image description here

/B is Start application without creating a new window. The application has ^C handling ignored. Unless the application enables ^C processing, ^Break is the only way to interrupt the application.

How do I get TimeSpan in minutes given two Dates?

Why not just doing it this way?

DateTime dt1 = new DateTime(2009, 6, 1);
DateTime dt2 = DateTime.Now;
double totalminutes = (dt2 - dt1).TotalMinutes;

Hope this helps.

How to index characters in a Golang string?

String characters are runes, so to print them, you have to turn them back into String.

fmt.Print(string("HELLO"[1]))

Convert an ArrayList to an object array

Something like the standard Collection.toArray(T[]) should do what you need (note that ArrayList implements Collection):

TypeA[] array = a.toArray(new TypeA[a.size()]);

On a side note, you should consider defining a to be of type List<TypeA> rather than ArrayList<TypeA>, this avoid some implementation specific definition that may not really be applicable for your application.

Also, please see this question about the use of a.size() instead of 0 as the size of the array passed to a.toArray(TypeA[])

How do I update a Python package?

You might want to look into a Python package manager like pip. If you don't want to use a Python package manager, you should be able to download M2Crypto and build/compile/install over the old installation.

Is there any publicly accessible JSON data source to test with real world data?

The Tumbler V2 API provides a pure JSON response but requires jumping through a few hoops:

  1. Register an application
  2. Get your "OAuth Consumer Key" which you'll find when editing your application from the apps page
  3. Use any of the methods that only require an API Key for authentication as this can be passed in the URL, e.g. posts
  4. Enjoy your JSON response!

Example URL: http://api.tumblr.com/v2/blog/puppygifs.tumblr.com/posts/photo?api_key=YOUR_KEY_HERE

Result showing tree structure in Fiddler:

Screenshot

Custom Python list sorting

As a side note, here is a better alternative to implement the same sorting:

alist.sort(key=lambda x: x.foo)

Or alternatively:

import operator
alist.sort(key=operator.attrgetter('foo'))

Check out the Sorting How To, it is very useful.

Creating a recursive method for Palindrome

Here is the code for palindrome check without creating many strings

public static boolean isPalindrome(String str){
    return isPalindrome(str,0,str.length()-1);
}

public static boolean isPalindrome(String str, int start, int end){
    if(start >= end)
        return true;
    else
        return (str.charAt(start) == str.charAt(end)) && isPalindrome(str, start+1, end-1);
}

If statement in select (ORACLE)

use the variable, Oracle does not support SQL in that context without an INTO. With a properly named variable your code will be more legible anyway.

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

That's your jQuery API problem, not your script. There is not much to worry about.

Find a commit on GitHub given the commit hash

The ability to search commits has recently been added to GitHub.

To search for a hash, just enter at least the first 7 characters in the search box. Then on the results page, click the "Commits" tab to see matching commits (but only on the default branch, usually master), or the "Issues" tab to see pull requests containing the commit.

To be more explicit you can add the hash: prefix to the search, but it's not really necessary.

There is also a REST API (at the time of writing it is still in preview).

Hibernate error - QuerySyntaxException: users is not mapped [from users]

Some Linux based MySQL installations require case sensitive. Work around is to apply nativeQuery.

@Query(value = 'select ID, CLUMN2, CLUMN3 FROM VENDOR c where c.ID = :ID', nativeQuery = true)

Is there a JSON equivalent of XQuery/XPath?

To summarise some of the current options for traversing/filtering JSON data, and provide some syntax examples...

  • JSPath
    .automobiles{.maker === "Honda" && .year > 2009}.model

  • json:select() (inspired more by CSS selectors)
    .automobiles .maker:val("Honda") .model

  • JSONPath (inspired more by XPath)
    $.automobiles[?(@.maker='Honda')].model

I think JSPath looks the nicest, so I'm going to try and integrate it with my AngularJS + CakePHP app.

(I originally posted this answer in another thread but thought it would be useful here, also.)

Comparing Class Types in Java

If you had two Strings and compared them using == by calling the getClass() method on them, it would return true. What you get is a reference on the same object.

This is because they are both references on the same class object. This is true for all classes in a java application. Java only loads the class once, so you have only one instance of a given class at a given time.

String hello  = "Hello";
String world = "world";

if (hello.getClass() == world.getClass()) {
    System.out.println("true");
} // prints true

How can I convert String[] to ArrayList<String>

Like this :

String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));

or

List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);

How to suppress Update Links warning?

I wanted to suppress the prompt that asks if you wish to update links to another workbook when my workbook is manually opened in Excel (as opposed to opening it programmatically via VBA). I tried including: Application.AskToUpdateLinks = False as the first line in my Auto_Open() macro but that didn't work. I discovered however that if you put it instead in the Workbook_Open() function in the ThisWorkbook module, it works brilliantly - the dialog is suppressed but the update still occurs silently in the background.

 Private Sub Workbook_Open()
    ' Suppress dialog & update automatically without asking
    Application.AskToUpdateLinks = False
End Sub

Creating runnable JAR with Gradle

Here is the solution I tried with Gradle 6.7

Runnable fat Jar (with all dependent libraries copied to the jar)

task fatJar(type: Jar) {
   
    manifest {
        attributes 'Main-Class': 'com.example.gradle.App'
    }
    from {
        configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
    } with jar
    
}

Runnable jar with all dependencies copied to a directory and adding the classpath to the manifest

    def dependsDir = "${buildDir}/libs/dependencies/"
    task copyDependencies(type: Copy) {
        from configurations.compile
        into "${dependsDir}"
    }
    task createJar(dependsOn: copyDependencies, type: Jar) {
      
        manifest {
            attributes('Main-Class': 'com.example.gradle.App',
                    'Class-Path': configurations.compile.collect { 'dependencies/' + it.getName() }.join(' ')
            )
        }
        with jar
    }

How to use ?

  • Add the above tasks to build.gradle
  • Execute gradle fatJar //create fatJar
  • Execute gradle createJar // create jar with dependencies copied.

More details : https://jafarmlp.medium.com/a-simple-java-project-with-gradle-2c323ae0e43d

Bootstrap 3 truncate long text inside rows of a table in a responsive way

I'm using bootstrap.
I used css parameters.

.table {
  table-layout:fixed;
}

.table td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

and bootstrap grid system parameters, like this.

<th class="col-sm-2">Name</th>

<td class="col-sm-2">hoge</td>

How to run a command in the background and get no output?

Use nohup if your background job takes a long time to finish or you just use SecureCRT or something like it login the server.

Redirect the stdout and stderr to /dev/null to ignore the output.

nohup /path/to/your/script.sh > /dev/null 2>&1 &

Getting the last n elements of a vector. Is there a better way than using the length() function?

You can do exactly the same thing in R with two more characters:

x <- 0:9
x[-5:-1]
[1] 5 6 7 8 9

or

x[-(1:5)]

PHP Sort a multidimensional array by element containing date

For those still looking a solved it this way inside a class with a function sortByDate, see the code below

<?php

class ContactsController 
{
    public function __construct()
    {
    //
    }


    function sortByDate($key)
    {
        return function ($a, $b) use ($key) {
            $t1 = strtotime($a[$key]);
            $t2 = strtotime($b[$key]);
            return $t2-$t1;
        };

    }

    public function index()
    {

        $data[] = array('contact' => '434343434', 'name' => 'dickson','updated_at' =>'2020-06-11 12:38:23','created_at' =>'2020-06-11 12:38:23');
        $data[] = array('contact' => '434343434', 'name' => 'dickson','updated_at' =>'2020-06-16 12:38:23','created_at' =>'2020-06-10 12:38:23');
        $data[] = array('contact' => '434343434', 'name' => 'dickson','updated_at' =>'2020-06-7 12:38:23','created_at' =>'2020-06-9 12:38:23');


        usort($data, $this->sortByDate('updated_at'));

        //usort($data, $this->sortByDate('created_at'));
        echo $data;

    }
}

How to call multiple functions with @click in vue?

If you want something a little bit more readable, you can try this:

<button @click="[click1($event), click2($event)]">
  Multiple
</button>

To me, this solution feels more Vue-like hope you enjoy

How do I change UIView Size?

Here you go. this should work.

questionFrame.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.7) 

answerFrame.frame =  CGRectMake(0 , self.view.frame.height * 0.7, self.view.frame.width, self.view.frame.height * 0.3)

Add / remove input field dynamically with jQuery

You can do something like this below:

//when the Add Field button is clicked
$("#add").click(function (e) {
//Append a new row of code to the "#items" div
  $("#items").append('<div><input type="text" name="input[]"><button  class="delete">Delete</button></div>');
});

For detailed tutorial http://voidtricks.com/jquery-add-remove-input-fields/

With ng-bind-html-unsafe removed, how do I inject HTML?

Instead of declaring a function in your scope, as suggested by Alex, you can convert it to a simple filter :

angular.module('myApp')
    .filter('to_trusted', ['$sce', function($sce){
        return function(text) {
            return $sce.trustAsHtml(text);
        };
    }]);

Then you can use it like this :

<div ng-bind-html="preview_data.preview.embed.html | to_trusted"></div>

And here is a working example : http://jsfiddle.net/leeroy/6j4Lg/1/

python max function using 'key' and lambda expression

lambda is an anonymous function, it is equivalent to:

def func(p):
   return p.totalScore     

Now max becomes:

max(players, key=func)

But as def statements are compound statements they can't be used where an expression is required, that's why sometimes lambda's are used.

Note that lambda is equivalent to what you'd put in a return statement of a def. Thus, you can't use statements inside a lambda, only expressions are allowed.


What does max do?

max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.

So, it simply returns the object that is the largest.


How does key work?

By default in Python 2 key compares items based on a set of rules based on the type of the objects (for example a string is always greater than an integer).

To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key argument.

Example 1:

A simple example, suppose you have a list of numbers in string form, but you want to compare those items by their integer value.

>>> lis = ['1', '100', '111', '2']

Here max compares the items using their original values (strings are compared lexicographically so you'd get '2' as output) :

>>> max(lis)
'2'

To compare the items by their integer value use key with a simple lambda:

>>> max(lis, key=lambda x:int(x))  # compare `int` version of each item
'111'

Example 2: Applying max to a list of tuples.

>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]

By default max will compare the items by the first index. If the first index is the same then it'll compare the second index. As in my example, all items have a unique first index, so you'd get this as the answer:

>>> max(lis)
(4, 'e')

But, what if you wanted to compare each item by the value at index 1? Simple: use lambda:

>>> max(lis, key = lambda x: x[1])
(-1, 'z')

Comparing items in an iterable that contains objects of different type:

List with mixed items:

lis = ['1','100','111','2', 2, 2.57]

In Python 2 it is possible to compare items of two different types:

>>> max(lis)  # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x))  # compare integer version of each item
'111'

But in Python 3 you can't do that any more:

>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
  File "<ipython-input-2-0ce0a02693e4>", line 1, in <module>
    max(lis)
TypeError: unorderable types: int() > str()

But this works, as we are comparing integer version of each object:

>>> max(lis, key=lambda x: int(x))  # or simply `max(lis, key=int)`
'111'

How can I create directory tree in C++/Linux?

It should be noted that starting from C++17 filesystem interface is part of the standard library. This means that one can have following to create directories:

#include <filesystem>

std::filesystem::create_directories("/a/b/c/d")

More info here: https://en.cppreference.com/w/cpp/filesystem/create_directory

Additionally, with gcc, one needs to "-std=c++17" to CFLAGS. And "-lstdc++fs" to LDLIBS. The latter potentially is not going to be required in the future.

Webpack.config how to just copy the index.html to the dist folder

To copy an already existing index.html file into the dist directory you can simply use the HtmlWebpackPlugin by specifying the source index.html as a template.

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  // ...
  plugins: [    
    new HtmlWebpackPlugin({
      template: './path/to/index.html',
    })
  ],
  // ...
};

The created dist/index.html file will be basically the same as your source file with the difference that bundled resources like .js files are injected with <script> tags by webpack. Minification and further options can be configured and are documented on github.

datetime dtypes in pandas read_csv

There is a parse_dates parameter for read_csv which allows you to define the names of the columns you want treated as dates or datetimes:

date_cols = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=date_cols)

Passing vector by reference

You don't need to use **arr, you can either use:

void do_something(int el, std::vector<int> *arr){
    arr->push_back(el);
}

or:

 void do_something(int el, std::vector<int> &arr){
    arr.push_back(el);
}

**arr makes no sense but if you insist using it, do it this way:

void do_something(int el, std::vector<int> **arr){
    (*arr)->push_back(el);
}

but again there is no reason to do so...

Cropping an UIImage

Look at https://github.com/vvbogdan/BVCropPhoto

- (UIImage *)croppedImage {
    CGFloat scale = self.sourceImage.size.width / self.scrollView.contentSize.width;

    UIImage *finalImage = nil;
    CGRect targetFrame = CGRectMake((self.scrollView.contentInset.left + self.scrollView.contentOffset.x) * scale,
            (self.scrollView.contentInset.top + self.scrollView.contentOffset.y) * scale,
            self.cropSize.width * scale,
            self.cropSize.height * scale);

    CGImageRef contextImage = CGImageCreateWithImageInRect([[self imageWithRotation:self.sourceImage] CGImage], targetFrame);

    if (contextImage != NULL) {
        finalImage = [UIImage imageWithCGImage:contextImage
                                         scale:self.sourceImage.scale
                                   orientation:UIImageOrientationUp];

        CGImageRelease(contextImage);
    }

    return finalImage;
}


- (UIImage *)imageWithRotation:(UIImage *)image {


    if (image.imageOrientation == UIImageOrientationUp) return image;
    CGAffineTransform transform = CGAffineTransformIdentity;

    switch (image.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;

        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, image.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }

    switch (image.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;

        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, image.size.width, image.size.height,
            CGImageGetBitsPerComponent(image.CGImage), 0,
            CGImageGetColorSpace(image.CGImage),
            CGImageGetBitmapInfo(image.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (image.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0, 0, image.size.height, image.size.width), image.CGImage);
            break;

        default:
            CGContextDrawImage(ctx, CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage);
            break;
    }

    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;

}

How do you setLayoutParams() for an ImageView?

Old thread but I had the same problem now. If anyone encounters this he'll probably find this answer:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

This will work only if you add the ImageView as a subView to a LinearLayout. If you add it to a RelativeLayout you will need to call:

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

Have you tried, after calling DataBind on your DropDownList, to do something like ddl.SelectedIndex = 0 ?

How to sort a list of strings?

The proper way to sort strings is:

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']

# Without using locale.strcoll you get:
assert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']

The previous example of mylist.sort(key=lambda x: x.lower()) will work fine for ASCII-only contexts.

Controlling Maven final name of jar artifact

I am using the following

        ....
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.0.2</version>
            <configuration>
                <finalName>${project.groupId}/${project.artifactId}-${baseVersion}.${monthlyVersion}.${instanceVersion}</finalName>
            </configuration>
        </plugin>
        ....

This way you can define each value individually or pragmatically from Jenkins of some other system.

mvn package -DbaseVersion=1 -monthlyVersion=2 -instanceVersion=3

This will place a folder target\{group.id}\projectName-1.2.3.jar

A better way to save time might be

        ....
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.0.2</version>
            <configuration>
                <finalName>${project.groupId}/${project.artifactId}-${baseVersion}</finalName>
            </configuration>
        </plugin>
        ....

Like the same except I use on variable.

  mvn package -DbaseVersion=0.3.4

This will place a folder target\{group.id}\projectName-1.2.3.jar

you can also use outputDirectory inside of configuration to specify a location you may want the package to be located.

Understanding events and event handlers in C#

Just to add to the existing great answers here - building on the code in the accepted one, which uses a delegate void MyEventHandler(string foo)...

Because the compiler knows the delegate type of the SomethingHappened event, this:

myObj.SomethingHappened += HandleSomethingHappened;

Is totally equivalent to:

myObj.SomethingHappened += new MyEventHandler(HandleSomethingHappened);

And handlers can also be unregistered with -= like this:

// -= removes the handler from the event's list of "listeners":
myObj.SomethingHappened -= HandleSomethingHappened;

For completeness' sake, raising the event can be done like this, only in the class that owns the event:

//Firing the event is done by simply providing the arguments to the event:
var handler = SomethingHappened; // thread-local copy of the event
if (handler != null) // the event is null if there are no listeners!
{
    handler("Hi there!");
}

The thread-local copy of the handler is needed to make sure the invocation is thread-safe - otherwise a thread could go and unregister the last handler for the event immediately after we checked if it was null, and we would have a "fun" NullReferenceException there.


C# 6 introduced a nice short hand for this pattern. It uses the null propagation operator.

SomethingHappened?.Invoke("Hi there!");

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

This has happened to me after I "updated" into 5.0 SDK and wanted to create a new application with support library

In both Projects (project.properties file) in the one you want to use support library and the support library itself it has to be set the same target

e.g. for my case it worked

  1. In project android-support-v7-appcompat Change project.properties into target=android-21
  2. Cleanandroid-support-v7-appcompat In my project (where I desire support library)
  3. In my project, Change project.properties into target=android-21 and android.library.reference.1=../android-support-v7-appcompat (or add support library in project properties)
  4. Clean the project

How to search for a part of a word with ElasticSearch

I think there's no need to change any mapping. Try to use query_string, it's perfect. All scenarios will work with default standard analyzer:

We have data:

{"_id" : "1","name" : "John Doeman","function" : "Janitor"}
{"_id" : "2","name" : "Jane Doewoman","function" : "Teacher"}

Scenario 1:

{"query": {
    "query_string" : {"default_field" : "name", "query" : "*Doe*"}
} }

Response:

{"_id" : "1","name" : "John Doeman","function" : "Janitor"}
{"_id" : "2","name" : "Jane Doewoman","function" : "Teacher"}

Scenario 2:

{"query": {
    "query_string" : {"default_field" : "name", "query" : "*Jan*"}
} }

Response:

{"_id" : "1","name" : "John Doeman","function" : "Janitor"}

Scenario 3:

{"query": {
    "query_string" : {"default_field" : "name", "query" : "*oh* *oe*"}
} }

Response:

{"_id" : "1","name" : "John Doeman","function" : "Janitor"}
{"_id" : "2","name" : "Jane Doewoman","function" : "Teacher"}

EDIT - Same implementation with spring data elastic search https://stackoverflow.com/a/43579948/2357869

One more explanation how query_string is better than others https://stackoverflow.com/a/43321606/2357869

Get the IP address of the machine

Further to what Steve Baker has said, you can find a description of the SIOCGIFCONF ioctl in the netdevice(7) man page.

Once you have the list of all the IP addresses on the host, you will have to use application specific logic to filter out the addresses you do not want and hope you have one IP address left.

Using Laravel Homestead: 'no input file specified'

Here's my solution:

It's a file path problem so below are my folders & sites paths. Also, I had to use "vagrant destroy" as provisioning didn't work.

enter image description here

How do Python functions handle the types of the parameters that you pass in?

You never specify the type; Python has the concept of duck typing; basically the code that processes the parameters will make certain assumptions about them - perhaps by calling certain methods that a parameter is expected to implement. If the parameter is of the wrong type, then an exception will be thrown.

In general it is up to your code to ensure that you are passing around objects of the proper type - there is no compiler to enforce this ahead of time.

Running sites on "localhost" is extremely slow

I fixed this problem by editing config.inc.php file which is in phpmyadmin folder: specifically changed $cfg['Servers'][$i]['host'] = 'localhost' to $cfg['Servers'][$i]['host'] = '127.0.0.1'

How to save and extract session data in codeigniter

In codeigniter we are able to store session values in a database. In the config.php file make the sess_use_database variable true

$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';

and create a ci_session table in the database

CREATE TABLE IF NOT EXISTS  `ci_sessions` (
    session_id varchar(40) DEFAULT '0' NOT NULL,
    ip_address varchar(45) DEFAULT '0' NOT NULL,
    user_agent varchar(120) NOT NULL,
    last_activity int(10) unsigned DEFAULT 0 NOT NULL,
    user_data text NOT NULL,
    PRIMARY KEY (session_id),
    KEY `last_activity_idx` (`last_activity`)
);

For more details and reference, click here

Convert string to symbol-able in ruby

Rails got ActiveSupport::CoreExtensions::String::Inflections module that provides such methods. They're all worth looking at. For your example:

'Book Author Title'.parameterize.underscore.to_sym # :book_author_title

Sass Variable in CSS calc() function

Even though its not directly related. But I found that the CALC code won't work if you do not put spaces properly.

So this did not work for me calc(#{$a}+7px)

But this worked calc(#{$a} + 7px)

Took me sometime to figure this out.

make html text input field grow as I type?

I just wrote this for you, I hope you like it :) No guarantees that it's cross-browser, but I think it is :)

(function(){
    var min = 100, max = 300, pad_right = 5, input = document.getElementById('adjinput');

    input.style.width = min+'px';
    input.onkeypress = input.onkeydown = input.onkeyup = function(){
        var input = this;
        setTimeout(function(){
            var tmp = document.createElement('div');
            tmp.style.padding = '0';
            if(getComputedStyle)
                tmp.style.cssText = getComputedStyle(input, null).cssText;
            if(input.currentStyle)
                tmp.style.cssText = input.currentStyle.cssText;
            tmp.style.width = '';
            tmp.style.position = 'absolute';
            tmp.innerHTML = input.value.replace(/&/g, "&amp;")
                                       .replace(/</g, "&lt;")
                                       .replace(/>/g, "&gt;")
                                       .replace(/"/g, "&quot;")
                                       .replace(/'/g, "&#039;")
                                       .replace(/ /g, '&nbsp;');
            input.parentNode.appendChild(tmp);
            var width = tmp.clientWidth+pad_right+1;
            tmp.parentNode.removeChild(tmp);
            if(min <= width && width <= max)
                input.style.width = width+'px';
        }, 1);
    }
})();

JSFiddle

Cannot declare instance members in a static class in C#

I know this post is old but...

I was able to do this, my problem was that I forgot to make my property static.

public static class MyStaticClass
{
    private static NonStaticObject _myObject = new NonStaticObject();

    //property
    public static NonStaticObject MyObject
    {
        get { return _myObject; }
        set { _myObject = value; }
    }
}

How can you check for a #hash in a URL using JavaScript?

Most people are aware of the URL properties in document.location. That's great if you're only interested in the current page. But the question was about being able to parse anchors on a page not the page itself.

What most people seem to miss is that those same URL properties are also available to anchor elements:

// To process anchors on click    
jQuery('a').click(function () {
   if (this.hash) {
      // Clicked anchor has a hash
   } else {
      // Clicked anchor does not have a hash
   }
});

// To process anchors without waiting for an event
jQuery('a').each(function () {
   if (this.hash) {
      // Current anchor has a hash
   } else {
      // Current anchor does not have a hash
   }
});

How to change xampp localhost to another folder ( outside xampp folder)?

It can be done in two steps for Ubuntu 14.04 with Xampp 1.8.3-5

Step 1:- Change DocumentRoot and Directory path in /opt/lampp/etc/httpd.conf from

DocumentRoot "/opt/lampp/htdocs" and Directory "/opt/lampp/htdocs"

to DocumentRoot "/home/user/Desktop/js" and Directory "/home/user/Desktop/js"

Step 2:- Change the rights of folder (in path and its parent folders to 777) eg via

sudo chmod -R 777 /home/user/Desktop/js

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

Answering this old question (for others which may help)

Configuring your httpd conf correctly will make the problem solved. Install any httpd server, if you don't have one.

Listing my config here.

[smilyface@box002 ~]$ cat /etc/httpd/conf/httpd.conf | grep shirts | grep -v "#"


        ProxyPass /shirts-service http://local.box002.com:16743/shirts-service
        ProxyPassReverse /shirts-service http://local.box002.com:16743/shirts-service
        ProxyPass /shirts http://local.box002.com:16443/shirts
        ProxyPassReverse /shirts http://local.box002.com:16443/shirts
        ...
        ...
        ...

edit the file as above and then restart httpd as below

[smilyface@box002 ~]$ sudo service httpd restart


And then request with with https will work without exception.
Also request with http will forward to https ! No worries.

Curl Command to Repeat URL Request

You might be interested in Apache Bench tool which is basically used to do simple load testing.

example :

ab -n 500 -c 20 http://www.example.com/

n = total number of request, c = number of concurrent request

Visual Studio Code Search and Replace with Regular Expressions

If you want ex. change all country codes in .json file from uppercase to lowercase:

ctrl+h
alt+r
alt+c

Find: ([A-Z]{2,})
Replace: $1

alt+enter
F1
type: lower -> select toLoweCase
ctrl+alt+enter

ex file:

[
 {"id": "PL", "name": "Poland"},
 {"id": "NZ", "name": "New Zealand"},
 ...
]

PHP/Apache: PHP Fatal error: Call to undefined function mysql_connect()

How about

sudo yum install php-mysql

or

sudo apt-get install php5-mysql

HTML Entity Decode

here is another version:

_x000D_
_x000D_
function convertHTMLEntity(text){_x000D_
    const span = document.createElement('span');_x000D_
_x000D_
    return text_x000D_
    .replace(/&[#A-Za-z0-9]+;/gi, (entity,position,text)=> {_x000D_
        span.innerHTML = entity;_x000D_
        return span.innerText;_x000D_
    });_x000D_
}_x000D_
_x000D_
console.log(convertHTMLEntity('Large &lt; &#163; 500'));
_x000D_
_x000D_
_x000D_

How do I start Mongo DB from Windows?

Clearly many people have answered upon your query of how to make mongoDb work, I'd answer the second part: Regarding an appropriate GUI for mongoDB

My suggestion is, go for MongoChef (now Studio 3T)

You can easily install and use it.

You might want want to refer to (from 03:10- to 08:50): https://www.youtube.com/watch?v=0ws3oIyqieY&index=2&list=PLS1QulWo1RIZtR6bncmSaH8fB81oRl6MP

For a step by step guide to the GUI tool.

How to update parent's state in React?

-We can create ParentComponent and with handleInputChange method to update the ParentComponent state. Import the ChildComponent and we pass two props from parent to child component ie.handleInputChange function and count.

import React, { Component } from 'react';
import ChildComponent from './ChildComponent';

class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.state = {
      count: '',
    };
  }

  handleInputChange(e) {
    const { value, name } = e.target;
    this.setState({ [name]: value });
  }

  render() {
    const { count } = this.state;
    return (
      <ChildComponent count={count} handleInputChange={this.handleInputChange} />
    );
  }
}
  • Now we create the ChildComponent file and save as ChildComponent.jsx. This component is stateless because the child component doesn't have a state. We use the prop-types library for props type checking.

    import React from 'react';
    import { func, number } from 'prop-types';
    
    const ChildComponent = ({ handleInputChange, count }) => (
      <input onChange={handleInputChange} value={count} name="count" />
    );
    
    ChildComponent.propTypes = {
      count: number,
      handleInputChange: func.isRequired,
    };
    
    ChildComponent.defaultProps = {
      count: 0,
    };
    
    export default ChildComponent;
    

how to set cursor style to pointer for links without hrefs

This is how change the cursor from an arrow to a hand when you hover over a given object (myObject).

myObject.style.cursor = 'pointer';

Format number to always show 2 decimal places

_x000D_
_x000D_
function number_format(string,decimals=2,decimal=',',thousands='.',pre='R$ ',pos=' Reais'){_x000D_
  var numbers = string.toString().match(/\d+/g).join([]);_x000D_
  numbers = numbers.padStart(decimals+1, "0");_x000D_
  var splitNumbers = numbers.split("").reverse();_x000D_
  var mask = '';_x000D_
  splitNumbers.forEach(function(d,i){_x000D_
    if (i == decimals) { mask = decimal + mask; }_x000D_
    if (i>(decimals+1) && ((i-2)%(decimals+1))==0) { mask = thousands + mask; }_x000D_
    mask = d + mask;_x000D_
  });_x000D_
  return pre + mask + pos;_x000D_
}_x000D_
var element = document.getElementById("format");_x000D_
var money= number_format("10987654321",2,',','.');_x000D_
element.innerHTML = money;
_x000D_
#format{_x000D_
display:inline-block;_x000D_
padding:10px;_x000D_
border:1px solid #ddd;_x000D_
background:#f5f5f5;_x000D_
}
_x000D_
<div id='format'>Test 123456789</div>
_x000D_
_x000D_
_x000D_

What is the difference between a definition and a declaration?

The declaration is when a primitive or object reference variable or method is created without assigning value or object. int a; final int a;

The definition means assigning the value or object respectively int a =10;

Initialization means allocating memory for a respective variable or object.

Axios get in url works but with second parameter as object it doesn't

axios.get accepts a request config as the second parameter (not query string params).

You can use the params config option to set query string params as follows:

axios.get('/api', {
  params: {
    foo: 'bar'
  }
});

AngularJS : automatically detect change in model

In views with {{}} and/or ng-model, Angular is setting up $watch()es for you behind the scenes.

By default $watch compares by reference. If you set the third parameter to $watch to true, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:

$scope.$watch('myModel', function() { ... }, true);

Update: Angular v1.2 added a new method for this, `$watchCollection():

$scope.$watchCollection('myModel', function() { ... });

Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.

How can I use Guzzle to send a POST request in JSON?

For Guzzle <= 4:

It's a raw post request so putting the JSON in the body solved the problem

$request = $this->client->post(
    $url,
    [
        'content-type' => 'application/json'
    ],
);
$request->setBody($data); #set body!
$response = $request->send();

How to install an npm package from GitHub directly?

The current top answer by Peter Lyons is not relevant with recent NPM versions. For example, using the same command that was criticized in this answer is now fine.

$ npm install https://github.com/visionmedia/express

If you have continued problems it might be a problem with whatever package you were using.

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

How do I calculate tables size in Oracle

I have the same variant as the last ones which calculates segments of table data, table indexes and blob-fields:

CREATE OR REPLACE FUNCTION
  SYS.RAZMER_TABLICY_RAW(pNazvanie in varchar, pOwner in varchar2)
return number
is
  val number(16);
  sz number(16);
begin
  sz := 0;

  --Calculate size of table data segments
  select
    sum(t.bytes) into val
  from
    sys.dba_segments t
  where
    t.segment_name = upper(pNazvanie)
  and
    t.owner = upper(pOwner);
  sz := sz + nvl(val,0);

  --Calculate size of table indexes segments
  select
    sum(s.bytes) into val
  from
    all_indexes t
  inner join
    dba_segments s
  on
    t.index_name = s.segment_name
  where
    t.table_name = upper(pNazvanie)
  and
    t.owner = upper(pOwner);
  sz := sz + nvl(val,0);

  --Calculate size of table blob segments
  select
    sum(s.bytes) into val
  from
    all_lobs t
  inner join
    dba_segments s on t.segment_name = s.segment_name
  where
    t.table_name = upper(pNazvanie)
  and
    t.owner = upper(pOwner);
  sz := sz + nvl(val,0);

  return sz;

end razmer_tablicy_raw;

Source.

Replacing instances of a character in a string

My problem was that I had a list of numbers, and I only want to replace a part of that number, soy I do this:

original_list = ['08113', '09106', '19066', '17056', '17063', '17053']

# With this part I achieve my goal
cves_mod = []
for i in range(0,len(res_list)):
    cves_mod.append(res_list[i].replace(res_list[i][2:], '999'))
cves_mod

# Result
cves_mod
['08999', '09999', '19999', '17999', '17999', '17999']

How to retrieve a file from a server via SFTP?

There is a nice comparison of the 3 mature Java libraries for SFTP: Commons VFS, SSHJ and JSch

To sum up SSHJ has the clearest API and it's the best out of them if you don't need other storages support provided by Commons VFS.

Here is edited SSHJ example from github:

final SSHClient ssh = new SSHClient();
ssh.loadKnownHosts(); // or, to skip host verification: ssh.addHostKeyVerifier(new PromiscuousVerifier())
ssh.connect("localhost");
try {
    ssh.authPassword("user", "password"); // or ssh.authPublickey(System.getProperty("user.name"))
    final SFTPClient sftp = ssh.newSFTPClient();
    try {
        sftp.get("test_file", "/tmp/test.tmp");
    } finally {
        sftp.close();
    }
} finally {
    ssh.disconnect();
}