Programs & Examples On #Hibernate tools

Hibernate Tools is a toolset for Hibernate implemented as an integrated suite of Eclipse plugins, together with a unified Ant task for integration into the build cycle. Hibernate Tools is a core component of JBoss Tools and hence also part of JBoss Developer Studio.

How to install Hibernate Tools in Eclipse?

Well, most convenient and safest way is to use JBoss update site within Eclipse software updates (Help -> Software Updates... -> Add Site...):

The latest stable release update site for JBoss Tools

There you can find Hibernate tools together with other handy JBoss plugins.

Why use armeabi-v7a code over armeabi code?

Instead of having a fat APK file, I would like to use just the armeabi files and remove the armeabi-v7a folder.

The opposite is a much better strategy. If you have minSdkVersion to 14 and upload your apk to the play store, you'll notice you'll support the same number of devices whether you support armeabi or not. Therefore, there are no devices with Android 4 or higher which would benefit from armeabi at all.

This is probably why the Android NDK doesn't even support armeabi anymore as per revision r17b. [source]

How do I vertically center text with CSS?

For all your vertical alignment needs!

Declare this Mixin:

@mixin vertical-align($position: relative) {
  position: $position;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

Then include it in your element:

.element{
    @include vertical-align();
}

Check if instance is of a type

The different answers here have two different meanings.

If you want to check whether an instance is of an exact type then

if (c.GetType() == typeof(TForm))

is the way to go.

If you want to know whether c is an instance of TForm or a subclass then use is/as:

if (c is TForm)

or

TForm form = c as TForm;
if (form != null)

It's worth being clear in your mind about which of these behaviour you actually want.

How do I install ASP.NET MVC 5 in Visual Studio 2012?

Step 1: Install update http://httpjunkie.com/2013/340/develop-mvc-5-with-asp-net-identity-in-visual-studio-2012/.

OK, so that gets you to be able to start from a blank ASP.NET MVC project, but a lot of people want the FULL INTERNET APPLICATION as shipped with Visual Studio 2013.

So I have a step 2: http://httpjunkie.com/2013/340/develop-mvc-5-with-asp-net-identity-in-visual-studio-2012/

If you follow that tutorial on my website I follow it up with a full install of Foundation 5 and a cool Hybrid OffCanvas/Top-Bar navigation.

.ssh/config file for windows (git)

These instructions work fine in Linux. In Windows, they are not working for me today.

I found an answer that helps for me, maybe this will help OP. I kissed a lot of frogs trying to solve this. You need to add your new non-standard-named key file with "ssh-add"! Here's instruction for the magic bullet: Generating a new SSH key and adding it to the ssh-agent. Once you know the magic search terms are "add key with ssh-add in windows" you find plenty of other links.

If I were using Windows often, I'd find some way to make this permanent. https://github.com/raeesbhatti/ssh-agent-helper.

The ssh key agent looks for default "id_rsa" and other keys it knows about. The key you create with a non-standard name must be added to the ssh key agent.

First, I start the key agent in the Git BASH shell:

$ eval $(ssh-agent -s)
Agent pid 6276

$ ssh-add ~/.ssh/Paul_Johnson-windowsvm-20180318
Enter passphrase for /c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318:
Identity added: /c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318 (/c/Users/pauljohn32/.ssh/Paul_Johnson-windowsvm-20180318)

Then I change to the directory where I want to clone the repo

$ cd ~/Documents/GIT/

$ git clone [email protected]:test/spr2018.git
Cloning into 'spr2018'...
remote: Counting objects: 3, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (3/3), done.

I fought with this for a long long time.

Here are other things I tried along the way

At first I was certain it is because of file and folder permissions. On Linux, I have seen .ssh settings rejected if the folder is not set at 700. Windows has 711. In Windows, I cannot find any way to make permissions 700.

After fighting with that, I think it must not be the problem. Here's why. If the key is named "id_rsa" then git works! Git is able to connect to server. However, if I name the key file something else, and fix the config file in a consistent way, no matter what, then git fails to connect. That makes me think permissions are not the problem.

A thing you can do to debug this problem is to watch verbose output from ssh commands using the configured key.

In the git bash shell, run this

$ ssh -T git@name-of-your-server

Note, the user name should be "git" here. If your key is set up and the config file is found, you see this, as I just tested in my Linux system:

$ ssh -T [email protected]
Welcome to GitLab, Paul E. Johnson!

On the other hand, in Windows I have same trouble you do before applying "ssh-add". It wants git's password, which is always a fail.

$ ssh -T [email protected]
[email protected]'s password:

Again, If i manually copy my key to "id_rsa" and "id_rsa.pub", then this works fine. After running ssh-add, observe the victory in Windows Git BASH:

$ ssh -T [email protected]
Welcome to GitLab, Paul E. Johnson!

You would hear the sound of me dancing with joy if you were here.

To figure out what was going wrong, you can I run 'ssh' with "-Tvv"

In Linux, I see this when it succeeds:

debug1: Offering RSA public key: pauljohn@pols124
debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg ssh-rsa blen 279
debug2: input_userauth_pk_ok: fp SHA256:bCoIWSXE5fkOID4Kj9Axt2UOVsRZz9JW91RQDUoasVo
debug1: Authentication succeeded (publickey).

In Windows, when this fails, I see it looking for default names:

debug1: Found key in /c/Users/pauljohn32/.ssh/known_hosts:1
debug2: set_newkeys: mode 1
debug1: rekey after 4294967296 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 4294967296 blocks
debug2: key: /c/Users/pauljohn32/.ssh/id_rsa (0x0)
debug2: key: /c/Users/pauljohn32/.ssh/id_dsa (0x0)
debug2: key: /c/Users/pauljohn32/.ssh/id_ecdsa (0x0)
debug2: key: /c/Users/pauljohn32/.ssh/id_ed25519 (0x0)
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Next authentication method: publickey
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_rsa
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_dsa
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_ecdsa
debug1: Trying private key: /c/Users/pauljohn32/.ssh/id_ed25519
debug2: we did not send a packet, disable method
debug1: Next authentication method: password
[email protected]'s password:

That was the hint I needed, it says it finds my ~/.ssh/config file but never tries the key I want it to try.

I only use Windows once in a long while and it is frustrating. Maybe the people who use Windows all the time fix this and forget it.

Unable to copy file - access to the path is denied

I had the same issue, To resolved this i had checked/done several things

What Didn't work

1) Read/write permissions were given to directory 
2) Restarted visual studio
3) Tried deleting visual studio temp files

What worked at last

Just paste the command given by Fred Morrison into the "Package Manager Console":

Get-Process | Where-Object -Property Name -EQ 'VBCSCompiler' | Stop-Process -Force -Verbose

Note: Just an observation Restarting Visual studio might not work in this case but restarting system can because stoppin process "VBCSCompiler" was the solution so we can do it either way.

How do I put variable values into a text string in MATLAB?

As Peter and Amro illustrate, you have to convert numeric values to formatted strings first in order to display them or concatenate them with other character strings. You can do this using the functions FPRINTF, SPRINTF, NUM2STR, and INT2STR.


With respect to getting ans = 3 as an output, it is probably because you are not assigning the output from answer to a variable. If you want to get all of the output values, you will have to call answer in the following way:

[out1,out2,out3] = answer(1,2);

This will place the value d in out1, the value e in out2, and the value f in out3. When you do the following:

answer(1,2)

MATLAB will automatically assign the first output d (which has the value 3 in this case) to the default workspace variable ans.


With respect to suggesting a good resource for learning MATLAB, you shouldn't underestimate the value of the MATLAB documentation. I've learned most of what I know on my own using it. You can access it online, or within your copy of MATLAB using the functions DOC, HELP, or HELPWIN.

How to center a window on the screen in Tkinter?

I have found a solution for the same question on this site

from tkinter import Tk
from tkinter.ttk import Label
root = Tk()
Label(root, text="Hello world").pack()

# Apparently a common hack to get the window size. Temporarily hide the
# window to avoid update_idletasks() drawing the window in the wrong
# position.
root.withdraw()
root.update_idletasks()  # Update "requested size" from geometry manager

x = (root.winfo_screenwidth() - root.winfo_reqwidth()) / 2
y = (root.winfo_screenheight() - root.winfo_reqheight()) / 2
root.geometry("+%d+%d" % (x, y))

# This seems to draw the window frame immediately, so only call deiconify()
# after setting correct window position
root.deiconify()
root.mainloop()

sure, I changed it correspondingly to my purposes, it works.

How to print current date on python3?

I use this which is standard for every time

import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

How to add a custom HTTP header to every WCF call?

You add it to the call using:

using (OperationContextScope scope = new OperationContextScope((IContextChannel)channel))
{
    MessageHeader<string> header = new MessageHeader<string>("secret message");
    var untyped = header.GetUntypedHeader("Identity", "http://www.my-website.com");
    OperationContext.Current.OutgoingMessageHeaders.Add(untyped);

    // now make the WCF call within this using block
}

And then, server-side you grab it using:

MessageHeaders headers = OperationContext.Current.IncomingMessageHeaders;
string identity = headers.GetHeader<string>("Identity", "http://www.my-website.com");

How to cut first n and last n columns?

Use

cut -b COLUMN_N_BEGINS-COLUMN_N_UNTIL INPUT.TXT > OUTPUT.TXT

-f doesn't work if you have "tabs" in the text file.

Update Query with INNER JOIN between tables in 2 different databases on 1 server

which may be useful

Update
    A INNER JOIN B ON A.COL1=B.COL3
SET
    A.COL2='CHANGED', A.COL4=B.COL4,......
WHERE ....;

Python logging not outputting anything

For anyone here that wants a super-simple answer: just set the level you want displayed. At the top of all my scripts I just put:

import logging
logging.basicConfig(level = logging.INFO)

Then to display anything at or above that level:

logging.info("Hi you just set your fleeb to level plumbus")

It is a hierarchical set of five levels so that logs will display at the level you set, or higher. So if you want to display an error you could use logging.error("The plumbus is broken").

The levels, in increasing order of severity, are DEBUG, INFO, WARNING, ERROR, and CRITICAL. The default setting is WARNING.

This is a good article containing this information expressed better than my answer:
https://www.digitalocean.com/community/tutorials/how-to-use-logging-in-python-3

PHP Deprecated: Methods with the same name

As mentioned in the error, the official manual and the comments:

Replace

public function TSStatus($host, $queryPort)

with

public function __construct($host, $queryPort)

Documentation for using JavaScript code inside a PDF file

Look for books by Ted Padova. Over the years, he has written a series of books called The Acrobat PDF {5,6,7,8,9...} Bible. They contain chapter(s) on JavaScript in PDF files. They are not as comprehensive as the reference documentation listed here, but in the books there are some realistic use-cases discussed in context.

There was also a talk on hacking PDF files by a computer scientist, given at a conference in 2010. The link on the talk's announcement-page to the slides is dead, but Google is your friend-. The talk is not exclusively on JavaScript, though. YouTube video - JavaScript starts at 06:00.

How to loop through all enum values in C#?

foreach(Foos foo in Enum.GetValues(typeof(Foos)))

Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

Because the range for floats is greater than that of integers -- returning an integer could overflow

Java array reflection: isArray vs. instanceof

In most cases, you should use the instanceof operator to test whether an object is an array.

Generally, you test an object's type before downcasting to a particular type which is known at compile time. For example, perhaps you wrote some code that can work with a Integer[] or an int[]. You'd want to guard your casts with instanceof:

if (obj instanceof Integer[]) {
    Integer[] array = (Integer[]) obj;
    /* Use the boxed array */
} else if (obj instanceof int[]) {
    int[] array = (int[]) obj;
    /* Use the primitive array */
} else ...

At the JVM level, the instanceof operator translates to a specific "instanceof" byte code, which is optimized in most JVM implementations.

In rarer cases, you might be using reflection to traverse an object graph of unknown types. In cases like this, the isArray() method can be helpful because you don't know the component type at compile time; you might, for example, be implementing some sort of serialization mechanism and be able to pass each component of the array to the same serialization method, regardless of type.

There are two special cases: null references and references to primitive arrays.

A null reference will cause instanceof to result false, while the isArray throws a NullPointerException.

Applied to a primitive array, the instanceof yields false unless the component type on the right-hand operand exactly matches the component type. In contrast, isArray() will return true for any component type.

How to insert tab character when expandtab option is on in Vim

You can disable expandtab option from within Vim as below:

:set expandtab!

or

:set noet

PS: And set it back when you are done with inserting tab, with "set expandtab" or "set et"

PS: If you have tab set equivalent to 4 spaces in .vimrc (softtabstop), you may also like to set it to 8 spaces in order to be able to insert a tab by pressing tab key once instead of twice (set softtabstop=8).

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

Have you seen CodeIgniter's Language library?

The Language Class provides functions to retrieve language files and lines of text for purposes of internationalization.

In your CodeIgniter system folder you'll find one called language containing sets of language files. You can create your own language files as needed in order to display error and other messages in other languages.

Language files are typically stored in your system/language directory. Alternately you can create a folder called language inside your application folder and store them there. CodeIgniter will look first in your application/language directory. If the directory does not exist or the specified language is not located there CI will instead look in your global system/language folder.

In your case...

  • you need to create a polish_lang.php and english_lang.php inside application/language/polish
  • then create your keys inside that file (e.g. $lang['hello'] = "Witaj";
  • then load it in your controller like $this->lang->load('polish_lang', 'polish');
  • then fetch the line like $this->lang->line('hello'); Just store the return value of this function in a variable so you can use it in your view.

Repeat the steps for the english language and all other languages you need.

SQL Server Installation - What is the Installation Media Folder?

For the SQL Server 2019 (Express Edition) installation, I did the following:

  1. Open SQL Server Installation Center
  2. Click on Installation
  3. Click on New SQL Server stand-alone installation or add features to an existing installation
  4. Browse to C:\SQL2019\Express_ENU and click OK

When or Why to use a "SET DEFINE OFF" in Oracle Database

Here is the example:

SQL> set define off;
SQL> select * from dual where dummy='&var';

no rows selected

SQL> set define on
SQL> /
Enter value for var: X
old   1: select * from dual where dummy='&var'
new   1: select * from dual where dummy='X'

D
-
X

With set define off, it took a row with &var value, prompted a user to enter a value for it and replaced &var with the entered value (in this case, X).

How to trigger a file download when clicking an HTML button or JavaScript

download attribute do it

 <a class="btn btn-success btn-sm" href="/file_path/file.type" download>
     <span>download </span>&nbsp;<i class="fa fa-download"></i>
 </a>

SASS and @font-face

In case anyone was wondering - it was probably my css...

@font-face
  font-family: "bingo"
  src: url('bingo.eot')
  src: local('bingo')
  src: url('bingo.svg#bingo') format('svg')
  src: url('bingo.otf') format('opentype')

will render as

@font-face {
  font-family: "bingo";
  src: url('bingo.eot');
  src: local('bingo');
  src: url('bingo.svg#bingo') format('svg');
  src: url('bingo.otf') format('opentype'); }

which seems to be close enough... just need to check the SVG rendering

Laravel csrf token mismatch for ajax POST Request

You have to add data in your ajax request. I hope so it will be work.

data: {
        "_token": "{{ csrf_token() }}",
        "id": id
        }

DTO pattern: Best way to copy properties between two objects

Wouldn't lambdaj's project function do what you are looking for?

It'll look something like this:

List<UserDTO> userNDtos = project(users, UserDTO.class, on(User.class).getUserName(), on(User.class).getFullName(), .....);

(Define the constructor for UserDTO accordingly...)

Also see here for examples...

Which equals operator (== vs ===) should be used in JavaScript comparisons?

An interesting pictorial representation of the equality comparison between == and ===.

Source: http://dorey.github.io/JavaScript-Equality-Table/


var1 === var2

When using === for JavaScript equality testing, everything is as is. Nothing gets converted before being evaluated.

Equality evaluation of === in JS


var1 == var2

When using == for JavaScript equality testing, some funky conversions take place.

Equality evaluation of == in JS

Moral of the story:

Use === unless you fully understand the conversions that take place with ==.

Bootstrap number validation

you can use PATTERN:

<input class="form-control" minlength="1" pattern="[0-9]*" [(ngModel)]="value" #name="ngModel">

<div *ngIf="name.invalid && (name.dirty || name.touched)" class="text-danger">
  <div *ngIf="name.errors?.pattern">Is not a number</div>
</div>

How to create two columns on a web page?

i recommend to look this article

http://www.456bereastreet.com/lab/developing_with_web_standards/csslayout/2-col/

see 4. Place the columns side by side special

To make the two columns (#main and #sidebar) display side by side we float them, one to the left and the other to the right. We also specify the widths of the columns.

    #main {
    float:left;
    width:500px;
    background:#9c9;
    }
    #sidebar {
    float:right;
    width:250px;
   background:#c9c;
   }

Note that the sum of the widths should be equal to the width given to #wrap in Step 3.

How to set column widths to a jQuery datatable?

Answer from official website

https://datatables.net/reference/option/columns.width

$('#example').dataTable({
    "columnDefs": [
        {
            "width": "20%",
            "targets": 0
        }
    ]
});

How to detect query which holds the lock in Postgres?

This modification of a_horse_with_no_name's answer will give you the blocking queries in addition to just the blocked sessions:

SELECT
    activity.pid,
    activity.usename,
    activity.query,
    blocking.pid AS blocking_id,
    blocking.query AS blocking_query
FROM pg_stat_activity AS activity
JOIN pg_stat_activity AS blocking ON blocking.pid = ANY(pg_blocking_pids(activity.pid));

Questions every good .NET developer should be able to answer?

Know the difference between reference and value types.

Know that events are stored as hard references (i.e. remember to unregister events or the application will leak memory).

Strings are immutable.

Best way to convert list to comma separated string in java

From Apache Commons library:

import org.apache.commons.lang3.StringUtils

Use:

StringUtils.join(slist, ',');

Another similar question and answer here

How add unique key to existing table (with non uniques rows)

I am providing my solution with the assumption on your business logic. Basicall in my design i will allow the table to store only one record for a user-game combination. So I will add a composite key to the table.

PRIMARY KEY (`user_id`,`game_id`)

How to check if a map contains a key in Go?

It is mentioned under "Index expressions".

An index expression on a map a of type map[K]V used in an assignment or initialization of the special form

v, ok = a[x] 
v, ok := a[x] 
var v, ok = a[x]

yields an additional untyped boolean value. The value of ok is true if the key x is present in the map, and false otherwise.

How to execute command stored in a variable?

If you just do eval $cmd when we do cmd="ls -l" (interactively and in a script) we get the desired result. In your case, you have a pipe with a grep without a pattern, so the grep part will fail with an error message. Just $cmd will generate a "command not found" (or some such) message. So try use eval and use a finished command, not one that generates an error message.

Best method for reading newline delimited files and discarding the newlines?

I'd do it like this:

f = open('test.txt')
l = [l for l in f.readlines() if l.strip()]
f.close()
print l

Backporting Python 3 open(encoding="utf-8") to Python 2

I think

from io import open

should do.

Javascript isnull

return (results||0) && results[1] || 0;

The && operator acts as guard and returns the 0 if results if falsy and return the rightmost part if truthy.

Convert string to BigDecimal in java

You are storing 135.69 as String in currency. But instead of passing variable currency, you are again passing 135.69(double value) into new BigDecimal(). So you are seeing a lot of numbers in the output. If you pass the currency variable, your output will be 135.69

How to Disable landscape mode in Android?

Add below commend on your project,

npm install

npm i react-native-orientation-locker

then you use manifest class like, React_Native (Your Project Folder)/ android/app/src/main/AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

<application
  android:name=".MainApplication"
  android:label="@string/app_name"
  android:icon="@mipmap/ic_launcher"
  android:allowBackup="false"
  android:theme="@style/AppTheme">
  <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:screenOrientation="landscape"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
    android:windowSoftInputMode="adjustResize">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
  </activity>
  <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>

Thank You!

JQuery Datatables : Cannot read property 'aDataSort' of undefined

I got the error by having multiple tables on the page and trying to initialize them all at once like this:

$('table').DataTable();

After a lot of trial and error, I initialized them separately and the error went away:

$("#table1-id").DataTable();
$("#table2-id").DataTable();

VarBinary vs Image SQL Server Data Type to Store Binary Data?

varbinary(max) is the way to go (introduced in SQL Server 2005)

How does tuple comparison work in Python?

The Python documentation does explain it.

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

Automatically resize jQuery UI dialog to the width of the content loaded by ajax

I imagine setting float:left for the dialog will work. Presumably the dialog is absolutely positioned by the plugin, in which case its position will be determined by this, but the side-effect of float - making elements only as wide as they need to be to hold content - will still take effect.

This should work if you just put a rule like

.myDialog {float:left}

in your stylesheet, though you may need to set it using jQuery

CSS @font-face not working in ie

Font Squirrel did not work for me. I uploaded a font for conversion to multiple font format for IE support. It performed onversion, which I was able to download. I then uploaded content to my server per specs. I was only either able to get Firefox or IE to work but not both. The solution that worked for me was The Mo Bullet Proofer link above.

Pandas get the most frequent values of a column

By using mode

df.name.mode()
Out[712]: 
0     alex
1    helen
dtype: object

What is Java String interning?

Java interning() method basically makes sure that if String object is present in SCP, If yes then it returns that object and if not then creates that objects in SCP and return its references

for eg: String s1=new String("abc");
        String s2="abc";
        String s3="abc";

s1==s2// false, because 1 object of s1 is stored in heap and other in scp(but this objects doesn't have explicit reference) and s2 in scp
s2==s3// true

now if we do intern on s1
s1=s1.intern() 

//JVM checks if there is any string in the pool with value “abc” is present? Since there is a string object in the pool with value “abc”, its reference is returned.
Notice that we are calling s1 = s1.intern(), so the s1 is now referring to the string pool object having value “abc”.
At this point, all the three string objects are referring to the same object in the string pool. Hence s1==s2 is returning true now.

bootstrap 3 tabs not working properly

In my case, I have two elements with the same id. I could not notice the cause of problem for a long time, because the first such element was hidden.

Break out of a While...Wend loop

A While/Wend loop can only be exited prematurely with a GOTO or by exiting from an outer block (Exit sub/function or another exitable loop)

Change to a Do loop instead:

Do While True
    count = count + 1

    If count = 10 Then
        Exit Do
    End If
Loop

Or for looping a set number of times:

for count = 1 to 10
   msgbox count
next

(Exit For can be used above to exit prematurely)

Finding longest string in array

function allLongestStrings(array) {
    const newArr=[];
    let temp =    Math.max(...(array.map(el => el.length)));    
     array.forEach(item => {
        if(temp == item.length){
          newArr.push(item);
        }
    });
    return newArr;
}

Make more than one chart in same IPython Notebook cell

You can also call the show() function after each plot. e.g

   plt.plot(a)
   plt.show()
   plt.plot(b)
   plt.show()

font-weight is not working properly?

i was also facing the same issue, I resolved it by after selecting the Google's font that i was using, then I clicked on (Family-Selected) minimized tab and then clicked on "CUSTOMIZE" button. Then I selected the font weights that I want and then embedded the updated link in my html..

What is the largest possible heap size with a 64-bit JVM?

If you want to use 32-bit references, your heap is limited to 32 GB.

However, if you are willing to use 64-bit references, the size is likely to be limited by your OS, just as it is with 32-bit JVM. e.g. on Windows 32-bit this is 1.2 to 1.5 GB.

Note: you will want your JVM heap to fit into main memory, ideally inside one NUMA region. That's about 1 TB on the bigger machines. If your JVM spans NUMA regions the memory access and the GC in particular will take much longer. If your JVM heap start swapping it might take hours to GC, or even make your machine unusable as it thrashes the swap drive.

Note: You can access large direct memory and memory mapped sizes even if you use 32-bit references in your heap. i.e. use well above 32 GB.

Compressed oops in the Hotspot JVM

Compressed oops represent managed pointers (in many but not all places in the JVM) as 32-bit values which must be scaled by a factor of 8 and added to a 64-bit base address to find the object they refer to. This allows applications to address up to four billion objects (not bytes), or a heap size of up to about 32Gb. At the same time, data structure compactness is competitive with ILP32 mode.

ISO time (ISO 8601) in Python

import datetime, time    
def convert_enddate_to_seconds(self, ts):
    """Takes ISO 8601 format(string) and converts into epoch time."""
     dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+\
                datetime.timedelta(hours=int(ts[-5:-3]),
                minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
    seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
    return seconds 

>>> import datetime, time
>>> ts = '2012-09-30T15:31:50.262-08:00'
>>> dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+ datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
>>> seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
>>> seconds
1348990310.26

Accessing variables from other functions without using global variables

If there's a chance that you will reuse this code, then I would probably make the effort to go with an object-oriented perspective. Using the global namespace can be dangerous -- you run the risk of hard to find bugs due to variable names that get reused. Typically I start by using an object-oriented approach for anything more than a simple callback so that I don't have to do the re-write thing. Any time that you have a group of related functions in javascript, I think, it's a candidate for an object-oriented approach.

Setting custom UITableViewCells height

in a custom UITableViewCell -controller add this

-(void)layoutSubviews {  

    CGRect newCellSubViewsFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    CGRect newCellViewFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height);

    self.contentView.frame = self.contentView.bounds = self.backgroundView.frame = self.accessoryView.frame = newCellSubViewsFrame;
    self.frame = newCellViewFrame;

    [super layoutSubviews];
}

In the UITableView -controller add this

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [indexPath row] * 1.5; // your dynamic height...
}

How do you create optional arguments in php?

The default value of the argument must be a constant expression. It can't be a variable or a function call.

If you need this functionality however:

function foo($foo, $bar = false)
{
    if(!$bar)
    {
        $bar = $foo;
    }
}

Assuming $bar isn't expected to be a boolean of course.

How to compare arrays in C#?

You can use the Enumerable.SequenceEqual() in the System.Linq to compare the contents in the array

bool isEqual = Enumerable.SequenceEqual(target1, target2);

How to grep recursively, but only in files with certain extensions?

There is no -r option on HP and Sun servers, this way worked for me on my HP server

find . -name "*.c" | xargs grep -i "my great text"

-i is for case insensitive search of string

How to get only the date value from a Windows Forms DateTimePicker control?

@Shoban It looks like the question is tagged c# so here is the appropriate snipped http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.value.aspx

public MyClass()
{
    // Create a new DateTimePicker
    DateTimePicker dateTimePicker1 = new DateTimePicker();
    Controls.Add(dateTimePicker1);
    MessageBox.Show(dateTimePicker1.Value.ToString());

    dateTimePicker1.Value = DateTime.Now.AddDays(1);
    MessageBox.Show(dateTimePicker1.Value.ToString());
 } 

List tables in a PostgreSQL schema

You can select the tables from information_schema

SELECT * FROM information_schema.tables 
WHERE table_schema = 'public'

Printing variables in Python 3.4

Try the format syntax:

print ("{0}. {1} appears {2} times.".format(1, 'b', 3.1415))

Outputs:

1. b appears 3.1415 times.

The print function is called just like any other function, with parenthesis around all its arguments.

Can I connect to SQL Server using Windows Authentication from Java EE webapp?

Unless you have some really compelling reason not to, I suggest ditching the MS JDBC driver.

Instead, use the jtds jdbc driver. Read the README.SSO file in the jtds distribution on how to configure for single-sign-on (native authentication) and where to put the native DLL to ensure it can be loaded by the JVM.

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

After I set core.autocrlf=true I was getting "LF will be replaced by CRLF" (note not "CRLF will be replaced by LF") when I was git adding (or perhaps it was it on git commit?) edited files in windows on a repository (that does use LF) that was checked out before I set core.autocrlf=true.

I made a new checkout with core.autocrlf=true and now I'm not getting those messages.

Application_Start not firing?

The following helps in any case (no matter if you're using IIS, Cassini or whatever):

  1. Set your breakpoint in Application_Start
  2. Start debugging (breakpoint most probably is not hit) -> a page is shown in the browser
  3. Change web.config (e.g. enter a blank line) and save it
  4. Reload the page in the browser -> breakpoint is hit!

Why does this work? When web.config is changed, the web server (IIS, Cassini, etc.) does a recycle, but in this case (for whatever reason), the process keeps the same, so you keep attached to it with the debugger (Visual Studio).

Android Studio: Module won't show up in "Edit Configuration"

It was fixed for me after removing and re-adding the Android and Android-Gradle Facets in the Module Settings dialog.

Add Bean Programmatically to Spring Web App Context

First initialize Property values

MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
mutablePropertyValues.add("hostName", details.getHostName());
mutablePropertyValues.add("port", details.getPort());

DefaultListableBeanFactory context = new DefaultListableBeanFactory();
GenericBeanDefinition connectionFactory = new GenericBeanDefinition();
connectionFactory.setBeanClass(Class);
connectionFactory.setPropertyValues(mutablePropertyValues);

context.registerBeanDefinition("beanName", connectionFactory);

Add to the list of beans

ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerSingleton("beanName", context.getBean("beanName"));

Check if a String contains numbers Java

As I was redirected here searching for a method to find digits in string in Kotlin language, I'll leave my findings here for other folks wanting a solution specific to Kotlin.

Finding out if a string contains digit:

val hasDigits = sampleString.any { it.isDigit() }

Finding out if a string contains only digits:

val hasOnlyDigits = sampleString.all { it.isDigit() }

Extract digits from string:

val onlyNumberString = sampleString.filter { it.isDigit() }

Trust Anchor not found for Android SSL Connection

I had the same problem while connecting from Android client to Kurento server. Kurento server use jks certificates, so I had to convert pem to it. As input for conversion I used cert.pem file and it lead to such errors. But if use fullchain.pem instead of cert.pem - all is OK.

What's the difference between Git Revert, Checkout and Reset?

Reset - On the commit-level, resetting is a way to move the tip of a branch to a different commit. This can be used to remove commits from the current branch.

Revert - Reverting undoes a commit by creating a new commit. This is a safe way to undo changes, as it has no chance of re-writing the commit history. Contrast this with git reset, which does alter the existing commit history. For this reason, git revert should be used to undo changes on a public branch, and git reset should be reserved for undoing changes on a private branch.

You can have a look on this link- Reset, Checkout and Revert

How to check if a file contains a specific string using Bash

if grep -q [string] [filename]
then
    [whatever action]
fi

Example

if grep -q 'my cat is in a tree' /tmp/cat.txt
then
    mkdir cat
fi

How to extract IP Address in Spring MVC Controller get call?

Put this method in your BaseController:

@SuppressWarnings("ConstantConditions")
protected String fetchClientIpAddr() {
    HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest();
    String ip = Optional.ofNullable(request.getHeader("X-FORWARDED-FOR")).orElse(request.getRemoteAddr());
    if (ip.equals("0:0:0:0:0:0:0:1")) ip = "127.0.0.1";
    Assert.isTrue(ip.chars().filter($ -> $ == '.').count() == 3, "Illegal IP: " + ip);
    return ip;
}

php/mySQL on XAMPP: password for phpMyAdmin and mysql_connect different?

if you open localhost/phpmyadmin you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.

Linq: GroupBy, Sum and Count

sometimes you need to select some fields by FirstOrDefault() or singleOrDefault() you can use the below query:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new Models.ResultLine
            {
                ProductName = cl.select(x=>x.Name).FirstOrDefault(),
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

SQL Server after update trigger

Try this script to create a temporary table TESTTEST and watch the order of precedence as the triggers are called in this order: 1) INSTEAD OF, 2) FOR, 3) AFTER

All of the logic is placed in INSTEAD OF trigger and I have 2 examples of how you might code some scenarios...

Good luck...

CREATE TABLE TESTTEST
(
    ID  INT,
    Modified0 DATETIME,
    Modified1 DATETIME
)
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_0] ON [dbo].TESTTEST
INSTEAD OF INSERT,UPDATE,DELETE
AS
BEGIN
    SELECT 'INSTEAD OF'
    SELECT 'TT0.0'
    SELECT * FROM TESTTEST

    SELECT *, 'I' Mode
    INTO #work
    FROM INSERTED

    UPDATE #work SET Mode='U' WHERE ID IN (SELECT ID FROM DELETED)
    INSERT INTO #work (ID, Modified0, Modified1, Mode)
    SELECT ID, Modified0, Modified1, 'D'
    FROM DELETED WHERE ID NOT IN (SELECT ID FROM INSERTED)

    --Check Security or any other logic to add and remove from #work before processing
    DELETE FROM #work WHERE ID=9 -- because you don't want anyone to edit this id?!?!
    DELETE FROM #work WHERE Mode='D' -- because you don't want anyone to delete any records

    SELECT 'EV'
    SELECT * FROM #work

    IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='I'))
    BEGIN
        SELECT 'I0.0'
        INSERT INTO dbo.TESTTEST (ID, Modified0, Modified1)
        SELECT ID, Modified0, Modified1
        FROM #work
        WHERE Mode='I'
        SELECT 'Cool stuff would happen here if you had FOR INSERT or AFTER INSERT triggers.'
        SELECT 'I0.1'
    END

    IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='D'))
    BEGIN
        SELECT 'D0.0'
        DELETE FROM TESTTEST WHERE ID IN (SELECT ID FROM #work WHERE Mode='D')
        SELECT 'Cool stuff would happen here if you had FOR DELETE or AFTER DELETE triggers.'
        SELECT 'D0.1'
    END

    IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='U'))
    BEGIN
        SELECT 'U0.0'
        UPDATE t SET t.Modified0=e.Modified0, t.Modified1=e.Modified1
        FROM dbo.TESTTEST t
        INNER JOIN #work e ON e.ID = t.ID
        WHERE e.Mode='U'
        SELECT 'U0.1'
    END
    DROP TABLE #work

    SELECT 'TT0.1'
    SELECT * FROM TESTTEST
END
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_1] ON [dbo].TESTTEST
FOR UPDATE
AS
BEGIN
    SELECT 'FOR UPDATE'

    SELECT 'TT1.0'
    SELECT * FROM TESTTEST

    SELECT 'I1'
    SELECT * FROM INSERTED

    SELECT 'D1'
    SELECT * FROM DELETED

    SELECT 'TT1.1'
    SELECT * FROM TESTTEST
END
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_2] ON [dbo].TESTTEST
AFTER UPDATE
AS
BEGIN
    SELECT 'AFTER UPDATE'

    SELECT 'TT2.0'
    SELECT * FROM TESTTEST

    SELECT 'I2'
    SELECT * FROM INSERTED

    SELECT 'D2'
    SELECT * FROM DELETED

    SELECT 'TT2.1'
    SELECT * FROM TESTTEST
END
GO

SELECT 'Start'
INSERT INTO TESTTEST (ID, Modified0) VALUES (9, GETDATE())-- not going to insert
SELECT 'RESTART'
INSERT INTO TESTTEST (ID, Modified0) VALUES (10, GETDATE())--going to insert
SELECT 'RESTART'
UPDATE TESTTEST SET Modified1=GETDATE() WHERE ID=10-- gointo to update
SELECT 'RESTART'
DELETE FROM TESTTEST WHERE ID=10-- not going to DELETE
SELECT 'FINISHED'

SELECT * FROM TESTTEST
DROP TABLE TESTTEST

Eclipse Error: "Failed to connect to remote VM"

If you are using windows os then replace line in tomcat configuration Tomcat6\bin\startup.bat.

Replace

call "%EXECUTABLE%" start %CMD_LINE_ARGS%

with

call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

How to edit default dark theme for Visual Studio Code?

The file you are looking for is at,

Microsoft VS Code\resources\app\extensions\theme-defaults\themes

on Windows and search for filename dark_vs.json to locate it on any other system.


Update:

With new versions of VSCode you don't need to hunt for the settings file to customize the theme. Now you can customize your color theme with the workbench.colorCustomizations and editor.tokenColorCustomizations user settings. Documentation on the matter can be found here.

Get model's fields in Django

get_fields() returns a tuple and each element is a Model field type, which can't be used directly as a string. So, field.name will return the field name

my_model_fields = [field.name for field in MyModel._meta.get_fields()]
The above code will return a list conatining all fields name

Example

In [11]: from django.contrib.auth.models import User

In [12]: User._meta.get_fields()
Out[12]: 
(<ManyToOneRel: admin.logentry>,
 <django.db.models.fields.AutoField: id>,
 <django.db.models.fields.CharField: password>,
 <django.db.models.fields.DateTimeField: last_login>,
 <django.db.models.fields.BooleanField: is_superuser>,
 <django.db.models.fields.CharField: username>,
 <django.db.models.fields.CharField: first_name>,
 <django.db.models.fields.CharField: last_name>,
 <django.db.models.fields.EmailField: email>,
 <django.db.models.fields.BooleanField: is_staff>,
 <django.db.models.fields.BooleanField: is_active>,
 <django.db.models.fields.DateTimeField: date_joined>,
 <django.db.models.fields.related.ManyToManyField: groups>,
 <django.db.models.fields.related.ManyToManyField: user_permissions>)

In [13]: [field.name for field in User._meta.get_fields()]
Out[13]: 
['logentry',
 'id',
 'password',
 'last_login',
 'is_superuser',
 'username',
 'first_name',
 'last_name',
 'email',
 'is_staff',
 'is_active',
 'date_joined',
 'groups',
 'user_permissions']

Using BETWEEN in CASE SQL statement

Take out the MONTHS from your case, and remove the brackets... like this:

CASE 
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

You can think of this as being equivalent to:

CASE TRUE
    WHEN RATE_DATE BETWEEN '2010-01-01' AND '2010-01-31' THEN 'JANUARY'
    ELSE 'NOTHING'
END AS 'MONTHS'

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

Another important difference is that Hashtable is thread safe. Hashtable has built in multiple reader/single writer (MR/SW) thread safety which means Hashtable allows ONE writer together with multiple readers without locking. In the case of Dictionary there is no thread safety, if you need thread safety you must implement your own synchronization.

To elaborate further:

Hashtable, provide some thread-safety through the Synchronized property, which returns a thread-safe wrapper around the collection. The wrapper works by locking the entire collection on every add or remove operation. Therefore, each thread that is attempting to access the collection must wait for its turn to take the one lock. This is not scalable and can cause significant performance degradation for large collections. Also, the design is not completely protected from race conditions.

The .NET Framework 2.0 collection classes like List<T>, Dictionary<TKey, TValue>, etc do not provide any thread synchronization; user code must provide all synchronization when items are added or removed on multiple threads concurrently If you need type safety as well thread safety, use concurrent collections classes in the .NET Framework. Further reading here.

How do I read and parse an XML file in C#?

Here's an application I wrote for reading xml sitemaps:

using System;
using System.Collections.Generic;
using System.Windows.Forms; 
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
using System.Xml;

namespace SiteMapReader
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please Enter the Location of the file");

            // get the location we want to get the sitemaps from 
            string dirLoc = Console.ReadLine();

            // get all the sitemaps 
            string[] sitemaps = Directory.GetFiles(dirLoc);
            StreamWriter sw = new StreamWriter(Application.StartupPath + @"\locs.txt", true);

            // loop through each file 
            foreach (string sitemap in sitemaps)
            {
                try
                {
                    // new xdoc instance 
                    XmlDocument xDoc = new XmlDocument();

                    //load up the xml from the location 
                    xDoc.Load(sitemap);

                    // cycle through each child noed 
                    foreach (XmlNode node in xDoc.DocumentElement.ChildNodes)
                    {
                        // first node is the url ... have to go to nexted loc node 
                        foreach (XmlNode locNode in node)
                        {
                            // thereare a couple child nodes here so only take data from node named loc 
                            if (locNode.Name == "loc")
                            {
                                // get the content of the loc node 
                                string loc = locNode.InnerText;

                                // write it to the console so you can see its working 
                                Console.WriteLine(loc + Environment.NewLine);

                                // write it to the file 
                                sw.Write(loc + Environment.NewLine);
                            }
                        }
                    }
                }
                catch { }
            }
            Console.WriteLine("All Done :-)"); 
            Console.ReadLine(); 
        }

        static void readSitemap()
        {
        }
    }
}

Code on Paste Bin http://pastebin.com/yK7cSNeY

Print very long string completely in pandas dataframe

The way I often deal with the situation you describe is to use the .to_csv() method and write to stdout:

import sys

df.to_csv(sys.stdout)

Update: it should now be possible to just use None instead of sys.stdout with similar effect!

This should dump the whole dataframe, including the entirety of any strings. You can use the to_csv parameters to configure column separators, whether the index is printed, etc. It will be less pretty than rendering it properly though.

I posted this originally in answer to the somewhat-related question at Output data from all columns in a dataframe in pandas

Set padding for UITextField with UITextBorderStyleNone

Just subclass UITextField like this (Swift version):

import UIKit

class CustomTextField: UITextField {

    override func textRectForBounds(bounds: CGRect) -> CGRect {
       return CGRectInset(bounds, 25.0, 0)
    }

    override func editingRectForBounds(bounds: CGRect) -> CGRect {
       return self.textRectForBounds(bounds)
    }

}

This adds horizontal padding of 25.0 points either side.

How to check if a variable is an integer or a string?

if you want to check what it is:

>>>isinstance(1,str)
False
>>>isinstance('stuff',str)
True
>>>isinstance(1,int)
True
>>>isinstance('stuff',int)
False

if you want to get ints from raw_input

>>>x=raw_input('enter thing:')
enter thing: 3
>>>try: x = int(x)
   except: pass

>>>isinstance(x,int)
True

How to parseInt in Angular.js

<input type="number" string-to-number ng-model="num1">
<input type="number" string-to-number ng-model="num2">

Total: {{num1 + num2}}

and in js :

parseInt($scope.num1) + parseInt($scope.num2)

Printing out a linked list using toString

public static void main(String[] args) {

    LinkedList list = new LinkedList();
    list.insertFront(1);
    list.insertFront(2);
    list.insertFront(3);
    System.out.println(list.toString());
}

String toString() {
            String result = "";
            LinkedListNode current = head;
            while(current.getNext() != null){
                result += current.getData();
                if(current.getNext() != null){
                     result += ", ";
                }
                current = current.getNext();
            }
            return "List: " + result;
}

Timing Delays in VBA

If you are in Excel VBA you can use the following.

Application.Wait(Now + TimeValue("0:00:01"))

(The time string should look like H:MM:SS.)

How to display an error message in an ASP.NET Web Application

The errors in ASP.Net are saved on the Server.GetLastError property,

Or i would put a label on the asp.net page for displaying the error.

try
{
    do something
}
catch (YourException ex)
{
    errorLabel.Text = ex.Message;
    errorLabel.Visible = true;
}

Git: Merge a Remote branch locally

Whenever I do a merge, I get into the branch I want to merge into (e.g. "git checkout branch-i-am-working-in") and then do the following:

git merge origin/branch-i-want-to-merge-from

Equivalent of LIMIT for DB2

Developed this method:

You NEED a table that has an unique value that can be ordered.

If you want rows 10,000 to 25,000 and your Table has 40,000 rows, first you need to get the starting point and total rows:

int start = 40000 - 10000;

int total = 25000 - 10000;

And then pass these by code to the query:

SELECT * FROM 
(SELECT * FROM schema.mytable 
ORDER BY userId DESC fetch first {start} rows only ) AS mini 
ORDER BY mini.userId ASC fetch first {total} rows only

jQuery Keypress Arrow Keys

You can check wether an arrow key is pressed by:

$(document).keydown(function(e){
    if (e.keyCode > 36 && e.keyCode < 41) 
      alert( "arrowkey pressed" );          
});

jsfiddle demo

getting the X/Y coordinates of a mouse click on an image with jQuery

Take a look at http://jsfiddle.net/TroyAlford/ZZEk8/ for a working example of the below:

<img id='myImg' src='/my/img/link.gif' />

<script type="text/javascript">
    $(document).bind('click', function () {
        // Add a click-handler to the image.
        $('#myImg').bind('click', function (ev) {
            var $img = $(ev.target);

            var offset = $img.offset();
            var x = ev.clientX - offset.left;
            var y = ev.clientY - offset.top;

            alert('clicked at x: ' + x + ', y: ' + y);
        });
    });
</script>

Note that the above will get you the x and the y relative to the image's box - but will not correctly take into account margin, border and padding. These elements aren't actually part of the image, in your case - but they might be part of the element that you would want to take into account.

In this case, you should also use $div.outerWidth(true) - $div.width() and $div.outerHeight(true) - $div.height() to calculate the amount of margin / border / etc.

Your new code might look more like:

<img id='myImg' src='/my/img/link.gif' />

<script type="text/javascript">
    $(document).bind('click', function () {
        // Add a click-handler to the image.
        $('#myImg').bind('click', function (ev) {
            var $img = $(ev.target);

            var offset = $img.offset(); // Offset from the corner of the page.
            var xMargin = ($img.outerWidth() - $img.width()) / 2;
            var yMargin = ($img.outerHeight() - $img.height()) / 2;
            // Note that the above calculations assume your left margin is 
            // equal to your right margin, top to bottom, etc. and the same 
            // for borders.

            var x = (ev.clientX + xMargin) - offset.left;
            var y = (ev.clientY + yMargin) - offset.top;

            alert('clicked at x: ' + x + ', y: ' + y);
        });
    });
</script>

How to get autocomplete in jupyter notebook without using tab?

Add the below to your keyboard user preferences on jupyter lab (Settings->Advanced system editor)

{
    "shortcuts":[
        {
            "command": "completer:invoke-file",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-FileEditor .jp-mod-completer-enabled"
        },
        {
            "command": "completer:invoke-file",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-FileEditor .jp-mod-completer-enabled"
        },
        {
            "command": "completer:invoke-notebook",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode .jp-mod-completer-enabled"
        }

    ]
}

How to get URL parameter using jQuery or plain JavaScript?

Get the param from a string:

Object.defineProperty(String.prototype, 'urlParam', {

    value: function (param) {

    "use strict";

    var str = this.trim();

    var regex = "[\?&]" + param + "=([^&#]*)";

    var results = new RegExp(regex, "i").exec(str);

    return (results !== null) ? results[1] : '';

    }
});

to use:

var src = 'http://your-url.com/?param=value'

console.log(src.urlParam(param)); // returns 'value'

onchange equivalent in angular2

We can use Angular event bindings to respond to any DOM event. The syntax is simple. We surround the DOM event name in parentheses and assign a quoted template statement to it. -- reference

Since change is on the list of standard DOM events, we can use it:

(change)="saverange()"

In your particular case, since you're using NgModel, you could break up the two-way binding like this instead:

[ngModel]="range" (ngModelChange)="saverange($event)"

Then

saverange(newValue) {
  this.range = newValue;
  this.Platform.ready().then(() => {
     this.rootRef.child("users").child(this.UserID).child('range').set(this.range)
  })
} 

However, with this approach saverange() is called with every keystroke, so you're probably better off using (change).

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

How to dismiss ViewController in Swift?

So if you wanna dismiss your Viewcontroller use this. This code is written in button action to dismiss VC

  @IBAction func cancel(sender: AnyObject) {
   dismiss(animated: true, completion: nil)
  }

From inside of a Docker container, how do I connect to the localhost of the machine?

Solution for Linux (kernel >=3.6).

Ok, your localhost server has default docker interface docker0 with ip address 172.17.0.1. Your container started with default network settings --net="bridge".

  1. Enable route_localnet for docker0 interface:
    $ sysctl -w net.ipv4.conf.docker0.route_localnet=1
  2. Add this rules to iptables:
    $ iptables -t nat -I PREROUTING -i docker0 -d 172.17.0.1 -p tcp --dport 3306 -j DNAT --to 127.0.0.1:3306
    $ iptables -t filter -I INPUT -i docker0 -d 127.0.0.1 -p tcp --dport 3306 -j ACCEPT
  3. Create mysql user with access from '%' that mean - from anyone, excluding localhost:
    CREATE USER 'user'@'%' IDENTIFIED BY 'password';
  4. Change in your script the mysql-server address to 172.17.0.1


From the kernel documentation:

route_localnet - BOOLEAN: Do not consider loopback addresses as martian source or destination while routing. This enables the use of 127/8 for local routing purposes (default FALSE).

Rotation of 3D vector?

Disclaimer: I am the author of this package

While special classes for rotations can be convenient, in some cases one needs rotation matrices (e.g. for working with other libraries like the affine_transform functions in scipy). To avoid everyone implementing their own little matrix generating functions, there exists a tiny pure python package which does nothing more than providing convenient rotation matrix generating functions. The package is on github (mgen) and can be installed via pip:

pip install mgen

Example usage copied from the readme:

import numpy as np
np.set_printoptions(suppress=True)

from mgen import rotation_around_axis
from mgen import rotation_from_angles
from mgen import rotation_around_x

matrix = rotation_from_angles([np.pi/2, 0, 0], 'XYX')
matrix.dot([0, 1, 0])
# array([0., 0., 1.])

matrix = rotation_around_axis([1, 0, 0], np.pi/2)
matrix.dot([0, 1, 0])
# array([0., 0., 1.])

matrix = rotation_around_x(np.pi/2)
matrix.dot([0, 1, 0])
# array([0., 0., 1.])

Note that the matrices are just regular numpy arrays, so no new data-structures are introduced when using this package.

How to squash all git commits into one?

This worked best for me.

git rebase -X ours -i master

This will git will prefer your feature branch to master; avoiding the arduous merge edits. Your branch needs to be up to date with master.

ours
           This resolves any number of heads, but the resulting tree of the merge is always that of the current
           branch head, effectively ignoring all changes from all other branches. It is meant to be used to
           supersede old development history of side branches. Note that this is different from the -Xours
           option to the recursive merge strategy.

Can I remove the URL from my print css, so the web address doesn't print?

you can try this in the stylesheet:

@page{size:auto; margin-bottom:5mm;}

But this also removes the page number

Creating a .dll file in C#.Net

To create a DLL File, click on New project, then select Class Library.

Enter your code into the class file that was automatically created for you and then click Build Solution from the Debug menu.

Now, look in your directory: ../debug/release/YOURDLL.dll

There it is! :)

P.S. DLL files cannot be run just like normal applciation (exe) files. You'll need to create a separate project (probably a win forms app) and then add your dll file to that project as a "Reference", you can do this by going to the Solution explorer, right clicking your project Name and selecting Add Reference then browsing to whereever you saved your dll file.

For more detail please click HERE

Checking if a textbox is empty in Javascript

onchange will work only if the value of the textbox changed compared to the value it had before, so for the first time it won't work because the state didn't change.

So it is better to use onblur event or on submitting the form.

_x000D_
_x000D_
function checkTextField(field) {_x000D_
  document.getElementById("error").innerText =_x000D_
    (field.value === "") ? "Field is empty." : "Field is filled.";_x000D_
}
_x000D_
<input type="text" onblur="checkTextField(this);" />_x000D_
<p id="error"></p>
_x000D_
_x000D_
_x000D_

(Or old live demo.)

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

If you're using AVD manager add a hardware property Keyboard support and set it to false.

That should disable the shown keyboard, and show the virtual one.

How to empty a char array?

By "empty an array" if you mean reset to 0, then you can use bzero.

#include <strings.h>  
void bzero(void *s, size_t n);  

If you want to fill the array with some other default character then you may use memset function.

#include <string.h>  
void *memset(void *s, int c, size_t n);  

Define css class in django Forms

You could also use Django Crispy Forms, it's a great tool to define forms in case you'd like to use some CSS framework like Bootstrap or Foundation. And it's easy to specify classes for your form fields there.

Your form class would like this then:

from django import forms

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, Field
from crispy_forms.bootstrap import FormActions

class SampleClass(forms.Form):
    name = forms.CharField(max_length=30)
    age = forms.IntegerField()
    django_hacker = forms.BooleanField(required=False)

    helper = FormHelper()
    helper.form_class = 'your-form-class'
    helper.layout = Layout(
        Field('name', css_class='name-class'),
        Field('age', css_class='age-class'),
        Field('django_hacker', css-class='hacker-class'),
        FormActions(
            Submit('save_changes', 'Save changes'),
        )
    )

What does "hashable" mean in Python?

All the answers here have good working explanation of hashable objects in python, but I believe one needs to understand the term Hashing first.

Hashing is a concept in computer science which is used to create high performance, pseudo random access data structures where large amount of data is to be stored and accessed quickly.

For example, if you have 10,000 phone numbers, and you want to store them in an array (which is a sequential data structure that stores data in contiguous memory locations, and provides random access), but you might not have the required amount of contiguous memory locations.

So, you can instead use an array of size 100, and use a hash function to map a set of values to same indices, and these values can be stored in a linked list. This provides a performance similar to an array.

Now, a hash function can be as simple as dividing the number with the size of the array and taking the remainder as the index.

For more detail refer to https://en.wikipedia.org/wiki/Hash_function

Here is another good reference: http://interactivepython.org/runestone/static/pythonds/SortSearch/Hashing.html

How to get current foreground activity context in android?

@lockwobr Thanks for update

This does not work 100% of the time in api version 16, if you read the code on github the function "currentActivityThread" was change in Kitkat, so I want to say version 19ish, kind of hard to match api version to releases in github.

Having access to the current Activity is very handy. Wouldn’t it be nice to have a static getActivity method returning the current Activity with no unnecessary questions?

The Activity class is very useful. It gives access to the application’s UI thread, views, resources, and many more. Numerous methods require a Context, but how to get the pointer? Here are some ways:

  • Tracking the application’s state using overridden lifecycle methods. You have to store the current Activity in a static variable and you need access to the code of all Activities.
  • Tracking the application’s state using Instrumentation. Declare Instrumentation in the manifest, implement it and use its methods to track Activity changes. Passing an Activity pointer to methods and classes used in your Activities. Injecting the pointer using one of the code injection libraries. All of these approaches are rather inconvenient; fortunately, there is a much easier way to get the current Activity.
  • Seems like the system needs access to all Activities without the issues mentioned above. So, most likely there is a way to get Activities using only static calls. I spent a lot of time digging through the Android sources on grepcode.com, and I found what I was looking for. There is a class called ActivityThread. This class has access to all Activities and, what’s even better, has a static method for getting the current ActivityThread. There is only one little problem – the Activity list has package access.

Easy to solve using reflection:

public static Activity getActivity() {
    Class activityThreadClass = Class.forName("android.app.ActivityThread");
    Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
    Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
    activitiesField.setAccessible(true);

    Map<Object, Object> activities = (Map<Object, Object>) activitiesField.get(activityThread);
    if (activities == null)
        return null;

    for (Object activityRecord : activities.values()) {
        Class activityRecordClass = activityRecord.getClass();
        Field pausedField = activityRecordClass.getDeclaredField("paused");
        pausedField.setAccessible(true);
        if (!pausedField.getBoolean(activityRecord)) {
            Field activityField = activityRecordClass.getDeclaredField("activity");
            activityField.setAccessible(true);
            Activity activity = (Activity) activityField.get(activityRecord);
            return activity;
        }
    }

    return null;
}

Such a method can be used anywhere in the app and it’s much more convenient than all of the mentioned approaches. Moreover, it seems like it’s not as unsafe as it looks. It doesn’t introduce any new potential leaks or null pointers.

The above code snippet lacks exception handling and naively assumes that the first running Activity is the one we’re looking for. You might want to add some additional checks.

Blog Post

Counting in a FOR loop using Windows Batch script

for a = 1 to 100 step 1

Command line in Windows . Please use %%a if running in Batch file.

    for /L %a in (1,1,100) Do echo %a 

"Eliminate render-blocking CSS in above-the-fold content"

The 2019 optimal solution for this is HTTP/2 Server Push.

You do not need any hacky javascript solutions or inline styles. However, you do need a server that supports HTTP 2.0 (any modern server version will), which itself requires your server to run SSL. However, with Let's Encrypt there's no reason not to be using SSL anyway.

My site https://r.je/ has a 100/100 score for both mobile and desktop.

The reason for these errors is that the browser gets the HTML, then has to wait for the CSS to be downloaded before the page can be rendered. Using HTTP2 you can send both the HTML and the CSS at the same time.

You can use HTTP/2 push by setting the Link header.

Apache example (.htaccess):

Header add Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload"

For NGINX you can add the header to your location tag in the server configuration:

location = / {
    add_header Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload";
}

With this header set, the browser receives the HTML and CSS at the same time which stops the CSS from blocking rendering.

You will want to tweak it so that the CSS is only sent on the first request, but the Link header is the most complete and least hacky solution to "Eliminate Render Blocking Javascript and CSS"

For a detailed discussion, take a look at my post here: Eliminate Render Blocking CSS using HTTP/2 Push

Check if one list contains element from the other

To shorten Narendra's logic, you can use this:

boolean var = lis1.stream().anyMatch(element -> list2.contains(element));

How to detect a textbox's content has changed

How about this:

< jQuery 1.7

$("#input").bind("propertychange change keyup paste input", function(){
    // do stuff;
});

> jQuery 1.7

$("#input").on("propertychange change keyup paste input", function(){
    // do stuff;
});

This works in IE8/IE9, FF, Chrome

Maximum number of records in a MySQL database table

In InnoDB, with a limit on table size of 64 terabytes and a MySQL row-size limit of 65,535 there can be 1,073,741,824 rows. That would be minimum number of records utilizing maximum row-size limit. However, more records can be added if the row size is smaller .

href around input type submit

Why would you want to put a submit button inside an anchor? You are either trying to submit a form or go to a different page. Which one is it?

Either submit the form:

<input type="submit" class="button_active" value="1" />

Or go to another page:

<input type="button" class="button_active" onclick="location.href='1.html';" />

Using HTML5 file uploads with AJAX and jQuery

It's not too hard. Firstly, take a look at FileReader Interface.

So, when the form is submitted, catch the submission process and

var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...


function shipOff(event) {
    var result = event.target.result;
    var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
    $.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}

Then, on the server side (i.e. myscript.php):

$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);

Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg in /uploads/ on your server, and respond with a JSON variable (to a continueSubmission() function) containing the fileName on the server.

Check out fwrite() and jQuery.post().

On the above page it details how to use readAsBinaryString(), readAsDataUrl(), and readAsArrayBuffer() for your other needs (e.g. images, videos, etc).

How to position one element relative to another with jQuery?

NOTE: This requires jQuery UI (not just jQuery).

You can now use:

$("#my_div").position({
    my:        "left top",
    at:        "left bottom",
    of:        this, // or $("#otherdiv")
    collision: "fit"
});

For fast positioning (jQuery UI/Position).

You can download jQuery UI here.

How to add a reference programmatically

Browsing the registry for guids or using paths, which method is best. If browsing the registry is no longer necessary, won't it be the better way to use guids? Office is not always installed in the same directory. The installation path can be manually altered. Also the version number is a part of the path. I could have never predicted that Microsoft would ever add '(x86)' to 'Program Files' before the introduction of 64 bits processors. If possible I would try to avoid using a path.

The code below is derived from Siddharth Rout's answer, with an additional function to list all the references that are used in the active workbook. What if I open my workbook in a later version of Excel? Will the workbook still work without adapting the VBA code? I have already checked that the guids for office 2003 and 2010 are identical. Let's hope that Microsoft doesn't change guids in future versions.

The arguments 0,0 (from .AddFromGuid) should use the latest version of a reference (which I have not been able to test).

What are your thoughts? Of course we cannot predict the future but what can we do to make our code version proof?

Sub AddReferences(wbk As Workbook)
    ' Run DebugPrintExistingRefs in the immediate pane, to show guids of existing references
    AddRef wbk, "{00025E01-0000-0000-C000-000000000046}", "DAO"
    AddRef wbk, "{00020905-0000-0000-C000-000000000046}", "Word"
    AddRef wbk, "{91493440-5A91-11CF-8700-00AA0060263B}", "PowerPoint"
End Sub

Sub AddRef(wbk As Workbook, sGuid As String, sRefName As String)
    Dim i As Integer
    On Error GoTo EH
    With wbk.VBProject.References
        For i = 1 To .Count
            If .Item(i).Name = sRefName Then
               Exit For
            End If
        Next i
        If i > .Count Then
           .AddFromGuid sGuid, 0, 0 ' 0,0 should pick the latest version installed on the computer
        End If
    End With
EX: Exit Sub
EH: MsgBox "Error in 'AddRef'" & vbCrLf & vbCrLf & err.Description
    Resume EX
    Resume ' debug code
End Sub

Public Sub DebugPrintExistingRefs()
    Dim i As Integer
    With Application.ThisWorkbook.VBProject.References
        For i = 1 To .Count
            Debug.Print "    AddRef wbk, """ & .Item(i).GUID & """, """ & .Item(i).Name & """"
        Next i
    End With
End Sub

The code above does not need the reference to the "Microsoft Visual Basic for Applications Extensibility" object anymore.

Script to get the HTTP status code of a list of urls?

Due to https://mywiki.wooledge.org/BashPitfalls#Non-atomic_writes_with_xargs_-P (output from parallel jobs in xargs risks being mixed), I would use GNU Parallel instead of xargs to parallelize:

cat url.lst |
  parallel -P0 -q curl -o /dev/null --silent --head --write-out '%{url_effective}: %{http_code}\n' > outfile

In this particular case it may be safe to use xargs because the output is so short, so the problem with using xargs is rather that if someone later changes the code to do something bigger, it will no longer be safe. Or if someone reads this question and thinks he can replace curl with something else, then that may also not be safe.

Creating a Facebook share button with customized url, title and image

Crude, but it works on our system:

<div class="block-share spread-share p-t-md">
  <a href="http://www.facebook.com/share.php?u=http://www.voteleavetakecontrol.org/our_affiliates&title=Farmers+for+Britain+have+made+the+sensible+decision+to+Vote+Leave.+Be+part+of+a+better+future+for+us+all.+Please+share!" 
     target="_blank">
    <button class="btn btn-social btn-facebook">
      <span class="icon icon-facebook">
      </span> 
      Share on Facebook
    </button>
  </a>

  <a href="https://www.facebook.com/FarmersForBritain" target="_blank">
    <button class="btn btn-social btn-facebook">
      <span class="icon icon-facebook">
      </span>
      Like  on Facebook
    </button>
  </a>
</div>

One line ftp server in python

Obligatory Twisted example:

twistd -n ftp

And probably useful:

twistd ftp --help

Usage: twistd [options] ftp [options].
WARNING: This FTP server is probably INSECURE do not use it.
Options:
  -p, --port=           set the port number [default: 2121]
  -r, --root=           define the root of the ftp-site. [default:
                    /usr/local/ftp]
  --userAnonymous=  Name of the anonymous user. [default: anonymous]
  --password-file=  username:password-style credentials database
  --version         
  --help            Display this help and exit.

How to execute Table valued function

You can execute it just as you select a table using SELECT clause. In addition you can provide parameters within parentheses.

Try with below syntax:

SELECT * FROM yourFunctionName(parameter1, parameter2)

Creating for loop until list.length

In Python you can iterate over the list itself:

for item in my_list:
   #do something with item

or to use indices you can use xrange():

for i in xrange(1,len(my_list)):    #as indexes start at zero so you 
                                    #may have to use xrange(len(my_list))
    #do something here my_list[i]

There's another built-in function called enumerate(), which returns both item and index:

for index,item in enumerate(my_list):
    # do something here

examples:

In [117]: my_lis=list('foobar')

In [118]: my_lis
Out[118]: ['f', 'o', 'o', 'b', 'a', 'r']

In [119]: for item in my_lis:
    print item
   .....:     
f
o
o
b
a
r

In [120]: for i in xrange(len(my_lis)):
    print my_lis[i]
   .....:     
f
o
o
b
a
r

In [122]: for index,item in enumerate(my_lis):
    print index,'-->',item
   .....:     
0 --> f
1 --> o
2 --> o
3 --> b
4 --> a
5 --> r

Why should a Java class implement comparable?

For example when you want to have a sorted collection or map

force line break in html table cell

I suggest you use a wrapper div or paragraph:

<td><p style="width:50%;">Text only allowed to extend 50% of the cell.</p></td>

And you can make a class out of it:

<td class="linebreak"><p>Text only allowed to extend 50% of the cell.</p></td>

td.linebreak p {
    width: 50%;
}

All of this assuming that you meant 50% as in 50% of the cell.

Why can't a text column have a default value in MySQL?

Without any deep knowledge of the mySQL engine, I'd say this sounds like a memory saving strategy. I assume the reason is behind this paragraph from the docs:

Each BLOB or TEXT value is represented internally by a separately allocated object. This is in contrast to all other data types, for which storage is allocated once per column when the table is opened.

It seems like pre-filling these column types would lead to memory usage and performance penalties.

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

I have been having this same problem for a few days and many uploads, seemed to work when I logged out of apple developer portal on my PC (which I use instead of my Mac to view the portal) upload the new version via my Mac and log into the developer portal on the Mac I was using to upload the ipa, seemed to work straight away after that, guess apple just really hates Windows or being logged in from a different computer is a problem.

How can foreign key constraints be temporarily disabled using T-SQL?

Find the constraint

SELECT * 
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('TABLE_NAME')

Execute the SQL generated by this SQL

SELECT 
    'ALTER TABLE ' +  OBJECT_SCHEMA_NAME(parent_object_id) +
    '.[' + OBJECT_NAME(parent_object_id) + 
    '] DROP CONSTRAINT ' + name
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('TABLE_NAME')

Safeway.

Note: Added solution for droping the constraint so that table can be dropped or modified without any constraint error.

Integer division with remainder in JavaScript?

I did some speed tests on Firefox.

-100/3             // -33.33..., 0.3663 millisec
Math.floor(-100/3) // -34,       0.5016 millisec
~~(-100/3)         // -33,       0.3619 millisec
(-100/3>>0)        // -33,       0.3632 millisec
(-100/3|0)         // -33,       0.3856 millisec
(-100-(-100%3))/3  // -33,       0.3591 millisec

/* a=-100, b=3 */
a/b                // -33.33..., 0.4863 millisec
Math.floor(a/b)    // -34,       0.6019 millisec
~~(a/b)            // -33,       0.5148 millisec
(a/b>>0)           // -33,       0.5048 millisec
(a/b|0)            // -33,       0.5078 millisec
(a-(a%b))/b        // -33,       0.6649 millisec

The above is based on 10 million trials for each.

Conclusion: Use (a/b>>0) (or (~~(a/b)) or (a/b|0)) to achieve about 20% gain in efficiency. Also keep in mind that they are all inconsistent with Math.floor, when a/b<0 && a%b!=0.

How can you get the active users connected to a postgreSQL database via SQL?

Using balexandre's info:

SELECT usesysid, usename FROM pg_stat_activity;

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

@jk1 answer is perfect, since @igor Ganapolsky asked, why can't we use Mockito.mock here? i post this answer.

For that we have provide one setter method for myobj and set the myobj value with mocked object.

class MyClass {
    MyInterface myObj;

    public void abc() {
        myObj.myMethodToBeVerified (new String("a"), new String("b"));
    }

    public void setMyObj(MyInterface obj)
    {
        this.myObj=obj;
    }
}

In our Test class, we have to write below code

class MyClassTest {

MyClass myClass = new MyClass();

    @Mock
    MyInterface myInterface;

    @test
    testAbc() {
        myclass.setMyObj(myInterface); //it is good to have in @before method
        myClass.abc();
        verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
     }
}

Determine the number of lines within a text file

You can launch the "wc.exe" executable (comes with UnixUtils and does not need installation) run as an external process. It supports different line count methods (like unix vs mac vs windows).

How to force a line break in a long word in a DIV?

From MDN:

The overflow-wrap CSS property specifies whether or not the browser should insert line breaks within words to prevent text from overflowing its content box.

In contrast to word-break, overflow-wrap will only create a break if an entire word cannot be placed on its own line without overflowing.

So you can use:

overflow-wrap: break-word;

Can I use?

How to download files using axios

The function to make the API call with axios:

  function getFileToDownload (apiUrl) {
     return axios.get(apiUrl, {
       responseType: 'arraybuffer',
       headers: {
         'Content-Type': 'application/json'
       }
     })
  }

Call the function and then download the excel file you get:

getFileToDownload('putApiUrlHere')
  .then (response => {
      const type = response.headers['content-type']
      const blob = new Blob([response.data], { type: type, encoding: 'UTF-8' })
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = 'file.xlsx'
      link.click()
  })

How to get a certain element in a list, given the position?

std::list doesn't provide any function to get element given an index. You may try to get it by writing some code, which I wouldn't recommend, because that would be inefficient if you frequently need to do so.

What you need is : std::vector. Use it as:

std::vector<Object> objects;
objects.push_back(myObject);

Object const & x = objects[0];    //index isn't checked
Object const & y = objects.at(0); //index is checked 

VB.net: Date without time

I almost always use the standard formating ShortDateString, because I want the user to be in control of the actual output of the date.

Code

   Dim d As DateTime = Now
   Debug.WriteLine(d.ToLongDateString)
   Debug.WriteLine(d.ToShortDateString)
   Debug.WriteLine(d.ToString("d"))
   Debug.WriteLine(d.ToString("yyyy-MM-dd"))

Results

Wednesday, December 10, 2008
12/10/2008
12/10/2008
2008-12-10

Note that these results will vary depending on the culture settings on your computer.

Spring boot Security Disable security

For Spring Boot 2 following properties are deprecated in application.yml configuration

  security.basic.enabled: false
  management.security.enabled: false

To disable security for Sprint Boot 2 Basic + Actuator Security following properties can be used in application.yml file instead of annotation based exclusion (@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class}))

  spring:
    autoconfigure:
      exclude[0]: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
      exclude[1]: org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration

For application.properties syntax would be like

spring.autoconfigure.exclude[0]=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

html <input type="text" /> onchange event not working

It is better to use onchange(event) with <select>. With <input> you can use below event:

- onkeyup(event)
- onkeydown(event)
- onkeypress(event)

bad operand types for binary operator "&" java

You have to be more precise, using parentheses, otherwise Java will not use the order of operands that you want it to use.

if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){

Becomes

if (((a[0] & 1) == 0) && ((a[1] & 1) == 0) && ((a[2] & 1) == 0)){

What is the equivalent of 'describe table' in SQL Server?

Just in case you don't want to use stored proc, here's a simple query version

select * 
  from information_schema.columns 
 where table_name = 'aspnet_Membership'
 order by ordinal_position

Rubymine: How to make Git ignore .idea files created by Rubymine

Add .idea to ~/.gitignore_global and follow the instructions here to get .gitignore_global working:

Git global ignore not working

Then you don't have to ever add it to an individual .gitignore file.

Row names & column names in R

And another expansion:

# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)

If you want to assign new column names you can do following on data.frame:

# an identical effect can be achieved with colnames()   
names(d) <- LETTERS[1:5]
> d
  A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3

If you, however run previous command on matrix, you'll mess things up:

names(m) <- LETTERS[1:5]
> m
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    2    4    3    4
[2,]    2    2    3    1    3
[3,]    3    2    1    2    4
[4,]    4    3    3    3    2
[5,]    1    3    2    4    3
attr(,"names")
 [1] "A" "B" "C" "D" "E" NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA 
[20] NA  NA  NA  NA  NA  NA 

Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames().

So there...

How to urlencode a querystring in Python?

If the urllib.parse.urlencode( ) is giving you errors , then Try the urllib3 module .

The syntax is as follows :

import urllib3
urllib3.request.urlencode({"user" : "john" }) 

How to make pylab.savefig() save image for 'maximized' window instead of default size

I did the same search time ago, it seems that he exact solution depends on the backend.

I have read a bunch of sources and probably the most useful was the answer by Pythonio here How to maximize a plt.show() window using Python I adjusted the code and ended up with the function below. It works decently for me on windows, I mostly use Qt, where I use it quite often, while it is minimally tested with other backends.

Basically it consists in identifying the backend and calling the appropriate function. Note that I added a pause afterwards because I was having issues with some windows getting maximized and others not, it seems this solved for me.

def maximize(backend=None,fullscreen=False):
    """Maximize window independently on backend.
    Fullscreen sets fullscreen mode, that is same as maximized, but it doesn't have title bar (press key F to toggle full screen mode)."""
    if backend is None:
        backend=matplotlib.get_backend()
    mng = plt.get_current_fig_manager()

    if fullscreen:
        mng.full_screen_toggle()
    else:
        if backend == 'wxAgg':
            mng.frame.Maximize(True)
        elif backend == 'Qt4Agg' or backend == 'Qt5Agg':
            mng.window.showMaximized()
        elif backend == 'TkAgg':
            mng.window.state('zoomed') #works fine on Windows!
        else:
            print ("Unrecognized backend: ",backend) #not tested on different backends (only Qt)
    plt.show()

    plt.pause(0.1) #this is needed to make sure following processing gets applied (e.g. tight_layout)

string decode utf-8

Try looking at decode string encoded in utf-8 format in android but it doesn't look like your string is encoded with anything particular. What do you think the output should be?

Display only date and no time

I had some problems with the other solutions on this page, so thought I'd drop this in.

@Html.TextBoxFor(m => m.EndDate, "{0:d}", new { @class = "form-control datepicker" })

So you only need to add "{0:d}" in the second parameter and you should be good to go.

How do you change the server header returned by nginx?

If you're okay with just changing the header to another string five letters or fewer, you can simply patch the binary.

sed -i 's/nginx\r/thing\r/' `which nginx`

Which, as a solution, has a few notable advantages. Namely, that you can allow your nginx versioning to be handled by the package manager (so, no compiling from source) even if nginx-extras isn't available for your distro, and you don't need to worry about any of the additional code of something like nginx-extras being vulnerable.

Of course, you'll also want to set the option server_tokens off, to hide the version number, or patch that format string as well.

I say "five letters or fewer" because of course you can always replace:

nginx\r\0

with

bob\r\0\r\0

leaving the last two bytes unchanged.

If you actually want more than five characters, you'll want to leave server_tokens on, and replace the (slightly longer) format string, although again there's an upper limit on that length imposed by the length of the format string - 1 (for the carriage return).

...If none of the above makes sense to you, or you've never patched a binary before, you may want to stay away from this approach, though.

What is the difference between a string and a byte string?

Unicode is an agreed-upon format for the binary representation of characters and various kinds of formatting (e.g. lower case/upper case, new line, carriage return), and other "things" (e.g. emojis). A computer is no less capable of storing a unicode representation (a series of bits), whether in memory or in a file, than it is of storing an ascii representation (a different series of bits), or any other representation (series of bits).

For communication to take place, the parties to the communication must agree on what representation will be used.

Because unicode seeks to represent all the possible characters (and other "things") used in inter-human and inter-computer communication, it requires a greater number of bits for the representation of many characters (or things) than other systems of representation that seek to represent a more limited set of characters/things. To "simplify," and perhaps to accommodate historical usage, unicode representation is almost exclusively converted to some other system of representation (e.g. ascii) for the purpose of storing characters in files.

It is not the case that unicode cannot be used for storing characters in files, or transmitting them through any communications channel, simply that it is not.

The term "string," is not precisely defined. "String," in its common usage, refers to a set of characters/things. In a computer, those characters may be stored in any one of many different bit-by-bit representations. A "byte string" is a set of characters stored using a representation that uses eight bits (eight bits being referred to as a byte). Since, these days, computers use the unicode system (characters represented by a variable number of bytes) to store characters in memory, and byte strings (characters represented by single bytes) to store characters to files, a conversion must be used before characters represented in memory will be moved into storage in files.

Difference between xcopy and robocopy

Robocopy replaces XCopy in the newer versions of windows

  1. Uses Mirroring, XCopy does not
  2. Has a /RH option to allow a set time for the copy to run
  3. Has a /MON:n option to check differences in files
  4. Copies over more file attributes than XCopy

Yes i agree with Mark Setchell, They are both crap. (brought to you by Microsoft)


UPDATE:

XCopy return codes:

0 - Files were copied without error.
1 - No files were found to copy.
2 - The user pressed CTRL+C to terminate xcopy. enough memory or disk space, or you entered an invalid drive name or invalid syntax on the command line.
5 - Disk write error occurred.

Robocopy returns codes:

0 - No errors occurred, and no copying was done. The source and destination directory trees are completely synchronized.
1 - One or more files were copied successfully (that is, new files have arrived).
2 - Some Extra files or directories were detected. No files were copied Examine the output log for details. 
3 - (2+1) Some files were copied. Additional files were present. No failure was encountered.
4 - Some Mismatched files or directories were detected. Examine the output log. Some housekeeping may be needed.
5 - (4+1) Some files were copied. Some files were mismatched. No failure was encountered.
6 - (4+2) Additional files and mismatched files exist. No files were copied and no failures were encountered. This means that the files already exist in the destination directory
7 - (4+1+2) Files were copied, a file mismatch was present, and additional files were present.
8 - Some files or directories could not be copied (copy errors occurred and the retry limit was exceeded). Check these errors further.
16 - Serious error. Robocopy did not copy any files. Either a usage error or an error due to insufficient access privileges on the source or destination directories.

There is more details on Robocopy return values here: http://ss64.com/nt/robocopy-exit.html

WorksheetFunction.CountA - not working post upgrade to Office 2010

It may be obvious but, by stating the Range and not including which workbook or worksheet then it may be trying to CountA() on a different sheet entirely. I find to fully address these things saves a lot of headaches.

Arduino IDE can't find ESP8266WiFi.h file

When programming the NODEMCU card with the Arduino IDE, you need to customize it and you must have selected the correct card.

Open Arduino IDE and go to files and click on the preference in the Arduino IDE.

Add the following link to the Additional Manager URLS section: "http://arduino.esp8266.com/stable/package_esp8266com_index.json" and press the OK button.

Then click Tools> Board Manager. Type "ESP8266" in the text box to search and install the ESP8266 software for Arduino IDE.

You will be successful when you try to program again by selecting the NodeMCU card after these operations. I hope I could help.

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

What worked for me is to first run:

 gradle wrapper

After successful build I was able to run

./gradlew assembleRelease

Note: To be able run gradle wrapper first run brew install gradle. If installation successful run gradle wrapper from project root.

Source and thanks: http://gradle.org/docs/current/userguide/gradle_wrapper.html and https://stackoverflow.com/users/745574/rage

React onClick function fires on render

For those not using arrow functions but something simpler ... I encountered this when adding parentheses after my signOut function ...

replace this <a onClick={props.signOut()}>Log Out</a>

with this <a onClick={props.signOut}>Log Out</a> ... !

How do I access store state in React Redux?

You need to use Store.getState() to get current state of your Store.

For more information about getState() watch this short video.

Codeigniter $this->db->get(), how do I return values for a specific row?

Incase you are dynamically getting your data e.g When you need data based on the user logged in by their id use consider the following code example for a No Active Record:

 $this->db->query('SELECT * FROM my_users_table WHERE id = ?', $this->session->userdata('id'));

 return $query->row_array();

This will return a specific row based on your the set session data of user.

CodeIgniter Active Record not equal

Try this code. This seems working in my case.

$this->db->where(array('id !='=> $id))

bind/unbind service example (android)

You can try using this code:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(intent);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

Add ripple effect to my button with button background color?

An alternative solution to using the <ripple> tag (which I personally prefer not to do, because the colors are not "default"), is the following:

Create a drawable for the button background, and include <item android:drawable="?attr/selectableItemBackground"> in the <layer-list>

Then (and I think this is the important part) programmatically set backgroundResource(R.drawable.custom_button) on your button instance.

Activity/Fragment

Button btn_temp = view.findViewById(R.id.btn_temp);
btn_temp.setBackgroundResource(R.drawable.custom_button);

Layout

<Button
    android:id="@+id/btn_temp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/custom_button"
    android:text="Test" />

custom_button.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white" />
            <corners android:radius="10dp" />
        </shape>
    </item>
    <item android:drawable="?attr/selectableItemBackground" />
</layer-list>

IE 8: background-size fix

As pointed by @RSK IE8 doesn't support background-size. To figure out a way to deal with this, I used some IE specific hacks as showed here:

//IE8.0 Hack!
@media \0screen {
    .brand {
        background-image: url("./images/logo1.png");
        margin-top: 8px;
    }

    .navbar .brand {
        margin-left: -2px;
        padding-bottom: 2px;
    }
}

//IE7.0 Hack!
*+html .brand {
    background-image: url("./images/logo1.png");
    margin-top: 8px;
}

*+html .navbar .brand {
    margin-left: -2px;
    padding-bottom: 2px;
}

Using this I was able to change my logo image to a ugly resided picture. But the final result is fine. I suggest u try something like this.

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

If you are trying to delete a column which is a FOREIGN KEY, you must find the correct name which is not the column name. Eg: If I am trying to delete the server field in the Alarms table which is a foreign key to the servers table.

  1. SHOW CREATE TABLE alarm; Look for the CONSTRAINT `server_id_refs_id_34554433` FORIEGN KEY (`server_id`) REFERENCES `server` (`id`) line.
  2. ALTER TABLE `alarm` DROP FOREIGN KEY `server_id_refs_id_34554433`;
  3. ALTER TABLE `alarm` DROP `server_id`

This will delete the foreign key server from the Alarms table.

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

For SQL Server 2012:

SELECT 
    o.OrderId, 
    IIF( o.NegotiatedPrice >= o.SuggestedPrice,
         o.NegotiatedPrice, 
         ISNULL(o.SuggestedPrice, o.NegiatedPrice) 
    )
FROM 
    Order o

How can getContentResolver() be called in Android?

This one worked for me getBaseContext();

cvc-elt.1: Cannot find the declaration of element 'MyElement'

I got this same error working in Eclipse with Maven with the additional information

schema_reference.4: Failed to read schema document 'https://maven.apache.org/xsd/maven-4.0.0.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.

This was after copying in a new controller and it's interface from a Thymeleaf example. Honestly, no matter how careful I am I still am at a loss to understand how one is expected to figure this out. On a (lucky) guess I right clicked the project, clicked Maven and Update Project which cleared up the issue.

Get index of a key in json

What you are after are numerical indexes in the way classic arrays work, however there is no such thing with json object/associative arrays.

"key1", "key2" themeselves are the indexes and there is no numerical index associated with them. If you want to have such functionality you have to assiciate them yourself.

How to use refs in React with Typescript

class SelfFocusingInput extends React.Component<{ value: string, onChange: (value: string) => any }, {}>{
    ctrls: {
        input?: HTMLInputElement;
    } = {};
    render() {
        return (
            <input
                ref={(input) => this.ctrls.input = input}
                value={this.props.value}
                onChange={(e) => { this.props.onChange(this.ctrls.input.value) } }
                />
        );
    }
    componentDidMount() {
        this.ctrls.input.focus();
    }
}

put them in an object

Best way to list files in Java, sorted by Date Modified?

You might also look at apache commons IO, it has a built in last modified comparator and many other nice utilities for working with files.

How can I make git show a list of the files that are being tracked?

The files managed by git are shown by git ls-files. Check out its manual page.

Running code in main thread from another thread

HandlerThread is better option to normal java Threads in Android .

  1. Create a HandlerThread and start it
  2. Create a Handler with Looper from HandlerThread :requestHandler
  3. post a Runnable task on requestHandler

Communication with UI Thread from HandlerThread

  1. Create a Handler with Looper for main thread : responseHandler and override handleMessage method
  2. Inside Runnable task of other Thread ( HandlerThread in this case), call sendMessage on responseHandler
  3. This sendMessage result invocation of handleMessage in responseHandler.
  4. Get attributes from the Message and process it, update UI

Example: Update TextView with data received from a web service. Since web service should be invoked on non-UI thread, created HandlerThread for Network Operation. Once you get the content from the web service, send message to your main thread (UI Thread) handler and that Handler will handle the message and update UI.

Sample code:

HandlerThread handlerThread = new HandlerThread("NetworkOperation");
handlerThread.start();
Handler requestHandler = new Handler(handlerThread.getLooper());

final Handler responseHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message msg) {
        txtView.setText((String) msg.obj);
    }
};

Runnable myRunnable = new Runnable() {
    @Override
    public void run() {
        try {
            Log.d("Runnable", "Before IO call");
            URL page = new URL("http://www.your_web_site.com/fetchData.jsp");
            StringBuffer text = new StringBuffer();
            HttpURLConnection conn = (HttpURLConnection) page.openConnection();
            conn.connect();
            InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
            BufferedReader buff = new BufferedReader(in);
            String line;
            while ((line = buff.readLine()) != null) {
                text.append(line + "\n");
            }
            Log.d("Runnable", "After IO call:"+ text.toString());
            Message msg = new Message();
            msg.obj = text.toString();
            responseHandler.sendMessage(msg);


        } catch (Exception err) {
            err.printStackTrace();
        }
    }
};
requestHandler.post(myRunnable);

Useful articles:

handlerthreads-and-why-you-should-be-using-them-in-your-android-apps

android-looper-handler-handlerthread-i

Transaction marked as rollback only: How do I find the cause

Found a good explanation with solutions: https://vcfvct.wordpress.com/2016/12/15/spring-nested-transactional-rollback-only/

1) remove the @Transacional from the nested method if it does not really require transaction control. So even it has exception, it just bubbles up and does not affect transactional stuff.

OR:

2) if nested method does need transaction control, make it as REQUIRE_NEW for the propagation policy that way even if throws exception and marked as rollback only, the caller will not be affected.

Upgrade to python 3.8 using conda

Open Anaconda Prompt (base):

  1. Update conda:
conda update -n base -c defaults conda
  1. Create new environment with Python 3.8:
conda create -n python38 python=3.8
  1. Activate your new Python 3.8 environment:
conda activate python38
  1. Start Python 3.8:
python

Finding local maxima/minima with Numpy in a 1D numpy array

None of these solutions worked for me since I wanted to find peaks in the center of repeating values as well. for example, in

ar = np.array([0,1,2,2,2,1,3,3,3,2,5,0])

the answer should be

array([ 3,  7, 10], dtype=int64)

I did this using a loop. I know it's not super clean, but it gets the job done.

def findLocalMaxima(ar):
# find local maxima of array, including centers of repeating elements    
maxInd = np.zeros_like(ar)
peakVar = -np.inf
i = -1
while i < len(ar)-1:
#for i in range(len(ar)):
    i += 1
    if peakVar < ar[i]:
        peakVar = ar[i]
        for j in range(i,len(ar)):
            if peakVar < ar[j]:
                break
            elif peakVar == ar[j]:
                continue
            elif peakVar > ar[j]:
                peakInd = i + np.floor(abs(i-j)/2)
                maxInd[peakInd.astype(int)] = 1
                i = j
                break
    peakVar = ar[i]
maxInd = np.where(maxInd)[0]
return maxInd 

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

You don't have a field named user_email in the members table ... as for why, I'm not sure as the code "looks" like it should try to join on different fields

Does the Auth::attempt method perform a join of the schema? Run grep -Rl 'class Auth' /path/to/framework and find where the attempt method is and what it does.

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

If you use .net core try this:

client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication =
        new X509ServiceCertificateAuthentication()
        {
            CertificateValidationMode = X509CertificateValidationMode.None,
            RevocationMode = System.Security.Cryptography.X509Certificates.X509RevocationMode.NoCheck
        };

Change PictureBox's image to image from my resources?

You must specify the full path of the resource file as the name of 'image within the resources of your application, see example below.

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    PictureBox1.Image = My.Resources.Chrysanthemum
End Sub

In the path assigned to the Image property after MyResources specify the name of the resource.

But before you do whatever you have to import in the resource section of your application from an image file exists or it can create your own.

Bye

How to convert nanoseconds to seconds using the TimeUnit enum?

TimeUnit is an enum, so you can't create a new one.

The following will convert 1000000000000ns to seconds.

TimeUnit.NANOSECONDS.toSeconds(1000000000000L);

How do I tell if an object is a Promise?

it('should return a promise', function() {
    var result = testedFunctionThatReturnsPromise();
    expect(result).toBeDefined();
    // 3 slightly different ways of verifying a promise
    expect(typeof result.then).toBe('function');
    expect(result instanceof Promise).toBe(true);
    expect(result).toBe(Promise.resolve(result));
});

Are SSL certificates bound to the servers ip address?

Most SSL certificates are bound to the hostname of the machine and not the ip address.

You might get a better answer if you ask this question on serverfault.com

Java 8 lambda Void argument

Add a static method inside your functional interface

package example;

interface Action<T, U> {
       U execute(T t);
       static  Action<Void,Void> invoke(Runnable runnable){
           return (v) -> {
               runnable.run();
                return null;
            };         
       }
    }

public class Lambda {


    public static void main(String[] args) {

        Action<Void, Void> a = Action.invoke(() -> System.out.println("Do nothing!"));
        Void t = null;
        a.execute(t);
    }

}

Output

Do nothing!

Convert PDF to image with high resolution

It also gives you good results:

exec("convert -geometry 1600x1600 -density 200x200 -quality 100 test.pdf test_image.jpg");

Difference between UTF-8 and UTF-16?

Simple way to differentiate UTF-8 and UTF-16 is to identify commonalities between them.

Other than sharing same unicode number for given character, each one is their own format.

UTF-8 try to represent, every unicode number given to character with one byte(If it is ASCII), else 2 two bytes, else 4 bytes and so on...

UTF-16 try to represent, every unicode number given to character with two byte to start with. If two bytes are not sufficient, then uses 4 bytes. IF that is also not sufficient, then uses 6 bytes.

Theoretically, UTF-16 is more space efficient, but in practical UTF-8 is more space efficient as most of the characters(98% of data) for processing are ASCII and UTF-8 try to represent them with single byte and UTF-16 try to represent them with 2 bytes.

Also, UTF-8 is superset of ASCII encoding. So every app that expects ASCII data would also accepted by UTF-8 processor. This is not true for UTF-16. UTF-16 could not understand ASCII, and this is big hurdle for UTF-16 adoption.

Another point to note is, all UNICODE as of now could be fit in 4 bytes of UTF-8 maximum(Considering all languages of world). This is same as UTF-16 and no real saving in space compared to UTF-8 ( https://stackoverflow.com/a/8505038/3343801 )

So, people use UTF-8 where ever possible.

How to parse a date?

We now have a more modern way to do this work.

java.time

The java.time framework is bundled with Java 8 and later. See Tutorial. These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. They are a vast improvement over the troublesome old classes, java.util.Date/.Calendar et al.

Note that the 3-4 letter codes like EDT are neither standardized nor unique. Avoid them whenever possible. Learn to use ISO 8601 standard formats instead. The java.time framework may take a stab at translating, but many of the commonly used codes have duplicate values.

By the way, note how java.time by default generates strings using the ISO 8601 formats but extended by appending the name of the time zone in brackets.

String input = "Thu Jun 18 20:56:02 EDT 2009";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "EEE MMM d HH:mm:ss zzz yyyy" , Locale.ENGLISH );
ZonedDateTime zdt = formatter.parse ( input , ZonedDateTime :: from );

Dump to console.

System.out.println ( "zdt : " + zdt );

When run.

zdt : 2009-06-18T20:56:02-04:00[America/New_York]

Adjust Time Zone

For fun let's adjust to the India time zone.

ZonedDateTime zdtKolkata = zdt.withZoneSameInstant ( ZoneId.of ( "Asia/Kolkata" ) );

zdtKolkata : 2009-06-19T06:26:02+05:30[Asia/Kolkata]

Convert to j.u.Date

If you really need a java.util.Date object for use with classes not yet updated to the java.time types, convert. Note that you are losing the assigned time zone, but have the same moment automatically adjusted to UTC.

java.util.Date date = java.util.Date.from( zdt.toInstant() );

How to import an Oracle database from dmp file and log file?

All this peace of code put into *.bat file and run all at once:

My code for creating user in oracle. crate_drop_user.sql file

drop user "USER" cascade;
DROP TABLESPACE "USER";

CREATE TABLESPACE USER DATAFILE 'D:\ORA_DATA\ORA10\USER.ORA' SIZE 10M REUSE 
    AUTOEXTEND 
    ON NEXT  5M  EXTENT MANAGEMENT LOCAL 
    SEGMENT SPACE MANAGEMENT  AUTO
/ 

CREATE  TEMPORARY TABLESPACE "USER_TEMP" TEMPFILE 
    'D:\ORA_DATA\ORA10\USER_TEMP.ORA' SIZE 10M REUSE AUTOEXTEND
    ON NEXT  5M  EXTENT MANAGEMENT LOCAL 
    UNIFORM SIZE 1M    
/

CREATE USER "USER"  PROFILE "DEFAULT" 
    IDENTIFIED BY "user_password" DEFAULT TABLESPACE "USER" 
    TEMPORARY TABLESPACE "USER_TEMP" 
/    

alter user USER quota unlimited on "USER";

GRANT CREATE PROCEDURE TO "USER";
GRANT CREATE PUBLIC SYNONYM TO "USER";
GRANT CREATE SEQUENCE TO "USER";
GRANT CREATE SNAPSHOT TO "USER";
GRANT CREATE SYNONYM TO "USER";
GRANT CREATE TABLE TO "USER";
GRANT CREATE TRIGGER TO "USER";
GRANT CREATE VIEW TO "USER";
GRANT "CONNECT" TO "USER";
GRANT SELECT ANY DICTIONARY to "USER";
GRANT CREATE TYPE TO "USER";

create file import.bat and put this lines in it:

SQLPLUS SYSTEM/systempassword@ORA_alias @"crate_drop_user.SQL"
IMP SYSTEM/systempassword@ORA_alias FILE=user.DMP FROMUSER=user TOUSER=user GRANTS=Y log =user.log

Be carefull if you will import from one user to another. For example if you have user named user1 and you will import to user2 you may lost all grants , so you have to recreate it.

Good luck, Ivan

Type.GetType("namespace.a.b.ClassName") returns null

Try this method.

public static Type GetType(string typeName)
{
    var type = Type.GetType(typeName);
    if (type != null) return type;
    foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
    {
        type = a.GetType(typeName);
        if (type != null)
            return type;
    }
    return null;
}

How to check java bit version on Linux?

Run java with -d64 or -d32 specified, it will give you an error message if it doesn't support 64-bit or 32-bit respectively. Your JVM may support both.

/usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found

I've got correct solution here.

The best way to correctly install gcc-4.9 and set it as your default gcc version use:

sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install gcc-4.9 g++-4.9
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.9 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.9

The --slave, with g++, will cause g++ to be switched along with gcc, to the same version. But, at this point gcc-4.9 will be your only version configured in update-alternatives, so add 4.8 to update-alternatives, so there actually is an alternative, by using:

sudo apt-get install gcc-4.8 g++-4.8
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.8

Then you can check which one that is set, and change back and forth using:

sudo update-alternatives --config gcc

NOTE: You could skip installing the PPA Repository and just use /usr/bin/gcc-4.9-base but I prefer using the fresh updated toolchains.

Using context in a fragment

Ideally, you should not need to use globals. The fragment has different notifications, one of them being onActivityCreated. You can get the instance of the activity in this lifecycle event of the fragment.

Then: you can dereference the fragment to get activity, context or applicationcontext as you desire:

this.getActivity() will give you the handle to the activity this.getContext() will give you a handle to the context this.getActivity().getApplicationContext() will give you the handle to the application context. You should preferably use the application context when passing it on to the db.

Cannot simply use PostgreSQL table name ("relation does not exist")

I had a similar problem on OSX but tried to play around with double and single quotes. For your case, you could try something like this

$query = 'SELECT * FROM "sf_bands"'; // NOTE: double quotes on "sf_Bands"

How to detect READ_COMMITTED_SNAPSHOT is enabled?

SELECT is_read_committed_snapshot_on FROM sys.databases 
WHERE name= 'YourDatabase'

Return value:

  • 1: READ_COMMITTED_SNAPSHOT option is ON. Read operations under the READ COMMITTED isolation level are based on snapshot scans and do not acquire locks.
  • 0 (default): READ_COMMITTED_SNAPSHOT option is OFF. Read operations under the READ COMMITTED isolation level use Shared (S) locks.

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

A few years ago it was said that update() and digest() were legacy methods and the new streaming API approach was introduced. Now the docs say that either method can be used. For example:

var crypto    = require('crypto');
var text      = 'I love cupcakes';
var secret    = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1';   //consider using sha256
var hash, hmac;

// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);    
hmac.write(text); // write in to the stream
hmac.end();       // can't read from the stream until you call end()
hash = hmac.read().toString('hex');    // read out hmac digest
console.log("Method 1: ", hash);

// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);

Tested on node v6.2.2 and v7.7.2

See https://nodejs.org/api/crypto.html#crypto_class_hmac. Gives more examples for using the streaming approach.

How do I make a fully statically linked .exe with Visual Studio Express 2005?

For the C-runtime go to the project settings, choose C/C++ then 'Code Generation'. Change the 'runtime library' setting to 'multithreaded' instead of 'multithreaded dll'.

If you are using any other libraries you may need to tell the linker to ignore the dynamically linked CRT explicitly.

How to create a DB for MongoDB container on start up?

In case someone is looking for how to configure MongoDB with authentication using docker-compose, here is a sample configuration using environment variables:

version: "3.3"

services:

  db:
      image: mongo
      environment:
        - MONGO_INITDB_ROOT_USERNAME=admin
        - MONGO_INITDB_ROOT_PASSWORD=<YOUR_PASSWORD>
      ports:
        - "27017:27017"

When running docker-compose up your mongo instance is run automatically with auth enabled. You will have a admin database with the given password.

IndentationError: unexpected indent error

The indentation is wrong, as the error tells you. As you can see, you have indented the code beginning with the indicated line too little to be in the for loop, but too much to be at the same level as the for loop. Python sees the lack of indentation as ending the for loop, then complains you have indented the rest of the code too much. (The def line I'm betting is just an artifact of how Stack Overflow wants you to format your code.)

Edit: Given your correction, I'm betting you have a mixture of tabs and spaces in the source file, such that it looks to the human eye like the code lines up, but Python considers it not to. As others have suggested, using only spaces is the recommended practice (see PEP 8). If you start Python with python -t, you will get warnings if there are mixed tabs and spaces in your code, which should help you pinpoint the issue.

Git list of staged files

You can Try using :- git ls-files -s

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

It can happen because of native method calling in your application. For example, in Qtjambi if you use QApplication.quit() instead of QApplication.closeAllWindows() for closing a Java application it generates an error log.

In this case, you can get a stack trace right to your method that called the native code and caused the crash. Just look in the log file it tells you about:

# An error report file with more information is saved as hs_err_pid24139.log.

The stack trace looks quite unusual, since it has native code mixed with VM code and your code, but each line is prefixed so you can tell which lines are your own code. There's a key at the top of the stack trace to explain the prefixes:

Native frames: (J=compiled Java code, A=aot compiled Java code, j=interpreted, Vv=VM code, C=native code)