Programs & Examples On #Flash memory

Flash memory is an electronic non-volatile computer storage device that can be reprogrammed and erased electrically.

How to add anchor tags dynamically to a div in Javascript?

One more variation wrapped up nicely where setAttribute isn't needed.

There are 3 lines that wouldn't be needed if Wetfox could dry off.

var saveAs = function (filename, content) {
    if(filename === undefined) filename = "Unknown.txt";
    if(content === undefined) content = "Empty?!";
    let link = document.createElement('a');
    link.style.display = "none"; // because Firefox sux
    document.body.appendChild(link); // because Firefox sux
    link.href = "data:application/octet-stream," + encodeURIComponent(content);
    link.download = filename;
    link.click();
    document.body.removeChild(link); // because Firefox sux
};

Thanks for the help.

PHP absolute path to root

In PHP there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the root:

 $_SERVER['DOCUMENT_ROOT']

The only problem is that the entries in this variable are provided by the web server and there is no guarantee that all web servers offer them.

Android Debug Bridge (adb) device - no permissions

Same problem with Pipo S1S after upgrading to 4.2.2 stock rom Jun 4.

$ adb devices
List of devices attached  
????????????    no permissions

All of the above suggestions, while valid to get your usb device recognised, do not solve the problem for me. (Android Debug Bridge version 1.0.31 running on Mint 15.)

Updating android sdk tools etc resets ~/.android/adb_usb.ini.

To recognise Pipo VendorID 0x2207 do these steps

Add to line /etc/udev/rules.d/51-android.rules

SUBSYSTEM=="usb", ATTR{idVendor}=="0x2207", MODE="0666", GROUP="plugdev"

Add line to ~/.android/adb_usb.ini:

0x2207

Then remove the adbkey files

rm -f ~/.android/adbkey ~/.android/adbkey.pub

and reconnect your device to rebuild the key files with a correct adb connection. Some devices will ask to re-authorize.

sudo adb kill-server
sudo adb start-server   
adb devices

Android Studio - Failed to apply plugin [id 'com.android.application']

First of all, before trying the most complicated things you should make the step easier, in my case this bug just happened on my way until the project contained 'spaces' for example:

Replace:

C://Users/Silva Neto/OneDrive/Work space/project

With:

C://Users/SilvaNeto/OneDrive/Workspace/project

Notice that we replaced spaces with camelCase but you can choose any naming scheme you like, and hopefully this could solve your issue.

I hope this will help.

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

If you use Hibernate 5.2.10.Final, you should change

<provider>org.hibernate.ejb.HibernatePersistence</provider>

to

<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

in your persistence.xml

According to Hibernate 5.2.2: No Persistence provider for EntityManager

Uncaught SyntaxError: Unexpected token < On Chrome

The only place it worked for me is when I place the scripts in public folder where my index.html resides and then placing these <script type="text/javascript" src="test/test.js"></script> inside <body> tag.

ToggleButton in C# WinForms

When my button's FlatStyle is set to system, it looks flat. And when it's set to popup, it only pops up when mouses over. Either is what I want. I want it to look sunken when checked and raised when unchecked and no change while mousing over (the button is really a checkbox but the checkbox's appearance property is set to button).

I end up setting the FlatStyle to flat and wrote a new Paint event handler.

 private void checkbox_paint(object sender, PaintEventArgs e)
        {
            CheckBox myCheckbox = (CheckBox)sender;
            Rectangle borderRectangle = myCheckbox.ClientRectangle;
            if (myCheckbox.Checked)
            {
                ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
                    Border3DStyle.Sunken);
            }
            else
            {
                ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
                    Border3DStyle.Raised);
            }
        }

I give a similar answer to this question: C# winforms button with solid border, like 3d Sorry for double posting.

Looking to understand the iOS UIViewController lifecycle

As per Apple's doc — Start Developing iOS Apps (Swift) — Work with View Controllers — Understand the View Controller Lifecycle

viewDidLoad()—Called when the view controller’s content view (the top of its view hierarchy) is created and loaded from a storyboard. … Use this method to perform any additional setup required by your view controller.

viewWillAppear()—Called just before the view controller’s content view is added to the app’s view hierarchy. Use this method to trigger any operations that need to occur before the content view is presented onscreen

viewDidAppear()—Called just after the view controller’s content view has been added to the app’s view hierarchy. Use this method to trigger any operations that need to occur as soon as the view is presented onscreen, such as fetching data or showing an animation.

viewWillDisappear()—Called just before the view controller’s content view is removed from the app’s view hierarchy. Use this method to perform cleanup tasks like committing changes or resigning the first responder status.

viewDidDisappear()—Called just after the view controller’s content view has been removed from the app’s view hierarchy. Use this method to perform additional teardown activities.

Delete files older than 10 days using shell script in Unix

find is the common tool for this kind of task :

find ./my_dir -mtime +10 -type f -delete

EXPLANATIONS

  • ./my_dir your directory (replace with your own)
  • -mtime +10 older than 10 days
  • -type f only files
  • -delete no surprise. Remove it to test your find filter before executing the whole command

And take care that ./my_dir exists to avoid bad surprises !

How to find a hash key containing a matching value

From the docs:

  • (Object?) detect(ifnone = nil) {|obj| ... }
  • (Object?) find(ifnone = nil) {|obj| ... }
  • (Object) detect(ifnone = nil)
  • (Object) find(ifnone = nil)

Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil otherwise.

If no block is given, an enumerator is returned instead.

(1..10).detect  {|i| i % 5 == 0 and i % 7 == 0 }   #=> nil
(1..100).detect {|i| i % 5 == 0 and i % 7 == 0 }   #=> 35

This worked for me:

clients.detect{|client| client.last['client_id'] == '2180' } #=> ["orange", {"client_id"=>"2180"}] 

clients.detect{|client| client.last['client_id'] == '999999' } #=> nil 

See: http://rubydoc.info/stdlib/core/1.9.2/Enumerable#find-instance_method

Shrinking navigation bar when scrolling down (bootstrap3)

For those not willing to use jQuery here is a Vanilla Javascript way of doing the same using classList:

function runOnScroll() {
    var element = document.getElementsByTagName('nav')  ;
    if(document.body.scrollTop >= 50) {
        element[0].classList.add('shrink')
    } else {
        element[0].classList.remove('shrink')
    }
    console.log(topMenu[0].classList)

};

There might be a nicer way of doing it using toggle, but the above works fine in Chrome

Google maps API V3 method fitBounds()

 var map = new google.maps.Map(document.getElementById("map"),{
                mapTypeId: google.maps.MapTypeId.ROADMAP

            });
var bounds = new google.maps.LatLngBounds();

for (i = 0; i < locations.length; i++){
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });
bounds.extend(marker.position);
}
map.fitBounds(bounds);

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

How to rebase local branch onto remote master

git fetch origin master:master pulls the latest version of master without needing to check it out.

So all you need is:

git fetch origin master:master && git rebase master

How to rename JSON key

If your object looks like this:

obj = {
    "_id":"5078c3a803ff4197dc81fbfb",
    "email":"[email protected]",
    "image":"some_image_url",
    "name":"Name 1"
   }

Probably the simplest method in JavaScript is:

obj.id = obj._id
del object['_id']

As a result, you will get:

obj = {
    "id":"5078c3a803ff4197dc81fbfb",
    "email":"[email protected]",
    "image":"some_image_url",
    "name":"Name 1"
   }

How do I format a number to a dollar amount in PHP

i tried money_format() but it didn't work for me at all. then i tried the following one. it worked perfect for me. hopefully it will work in right way for you too.. :)

you should use this one

number_format($money, 2,'.', ',')

it will show money number in terms of money format up to 2 decimal.

How to trigger jQuery change event in code

Use That :

$(selector).trigger("change");

OR

$('#id').trigger("click");

OR

$('.class').trigger(event);

Trigger can be any event that javascript support.. Hope it's easy to understandable to all of You.

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

If you forget your password or you want to modify your password.You can follow these steps :

1 :stop your mysql

[root@maomao ~]# service mysqld stop
Stopping MySQL: [ OK ]

2 :use “--skip-grant-tables” to restart mysql

[root@mcy400 ~]# mysqld_safe --skip-grant-tables
[root@cy400 ~]# Starting mysqld daemon with databases from /var/lib/mysql

3 : open a new window and input mysql -u root

[root@cy400 ~]# mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.

4 : change the user database

mysql> use mysql
Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed

5 : modify your password your new password should be input in "()"

mysql> update user set password=password('root123') where user='root';
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3 Changed: 3 Warnings: 0

6 : flush

mysql> flush privileges;

7: quit

mysql> quit
Bye

8: restart mysql

[root@cy400 ~]# service mysqld restart;
Stopping MySQL: [ OK ]
Starting MySQL: [ OK ]

Bingo! You can connect your database with your username and new password:

[root@cy400 ~]# mysql -u root -p <br>
Enter password: admin123 <br>
Welcome to the MySQL monitor.  Commands end with ; or \g. <br>
Your MySQL connection id is 2 <br>
Server version: 5.0.77 Source distribution <br>
Type 'help;' or '\h' for help. Type '\c' to clear the buffer. <br>
mysql> quit <br>
Bye

How to create friendly URL in php?

I recently used the following in an application that is working well for my needs.

.htaccess

<IfModule mod_rewrite.c>
# enable rewrite engine
RewriteEngine On

# if requested url does not exist pass it as path info to index.php
RewriteRule ^$ index.php?/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?/$1 [QSA,L]
</IfModule>

index.php

foreach (explode ("/", $_SERVER['REQUEST_URI']) as $part)
{
    // Figure out what you want to do with the URL parts.
}

How do I replace whitespaces with underscore?

Surprisingly this library not mentioned yet

python package named python-slugify, which does a pretty good job of slugifying:

pip install python-slugify

Works like this:

from slugify import slugify

txt = "This is a test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")

txt = "This -- is a ## test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")

txt = 'C\'est déjà l\'été.'
r = slugify(txt)
self.assertEquals(r, "cest-deja-lete")

txt = 'Nín hao. Wo shì zhong guó rén'
r = slugify(txt)
self.assertEquals(r, "nin-hao-wo-shi-zhong-guo-ren")

txt = '?????????'
r = slugify(txt)
self.assertEquals(r, "kompiuter")

txt = 'jaja---lol-méméméoo--a'
r = slugify(txt)
self.assertEquals(r, "jaja-lol-mememeoo-a") 

Joining two table entities in Spring Data JPA

This has been an old question but solution is very simple to that. If you are ever unsure about how to write criterias, joins etc in hibernate then best way is using native queries. This doesn't slow the performance and very useful. Eq. below

    @Query(nativeQuery = true, value = "your sql query")
returnTypeOfMethod methodName(arg1, arg2);

Object Library Not Registered When Adding Windows Common Controls 6.0

You can run the tool from Microsoft in this KB http://support.microsoft.com/default.aspx?scid=kb;en-us;Q195353 to fix the licensing issues for earlier ActiveX controls. This worked for me.

SQL Case Sensitive String Compare

Just as another alternative you could use HASHBYTES, something like this:

SELECT * 
FROM a_table 
WHERE HASHBYTES('sha1', attribute) = HASHBYTES('sha1', 'k')

Symbol for any number of any characters in regex?

I would use .*. . matches any character, * signifies 0 or more occurrences. You might need a DOTALL switch to the regex to capture new lines with ..

Can iterators be reset in Python?

While there is no iterator reset, the "itertools" module from python 2.6 (and later) has some utilities that can help there. One of then is the "tee" which can make multiple copies of an iterator, and cache the results of the one running ahead, so that these results are used on the copies. I will seve your purposes:

>>> def printiter(n):
...   for i in xrange(n):
...     print "iterating value %d" % i
...     yield i

>>> from itertools import tee
>>> a, b = tee(printiter(5), 2)
>>> list(a)
iterating value 0
iterating value 1
iterating value 2
iterating value 3
iterating value 4
[0, 1, 2, 3, 4]
>>> list(b)
[0, 1, 2, 3, 4]

Error in if/while (condition) {: missing Value where TRUE/FALSE needed

this works with "NA" not for NA

comments = c("no","yes","NA")
  for (l in 1:length(comments)) {
    #if (!is.na(comments[l])) print(comments[l])
    if (comments[l] != "NA") print(comments[l])
  }

What's the difference between the Window.Loaded and Window.ContentRendered events

This is not about the difference between Window.ContentRendered and Window.Loaded but about what how the Window.Loaded event can be used:

I use it to avoid splash screens in all applications which need a long time to come up.

    // initializing my main window
    public MyAppMainWindow()
    {
        InitializeComponent();

        // Set the event
        this.ContentRendered += MyAppMainWindow_ContentRendered;
    }

    private void MyAppMainWindow_ContentRendered(object sender, EventArgs e)
    {
        // ... comes up quick when the controls are loaded and rendered

        // unset the event
        this.ContentRendered -= MyAppMainWindow_ContentRendered;

        // ... make the time comsuming init stuff here
    }

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

How to expand a list to function arguments in Python

That can be done with:

foo(*values)

Running Google Maps v2 on the Android emulator

Google has updated the Virtual Device targeting API 23. It now comes with Google Play Services 9.0.80. So if you are using Google Maps API V 2.0 (I'm using play-services-maps:9.0.0 and play-services-location.9.0.0) no workaround necessary. It just works!

What is the difference between Nexus and Maven?

Whatever I understood from my learning and what I think it is is here. I am Quoting some part from a book i learnt this things. Nexus Repository Manager and Nexus Repository Manager OSS started as a repository manager supporting the Maven repository format. While it supports many other repository formats now, the Maven repository format is still the most common and well supported format for build and provisioning tools running on the JVM and beyond. This chapter shows example configurations for using the repository manager with Apache Maven and a number of other tools. The setups take advantage of merging many repositories and exposing them via a repository group. Setting this up is documented in the chapter in addition to the configuration used by specific tools.

Details

How to make a website secured with https

What should I do to prepare my website for https. (Do I need to alter the code / Config)

You should keep best practices for secure coding in mind (here is a good intro: http://www.owasp.org/index.php/Secure_Coding_Principles ), otherwise all you need is a correctly set up SSL certificate.

Is SSL and https one and the same..

Pretty much, yes.

Do I need to apply with someone to get some license or something.

You can buy an SSL certificate from a certificate authority or use a self-signed certificate. The ones you can purchase vary wildly in price - from $10 to hundreds of dollars a year. You would need one of those if you set up an online shop, for example. Self-signed certificates are a viable option for an internal application. You can also use one of those for development. Here's a good tutorial on how to set up a self-signed certificate for IIS: Enabling SSL on IIS 7.0 Using Self-Signed Certificates

Do I need to make all my pages secured or only the login page..

Use HTTPS for everything, not just the initial user login. It's not going to be too much of an overhead and it will mean the data that the users send/receive from your remotely hosted application cannot be read by outside parties if it is intercepted. Even Gmail now turns on HTTPS by default.

JSLint says "missing radix parameter"

Prior to ECMAScript 5, parseInt() also autodetected octal literals, which caused problems because many developers assumed a leading 0 would be ignored.

So Instead of :

var num = parseInt("071");      // 57

Do this:

var num = parseInt("071", 10);  // 71

var num = parseInt("071", 8);

var num = parseFloat(someValue); 

Reference

Adding a dictionary to another

Create an Extension Method most likely you will want to use this more than once and this prevents duplicate code.

Implementation:

 public static void AddRange<T, S>(this Dictionary<T, S> source, Dictionary<T, S> collection)
 {
        if (collection == null)
        {
            throw new ArgumentNullException("Collection is null");
        }

        foreach (var item in collection)
        {
            if(!source.ContainsKey(item.Key)){ 
               source.Add(item.Key, item.Value);
            }
            else
            {
               // handle duplicate key issue here
            }  
        } 
 }

Usage:

Dictionary<string,string> animals = new Dictionary<string,string>();
Dictionary<string,string> newanimals = new Dictionary<string,string>();

animals.AddRange(newanimals);

How to always show scrollbar

Setting the android:scrollbarFadeDuration="0" will do the trick.

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

Just copy-paste the .jar under the "libs" folder (or whole "libs" folder), right click on it and select 'Add as library' option from the list. It will do the rest...

enter image description here

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

Angular adds this to keep track of your changes, so it knows when it needs to update the DOM.

If you use angular.toJson(obj) instead of JSON.stringify(obj) then Angular will strip out these internal-use values for you.

Also, if you change your repeat expression to use the track by {uniqueProperty} suffix, Angular won't have to add $$hashKey at all. For example

<ul>
    <li ng-repeat="link in navLinks track by link.href">
        <a ng-href="link.href">{{link.title}}</a>
    </li>
</ul>

Just always remember you need the "link." part of the expression - I always tend to forget that. Just track by href will surely not work.

How to import a module given the full path?

A simple solution using importlib instead of the imp package (tested for Python 2.7, although it should work for Python 3 too):

import importlib

dirname, basename = os.path.split(pyfilepath) # pyfilepath: '/my/path/mymodule.py'
sys.path.append(dirname) # only directories should be added to PYTHONPATH
module_name = os.path.splitext(basename)[0] # '/my/path/mymodule.py' --> 'mymodule'
module = importlib.import_module(module_name) # name space of defined module (otherwise we would literally look for "module_name")

Now you can directly use the namespace of the imported module, like this:

a = module.myvar
b = module.myfunc(a)

The advantage of this solution is that we don't even need to know the actual name of the module we would like to import, in order to use it in our code. This is useful, e.g. in case the path of the module is a configurable argument.

Extracting time from POSIXct

The time_t value for midnight GMT is always divisible by 86400 (24 * 3600). The value for seconds-since-midnight GMT is thus time %% 86400.

The hour in GMT is (time %% 86400) / 3600 and this can be used as the x-axis of the plot:

plot((as.numeric(times) %% 86400)/3600, val)

enter image description here

To adjust for a time zone, adjust the time before taking the modulus, by adding the number of seconds that your time zone is ahead of GMT. For example, US central daylight saving time (CDT) is 5 hours behind GMT. To plot against the time in CDT, the following expression is used:

plot(((as.numeric(times) - 5*3600) %% 86400)/3600, val)

PHP regular expressions: No ending delimiter '^' found in

Your regex pattern needs to be in delimiters:

$numpattern="/^([0-9]+)$/";

TimeSpan to DateTime conversion

If you only need to show time value in a datagrid or label similar, best way is convert directly time in datetime datatype.

SELECT CONVERT(datetime,myTimeField) as myTimeField FROM Table1

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Well presumably it's not using the same version of Java when running it externally. Look through the startup scripts carefully to find where it picks up the version of Java to run. You should also check the startup logs to see whether they indicate which version is running.

Alternatively, unless you need the Java 7 features, you could always change your compiler preferences in Eclipse to target 1.6 instead.

How to remove "disabled" attribute using jQuery?

for removing the disabled properties

 $('#inputDisabled').removeAttr('Disabled');

for adding the disabled properties

 $('#inputDisabled').attr('disabled', 'disabled' );

How to search in an array with preg_match?

$haystack = array (
   'say hello',
   'hello stackoverflow',
   'hello world',
   'foo bar bas'
);

$matches  = preg_grep('/hello/i', $haystack);

print_r($matches);

Output

Array
(
    [1] => say hello
    [2] => hello stackoverflow
    [3] => hello world
)

Setting paper size in FPDF

They say it right there in the documentation for the FPDF constructor:

FPDF([string orientation [, string unit [, mixed size]]])

This is the class constructor. It allows to set up the page size, the orientation and the unit of measure used in all methods (except for font sizes). Parameters ...

size

The size used for pages. It can be either one of the following values (case insensitive):

A3 A4 A5 Letter Legal

or an array containing the width and the height (expressed in the unit given by unit).

They even give an example with custom size:

Example with a custom 100x150 mm page size:

$pdf = new FPDF('P','mm',array(100,150));

How to install OpenSSL in windows 10?

In case you have Git installed,

you can open the Git Bash (shift pressed + right click in the folder -> Git Bash Here) and use openssl command right in the Bash

Spring can you autowire inside an abstract class?

Normally, Spring should do the autowiring, as long as your abstract class is in the base-package provided for component scan.

See this and this for further reference.

@Service and @Component are both stereotypes that creates beans of the annotated type inside the Spring container. As Spring Docs state,

This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

Attach a body onload event with JS

document.body.onload is a cross-browser, but a legacy mechanism that only allows a single callback (you cannot assign multiple functions to it).

The closest "standard" alternative, addEventListener is not supported by Internet Explorer (it uses attachEvent), so you will likely want to use a library (jQuery, MooTools, prototype.js, etc.) to abstract the cross-browser ugliness for you.

How to change already compiled .class file without decompile?

Use a bytecode editor, like:

http://set.ee/jbe/

Be careful because you need a very good knowledge of the Java bytecode.

You can also change the class at runtime with bytecode weaving (like AspectJ).

How to Load RSA Private Key From File

Two things. First, you must base64 decode the mykey.pem file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec, which is based on the SubjectPublicKeyInfo ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

// ...   

String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);

Lining up labels with radio buttons in bootstrap

Best is to just Apply margin-top: 2px on the input element.

Bootstrap adds a margin-top: 4px to input element causing radio button to move down than the content.

syntax error near unexpected token `('

Since you've got both the shell that you're typing into and the shell that sudo -s runs, you need to quote or escape twice. (EDITED fixed quoting)

sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'

or

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)

Out of curiosity, why do you need -s? Can't you just do this:

sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

Display the current time and date in an Android application

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
Date date = Calendar.getInstance().getTime();
String sDate = format.format(date);//31-12-9999
int mYear = c.get(Calendar.YEAR);//9999
int mMonth = c.get(Calendar.MONTH);
mMonth = mMonth + 1;//12
int hrs = c.get(Calendar.HOUR_OF_DAY);//24
int min = c.get(Calendar.MINUTE);//59
String AMPM;
if (c.get(Calendar.AM_PM) == 0) {
    AMPM = "AM";
} else {
    AMPM = "PM";
}

"Operation must use an updateable query" error in MS Access

I used a temp table and finally got this to work. Here is the logic that is used once you create the temp table:

UPDATE your_table, temp
SET your_table.value = temp.value
WHERE your_table.id = temp.id

Java 8 Distinct by property

Here is the example
public class PayRoll {

    private int payRollId;
    private int id;
    private String name;
    private String dept;
    private int salary;


    public PayRoll(int payRollId, int id, String name, String dept, int salary) {
        super();
        this.payRollId = payRollId;
        this.id = id;
        this.name = name;
        this.dept = dept;
        this.salary = salary;
    }
} 

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class Prac {
    public static void main(String[] args) {

        int salary=70000;
        PayRoll payRoll=new PayRoll(1311, 1, "A", "HR", salary);
        PayRoll payRoll2=new PayRoll(1411, 2    , "B", "Technical", salary);
        PayRoll payRoll3=new PayRoll(1511, 1, "C", "HR", salary);
        PayRoll payRoll4=new PayRoll(1611, 1, "D", "Technical", salary);
        PayRoll payRoll5=new PayRoll(711, 3,"E", "Technical", salary);
        PayRoll payRoll6=new PayRoll(1811, 3, "F", "Technical", salary);
        List<PayRoll>list=new ArrayList<PayRoll>();
        list.add(payRoll);
        list.add(payRoll2);
        list.add(payRoll3);
        list.add(payRoll4);
        list.add(payRoll5);
        list.add(payRoll6);


        Map<Object, Optional<PayRoll>> k = list.stream().collect(Collectors.groupingBy(p->p.getId()+"|"+p.getDept(),Collectors.maxBy(Comparator.comparingInt(PayRoll::getPayRollId))));


        k.entrySet().forEach(p->
        {
            if(p.getValue().isPresent())
            {
                System.out.println(p.getValue().get());
            }
        });



    }
}

Output:

PayRoll [payRollId=1611, id=1, name=D, dept=Technical, salary=70000]
PayRoll [payRollId=1811, id=3, name=F, dept=Technical, salary=70000]
PayRoll [payRollId=1411, id=2, name=B, dept=Technical, salary=70000]
PayRoll [payRollId=1511, id=1, name=C, dept=HR, salary=70000]

How to know the git username and email saved during configuration?

The command git config --list will list the settings. There you should also find user.name and user.email.

Sorting arraylist in alphabetical order (case insensitive)

Starting from Java 8 you can use Stream:

List<String> sorted = Arrays.asList(
                          names.stream().sorted(
                              (s1, s2) -> s1.compareToIgnoreCase(s2)
                          ).toArray(String[]::new)
                      );

It gets a stream from that ArrayList, then it sorts it (ignoring the case). After that, the stream is converted to an array which is converted to an ArrayList.

If you print the result using:

System.out.println(sorted);

you get the following output:

[ananya, Athira, bala, jeena, Karthika, Neethu, Nithin, seetha, sudhin, Swetha, Tony, Vinod]

Replace missing values with column mean

If DF is your data frame of numeric columns:

library(zoo)
na.aggregate(DF)

ADDED:

Using only the base of R define a function which does it for one column and then lapply to every column:

NA2mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
replace(DF, TRUE, lapply(DF, NA2mean))

The last line could be replaced with the following if it's OK to overwrite the input:

DF[] <- lapply(DF, NA2mean)

How to use Bootstrap modal using the anchor tag for Register?

Here is a link to W3Schools that answers your question https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp

Note: For anchor tag elements, omit data-target, and use href="#modalID" instead:

I hope that helps

Random character generator with a range of (A..Z, 0..9) and punctuation

random char package com.company;

         import java.util.concurrent.ThreadLocalRandom;

         public class Main {

            public static void main(String[] args) {
            // write your code here
                char hurufBesar =randomSeriesForThreeCharacter(65,90);
                char angka = randomSeriesForThreeCharacter(48,57);
                char simbol = randomSeriesForThreeCharacter(33,47);
                char hurufKecil= randomSeriesForThreeCharacter(97,122);
                char angkaLagi = randomSeriesForThreeCharacter(48,57);

                System.out.println(hurufBesar+" "+angka+" "+simbol+" "+hurufKecil+" "+angkaLagi);
            }

            public static char randomSeriesForThreeCharacter(int min,int max) {
                int randomNumber = ThreadLocalRandom.current().nextInt(min, max + 1);
                char random_3_Char = (char) (randomNumber);
                return random_3_Char;
             }
         }

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

Things change. The escape/unescape methods have been deprecated.

You can URI encode the string before you Base64-encode it. Note that this does't produce Base64-encoded UTF8, but rather Base64-encoded URL-encoded data. Both sides must agree on the same encoding.

See working example here: http://codepen.io/anon/pen/PZgbPW

// encode string
var base64 = window.btoa(encodeURIComponent('€ ?? æøåÆØÅ'));
// decode string
var str = decodeURIComponent(window.atob(tmp));
// str is now === '€ ?? æøåÆØÅ'

For OP's problem a third party library such as js-base64 should solve the problem.

Createuser: could not connect to database postgres: FATAL: role "tom" does not exist

Your error is posted in the official documentation. You can read this article.

I have copied the reason for you (and hyperlinked the URLs) from that article:

This will happen if the administrator has not created a PostgreSQL user account for you. (PostgreSQL user accounts are distinct from operating system user accounts.) If you are the administrator, see Chapter 20 for help creating accounts. You will need to become the operating system user under which PostgreSQL was installed (usually postgres) to create the first user account. It could also be that you were assigned a PostgreSQL user name that is different from your operating system user name; in that case you need to use the -U switch or set the PGUSER environment variable to specify your PostgreSQL user name

For your purposes, you can do:

1) Create a PostgreSQL user account:

sudo -u postgres createuser tom -d -P

(the -P option to set a password; the -d option for allowing the creation of database for your username 'tom'. Note that 'tom' is your operating system username. That way, you can execute PostgreSQL commands without sudoing.)

2) Now you should be able to execute createdb and other PostgreSQL commands.

Android Failed to install HelloWorld.apk on device (null) Error

I was getting the same error.

I Just left the AVD running even after it says "Failed to install *.apk on device-emulator-5554". It automatically loaded the project afterwards.

I think the error comes due the slow start up of the AVD.

anaconda/conda - install a specific package version

To install a specific package:

conda install <pkg>=<version>

eg:

conda install matplotlib=1.4.3

Simple int to char[] conversion

#include<stdio.h> 
#include<stdlib.h>
#include<string.h>
void main()
{
int a = 543210 ;
char arr[10] ="" ;

itoa(a,arr,10) ;   // itoa() is a function of stdlib.h file that convert integer 
                   // int to array itoa( integer, targated array, base u want to             
                   //convert like decimal have 10 

for( int i= 0 ; i < strlen(arr); i++)   //  strlen()   function in string file thar return string length
  printf("%c",arr[i]);

}

Most concise way to test string equality (not object equality) for Ruby strings or symbols?

Your code sample didn't expand on part of your topic, namely symbols, and so that part of the question went unanswered.

If you have two strings, foo and bar, and both can be either a string or a symbol, you can test equality with

foo.to_s == bar.to_s

It's a little more efficient to skip the string conversions on operands with known type. So if foo is always a string

foo == bar.to_s

But the efficiency gain is almost certainly not worth demanding any extra work on behalf of the caller.

Prior to Ruby 2.2, avoid interning uncontrolled input strings for the purpose of comparison (with strings or symbols), because symbols are not garbage collected, and so you can open yourself to denial of service through resource exhaustion. Limit your use of symbols to values you control, i.e. literals in your code, and trusted configuration properties.

Ruby 2.2 introduced garbage collection of symbols.

How to get primary key of table?

For a PHP approach, you can use mysql_field_flags

$q = mysql_query('select * from table limit 1');

for($i = 0; $i < mysql_num_fields(); $i++)
    if(strpos(mysql_field_tags($q, $i), 'primary_key') !== false)
        echo mysql_field_name($q, $i)." is a primary key\n";

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

Catch browser's "zoom" event in JavaScript

I'am replying to a 3 year old link but I guess here's a more acceptable answer,

Create .css file as,

@media screen and (max-width: 1000px) 
{
       // things you want to trigger when the screen is zoomed
}

EG:-

@media screen and (max-width: 1000px) 
{
    .classname
    {
          font-size:10px;
    }
}

The above code makes the size of the font '10px' when the screen is zoomed to approximately 125%. You can check for different zoom level by changing the value of '1000px'.

How to position background image in bottom right corner? (CSS)

This should do it:

<style>
body {
    background:url(bg.jpg) fixed no-repeat bottom right;
}
</style>

http://www.w3schools.com/cssref/pr_background-position.asp

What is the common header format of Python files?

The answers above are really complete, but if you want a quick and dirty header to copy'n paste, use this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Module documentation goes here
   and here
   and ...
"""

Why this is a good one:

  • The first line is for *nix users. It will choose the Python interpreter in the user path, so will automatically choose the user preferred interpreter.
  • The second one is the file encoding. Nowadays every file must have a encoding associated. UTF-8 will work everywhere. Just legacy projects would use other encoding.
  • And a very simple documentation. It can fill multiple lines.

See also: https://www.python.org/dev/peps/pep-0263/

If you just write a class in each file, you don't even need the documentation (it would go inside the class doc).

Maximum number of rows of CSV data in excel sheet

Using the Excel Text import wizard to import it if it is a text file, like a CSV file, is another option and can be done based on which row number to which row numbers you specify. See: This link

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

It happens when your HTTP request's headers claim that the content is gzip encoded, but it isn't. Turn off gzip encoding setting or make sure the content is in fact encoded.

How to check whether a string is a valid HTTP URL?

After Uri.TryCreate you can check Uri.Scheme to see if it HTTP(s).

Mongoimport of json file

this will work:

$  mongoimport --db databaseName --collection collectionName --file filePath/jsonFile.json 

2021-01-09T11:13:57.410+0530 connected to: mongodb://localhost/ 2021-01-09T11:13:58.176+0530 1 document(s) imported successfully. 0 document(s) failed to import.

Above I shared the query along with its response

Moq, SetupGet, Mocking a property

But while mocking read-only properties means properties with getter method only you should declare it as virtual otherwise System.NotSupportedException will be thrown because it is only supported in VB as moq internally override and create proxy when we mock anything.

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

It works for me...

if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
    {
    $certCallback = @"
        using System;
        using System.Net;
        using System.Net.Security;
        using System.Security.Cryptography.X509Certificates;
        public class ServerCertificateValidationCallback
        {
            public static void Ignore()
            {
                if(ServicePointManager.ServerCertificateValidationCallback ==null)
                {
                    ServicePointManager.ServerCertificateValidationCallback += 
                        delegate
                        (
                            Object obj, 
                            X509Certificate certificate, 
                            X509Chain chain, 
                            SslPolicyErrors errors
                        )
                        {
                            return true;
                        };
                }
            }
        }
    "@
        Add-Type $certCallback
     }
    [ServerCertificateValidationCallback]::Ignore()

Invoke-WebRequest -Uri https://apod.nasa.gov/apod/

Get HTML code from website in C#

I am using AngleSharp and have been very satisfied with it.

Here is a simple example how to fetch a page:

var config = Configuration.Default.WithDefaultLoader();
var document = await BrowsingContext.New(config).OpenAsync("https://www.google.com");

And now you have a web page in document variable. Then you can easily access it by LINQ or other methods. For example if you want to get a string value from a HTML table:

var someStringValue = document.All.Where(m =>
        m.LocalName == "td" &&
        m.HasAttribute("class") &&
        m.GetAttribute("class").Contains("pid-1-bid")
    ).ElementAt(0).TextContent.ToString();

To use CSS selectors please see AngleSharp examples.

delete map[key] in go?

Use make (chan int) instead of nil. The first value has to be the same type that your map holds.

package main

import "fmt"

func main() {

    var sessions = map[string] chan int{}
    sessions["somekey"] = make(chan int)

    fmt.Printf ("%d\n", len(sessions)) // 1

    // Remove somekey's value from sessions
    delete(sessions, "somekey")

    fmt.Printf ("%d\n", len(sessions)) // 0
}

UPDATE: Corrected my answer.

How to list all methods for an object in Ruby?

If You are looking list of methods which respond by an instance (in your case @current_user). According to ruby documentation methods

Returns a list of the names of public and protected methods of obj. This will include all the methods accessible in obj's ancestors. If the optional parameter is false, it returns an array of obj's public and protected singleton methods, the array will not include methods in modules included in obj.

@current_user.methods
@current_user.methods(false) #only public and protected singleton methods and also array will not include methods in modules included in @current_user class or parent of it.

Alternatively, You can also check that a method is callable on an object or not?.

@current_user.respond_to?:your_method_name

If you don't want parent class methods then just subtract the parent class methods from it.

@current_user.methods - @current_user.class.superclass.new.methods #methods that are available to @current_user instance.

public static const in TypeScript

Just simply 'export' variable and 'import' in your class

export var GOOGLE_API_URL = 'https://www.googleapis.com/admin/directory/v1';

// default err string message
export var errStringMsg = 'Something went wrong';

Now use it as,

import appConstants = require('../core/AppSettings');
console.log(appConstants.errStringMsg);
console.log(appConstants.GOOGLE_API_URL);

figure of imshow() is too small

That's strange, it definitely works for me:

from matplotlib import pyplot as plt

plt.figure(figsize = (20,2))
plt.imshow(random.rand(8, 90), interpolation='nearest')

I am using the "MacOSX" backend, btw.

How to use the unsigned Integer in Java 8 and Java 9?

There is no way how to declare an unsigned long or int in Java 8 or Java 9. But some methods treat them as if they were unsigned, for example:

static long values = Long.parseUnsignedLong("123456789012345678");

but this is not declaration of the variable.

XMLHttpRequest cannot load an URL with jQuery

You can't do a XMLHttpRequest crossdomain, the only "option" would be a technique called JSONP, which comes down to this:

To start request: Add a new <script> tag with the remote url, and then make sure that remote url returns a valid javascript file that calls your callback function. Some services support this (and let you name your callback in a GET parameters).

The other easy way out, would be to create a "proxy" on your local server, which gets the remote request and then just "forwards" it back to your javascript.

edit/addition:

I see jQuery has built-in support for JSONP, by checking if the URL contains "callback=?" (where jQuery will replace ? with the actual callback method). But you'd still need to process that on the remote server to generate a valid response.

Check whether values in one data frame column exist in a second data frame

Use %in% as follows

A$C %in% B$C

Which will tell you which values of column C of A are in B.

What is returned is a logical vector. In the specific case of your example, you get:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

Which you can use as an index to the rows of A or as an index to A$C to get the actual values:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

We can negate it too:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C



If you want to know if a specific value is in B$C, use the same function:

  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE

Cross-Origin Read Blocking (CORB)

Response headers are generally set on the server. Set 'Access-Control-Allow-Headers' to 'Content-Type' on server side

Check if a time is between two times (time DataType)

This should also work (even in SQL-Server 2005):

SELECT *
FROM dbo.MyTable
WHERE Created >= DATEADD(hh,23,DATEADD(day, DATEDIFF(day, 0, Created - 1), 0))
  AND Created <  DATEADD(hh,7,DATEADD(day, DATEDIFF(day, 0, Created), 0))

DEMO

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

I know this is an old question, but rather than adding the snapin which is apparently unsupported, I just looked at the EMS shortcut properties and copied those commands.

The full shortcut target is:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"

So I put the following at the start of my script and it seemed to function as expected:

. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto

Notes:

  • Has to be run in 64bit PS
  • This was tested on a server with just the Management Tools installed. It automatically connected to our existing Exchange infrastructure.
  • No extensive testing has been done, so I do not know if this method is viable. I will edit this post if I run into any issues.

Best way to get child nodes

Just to add to the other answers, there are still noteworthy differences here, specifically when dealing with <svg> elements.

I have used both .childNodes and .children and have preferred working with the HTMLCollection delivered by the .children getter.

Today however, I ran into issues with IE/Edge failing when using .children on an <svg>. While .children is supported in IE on basic HTML elements, it isn't supported on document/document fragments, or SVG elements.

For me, I was able to simply grab the needed elements via .childNodes[n] because I don't have extraneous text nodes to worry about. You may be able to do the same, but as mentioned elsewhere above, don't forget that you may run into unexpected elements.

Hope this is helpful to someone scratching their head trying to figure out why .children works elsewhere in their js on modern IE and fails on document or SVG elements.

Postgres "psql not recognized as an internal or external command"

Windows 10

It could be that your server doesn't start automatically on windows 10 and you need to start it yourself after setting your Postgresql path using the following command in cmd:

pg_ctl -D "C:\Program Files\PostgreSQL\11.4\data" start

You need to be inside "C:\Program Files\PostgreSQL\11.4\bin" directory to execute the above command.

EX:

enter image description here

You still need to be inside the bin directory to work with psql

"Conversion to Dalvik format failed with error 1" on external JAR

Updating Proguard to latest version solved it for me.

  • My proguard path was C:\Program Files (x86)\Android\android-sdk\tools\proguard\
  • I downloaded the new version from here
  • and replaced both bin and lib folders

THANK GOD!

What does ||= (or-equals) mean in Ruby?

Please also remember that ||= isn't an atomic operation and so, it isn't thread safe. As rule of thumb, don't use it for class methods.

How to build jars from IntelliJ properly?

You might want to take a look at Maven (http://maven.apache.org). You can use it either as the main build process for your application, or just to perform certain tasks through the Edit Configurations dialog. The process of creating a JAR of a module within Maven is fairly trivial, if you want it to include all the dependencies in a self-executable JAR that is trivial as well.

If you've never used Maven before then you want to read Better Builds With Maven.

How to flip background image using CSS?

For what it's worth, for Gecko-based browsers you can't condition this thing off of :visited due to the resulting privacy leaks. See http://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/

UTF-8 text is garbled when form is posted as multipart/form-data

I had the same problem using Apache commons-fileupload. I did not find out what causes the problems especially because I have the UTF-8 encoding in the following places: 1. HTML meta tag 2. Form accept-charset attribute 3. Tomcat filter on every request that sets the "UTF-8" encoding

-> My solution was to especially convert Strings from ISO-8859-1 (or whatever is the default encoding of your platform) to UTF-8:

new String (s.getBytes ("iso-8859-1"), "UTF-8");

hope that helps

Edit: starting with Java 7 you can also use the following:

new String (s.getBytes (StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

What is the difference between decodeURIComponent and decodeURI?

encodeURIComponent/decodeURIComponent() is almost always the pair you want to use, for concatenating together and splitting apart text strings in URI parts.

encodeURI in less common, and misleadingly named: it should really be called fixBrokenURI. It takes something that's nearly a URI, but has invalid characters such as spaces in it, and turns it into a real URI. It has a valid use in fixing up invalid URIs from user input, and it can also be used to turn an IRI (URI with bare Unicode characters in) into a plain URI (using %-escaped UTF-8 to encode the non-ASCII).

decodeURI decodes the same characters as decodeURIComponent except for a few special ones. It is provided to be an inverse of encodeURI, but you still can't count on it to return the same as you originally put in — see eg. decodeURI(encodeURI('%20 '));.

Where encodeURI should really be named fixBrokenURI(), decodeURI() could equally be called potentiallyBreakMyPreviouslyWorkingURI(). I can think of no valid use for it anywhere; avoid.

How to disable Compatibility View in IE

Another way to achieve this in Apache is by putting the following lines in .htaccess in the root folder of your website (or in Apache's config files).

BrowserMatch "MSIE" isIE
BrowserMatch "Trident" isIE
Header set X-UA-Compatible "IE=edge" env=isIE

This requires that you have the mod_headers and mod_setenvif modules enabled.

The extra HTTP header only gets sent to IE browsers, and none of the others.

Reset the Value of a Select Box

I found a little utility function a while back and I've been using it for resetting my form elements ever since (source: http://www.learningjquery.com/2007/08/clearing-form-data):

function clearForm(form) {
  // iterate over all of the inputs for the given form element
  $(':input', form).each(function() {
    var type = this.type;
    var tag = this.tagName.toLowerCase(); // normalize case
    // it's ok to reset the value attr of text inputs, 
    // password inputs, and textareas
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = "";
    // checkboxes and radios need to have their checked state cleared 
    // but should *not* have their 'value' changed
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    // select elements need to have their 'selectedIndex' property set to -1
    // (this works for both single and multiple select elements)
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

... or as a jQuery plugin...

$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

Use tnsnames.ora in Oracle SQL Developer

On the newer versions of macOS, one also has to set java.library.path. The easiest/safest way to do that [1] is by creating ~/.sqldeveloper/<version>/sqldeveloper.conf file and populating it as such:

AddVMOption -Djava.library.path=<instant client directory>

[1] https://community.oracle.com/message/14132189#14132189

How to open .SQLite files

If you just want to see what's in the database without installing anything extra, you might already have SQLite CLI on your system. To check, open a command prompt and try:

sqlite3 database.sqlite

Replace database.sqlite with your database file. Then, if the database is small enough, you can view the entire contents with:

sqlite> .dump

Or you can list the tables:

sqlite> .tables

Regular SQL works here as well:

sqlite> select * from some_table;

Replace some_table as appropriate.

Run a JAR file from the command line and specify classpath

You can do these in unix shell:

java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

You can do these in windows powershell:

java -cp "MyJar.jar;lib\*" com.somepackage.subpackage.Main

jQuery's .click - pass parameters to user function

      $imgReload.data('self', $self);
            $imgReload.click(function (e) {
                var $p = $(this).data('self');
                $p._reloadTable();
            });

Set javaScript object to onclick element:

 $imgReload.data('self', $self);

get Object from "this" element:

 var $p = $(this).data('self');

How to pass arguments to entrypoint in docker-compose.yml

To override the default entrypoint, use entrypoint option. To pass the arguments use command.

Here is the example of replacing bash with sh in ubuntu image:

version: '3'
services:
  sh:
    entrypoint: /bin/sh
    command: -c "ps $$(echo $$$$)"
    image: ubuntu
    tty: true
  bash:
    entrypoint: /bin/bash
    command: -c "ps $$(echo $$$$)"
    image: ubuntu
    tty: true

Here is the output:

$ docker-compose up   
Starting test_sh_1                ... done
Starting 020211508a29_test_bash_1 ... done
Attaching to test_sh_1, 020211508a29_test_bash_1
sh_1    |   PID TTY      STAT   TIME COMMAND
sh_1    |     1 pts/0    Ss+    0:00 /bin/sh -c ps $(echo $$)
020211508a29_test_bash_1 |   PID TTY      STAT   TIME COMMAND
020211508a29_test_bash_1 |     1 pts/0    Rs+    0:00 ps 1

How to set the text color of TextView in code?

Similarly, I was using color.xml:

<color name="white">#ffffff</color>
    <color name="black">#000000</color>   

For setting the TextView background like:

textView.setTextColor(R.color.white);

I was getting a different color, but when I used the below code I got the actual color.

textView.setTextColor(Color.parseColor("#ff6363"));

Prevent Sequelize from outputting SQL to the console on execution of query?

Here is my answer:

Brief: I was using typeorm as a ORM library. So, to set the query logging level I have used the following option instead of directly setting the logging option as false.

Solution: File name - ormconfig.ts

{
    'type': process.env.DB_DRIVER,
    'host': process.env.DB_HOST,
    'port': process.env.DB_PORT,
    'username': process.env.DB_USER,
    'password': process.env.DB_PASS,
    'database': process.env.DB_NAME,
    'migrations': [process.env.MIGRATIONS_ENTITIES],
    'synchronize': false,
    'logging': process.env.DB_QUERY_LEVEL,
    'entities': [
        process.env.ORM_ENTITIES
    ],
    'cli': {
        'migrationsDir': 'migrations'
     }
}

And, in the envrionment variable set the DB_QUERY_LEVEL as ["query", "error"].

Result: As a result it will log only when the query has error else it won't.

Ref link: typeorm db query logging doc

Hope this helps! Thanks.

What can I use for good quality code coverage for C#/.NET?

I am not sure what the difference is with the retail NCover, but there is also an NCover project on SourceForge that is of course open source and free.

How do I access nested HashMaps in Java?

I came to this StackOverflow page looking for a something ala valueForKeyPath known from objc. I also came by another post - "Key-Value Coding" for Java, but ended up writing my own.

I'm still looking for at better solution than PropertyUtils.getProperty in apache's beanutils library.

Usage

Map<String, Object> json = ...
public String getOptionalFirstName() {
    return MyCode.getString(json, "contact", "firstName");
}

Implementation

public static String getString(Object object, String key0, String key1) {
    if (key0 == null) {
        return null;
    }
    if (key1 == null) {
        return null;
    }
    if (object instanceof Map == false) {
        return null;
    }
    @SuppressWarnings("unchecked")
    Map<Object, Object> map = (Map<Object, Object>)object;
    Object object1 = map.get(key0);
    if (object1 instanceof Map == false) {
        return null;
    }
    @SuppressWarnings("unchecked")
    Map<Object, Object> map1 = (Map<Object, Object>)object1;
    Object valueObject = map1.get(key1);
    if (valueObject instanceof String == false) {
        return null;
    }
    return (String)valueObject;
}

HAProxy redirecting http to https (ssl)

In newer versions of HAProxy it is recommended to use

http-request redirect scheme https if !{ ssl_fc }

to redirect http traffic to https.

Using % for host when creating a MySQL user

Going to provide a slightly different answer to those provided so far.

If you have a row for an anonymous user from localhost in your users table ''@'localhost' then this will be treated as more specific than your user with wildcard'd host 'user'@'%'. This is why it is necessary to also provide 'user'@'localhost'.

You can see this explained in more detail at the bottom of this page.

ContractFilter mismatch at the EndpointDispatcher exception

I had this error and it was caused by the recevier contract not implementing the method being called. Basically, someone hadn't deployed the lastest version of the WCF service to the host server.

Struct Constructor in C++?

In C++ both struct & class are equal except struct'sdefault member access specifier is public & class has private.

The reason for having struct in C++ is C++ is a superset of C and must have backward compatible with legacy C types.

For example if the language user tries to include some C header file legacy-c.h in his C++ code & it contains struct Test {int x,y};. Members of struct Test should be accessible as like C.

remove all special characters in java

You can read the lines and replace all special characters safely this way.
Keep in mind that if you use \\W you will not replace underscores.

Scanner scan = new Scanner(System.in);

while(scan.hasNextLine()){
    System.out.println(scan.nextLine().replaceAll("[^a-zA-Z0-9]", ""));
}

Why not inherit from List<T>?

Problems with serializing

One aspect is missing. Classes that inherit from List can't be serialized correctly using XmlSerializer. In that case DataContractSerializer must be used instead, or an own serializing implementation is needed.
public class DemoList : List<Demo>
{
    // using XmlSerializer this properties won't be seralized
    // There is no error, the data is simply not there.
    string AnyPropertyInDerivedFromList { get; set; }     
}

public class Demo
{
    // this properties will be seralized
    string AnyPropetyInDemo { get; set; }  
}

Further reading: When a class is inherited from List<>, XmlSerializer doesn't serialize other attributes

Python spacing and aligning strings

@IronMensan's format method answer is the way to go. But in the interest of answering your question about ljust:

>>> def printit():
...     print 'Location: 10-10-10-10'.ljust(40) + 'Revision: 1'
...     print 'District: Tower'.ljust(40) + 'Date: May 16, 2012'
...     print 'User: LOD'.ljust(40) + 'Time: 10:15'
...
>>> printit()
Location: 10-10-10-10                   Revision: 1
District: Tower                         Date: May 16, 2012
User: LOD                               Time: 10:15

Edit to note this method doesn't require you to know how long your strings are. .format() may also, but I'm not familiar enough with it to say.

>>> uname='LOD'
>>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
'User: LOD                               Time: 10:15'
>>> uname='Tiddlywinks'
>>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
'User: Tiddlywinks                       Time: 10:15'

ASP.NET MVC - Set custom IIdentity or IPrincipal

As an addition to LukeP code for Web Forms users (not MVC) if you want to simplify the access in the code behind of your pages, just add the code below to a base page and derive the base page in all your pages:

Public Overridable Shadows ReadOnly Property User() As CustomPrincipal
    Get
        Return DirectCast(MyBase.User, CustomPrincipal)
    End Get
End Property

So in your code behind you can simply access:

User.FirstName or User.LastName

What I'm missing in a Web Form scenario, is how to obtain the same behaviour in code not tied to the page, for example in httpmodules should I always add a cast in each class or is there a smarter way to obtain this?

Thanks for your answers and thank to LukeP since I used your examples as a base for my custom user (which now has User.Roles, User.Tasks, User.HasPath(int) , User.Settings.Timeout and many other nice things)

Add object to ArrayList at specified index

If you are using the Android flavor of Java, might I suggest using a SparseArray. It's a more memory efficient mapping of integers to objects and easier to iterate over than a Map

Get the value of a dropdown in jQuery

If you're using a <select>, .val() gets the 'value' of the selected <option>. If it doesn't have a value, it may fallback to the id. Put the value you want it to return in the value attribute of each <option>

Edit: See comments for clarification on what value actually is (not necessarily equal to the value attribute).

Javascript get object key name

Here is a simple example, it will help you to get object key name.

var obj ={parts:{costPart:1000, salesPart: 2000}}; console.log(Object.keys(obj));

the output would be parts.

How do I profile memory usage in Python?

If you only want to look at the memory usage of an object, (answer to other question)

There is a module called Pympler which contains the asizeof module.

Use as follows:

from pympler import asizeof
asizeof.asizeof(my_object)

Unlike sys.getsizeof, it works for your self-created objects.

>>> asizeof.asizeof(tuple('bcd'))
200
>>> asizeof.asizeof({'foo': 'bar', 'baz': 'bar'})
400
>>> asizeof.asizeof({})
280
>>> asizeof.asizeof({'foo':'bar'})
360
>>> asizeof.asizeof('foo')
40
>>> asizeof.asizeof(Bar())
352
>>> asizeof.asizeof(Bar().__dict__)
280
>>> help(asizeof.asizeof)
Help on function asizeof in module pympler.asizeof:

asizeof(*objs, **opts)
    Return the combined size in bytes of all objects passed as positional arguments.

Git: Pull from other remote

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

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

then you would use this to pull changes:

git pull upstream master

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

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

And to pull: git pull origin master

Make browser window blink in task Bar

You may want to try window.focus() - but it may be annoying if the screen switches around

ASP.NET MVC - Extract parameter of an URL

Update

RouteData.Values["id"] + Request.Url.Query

Will match all your examples


It is not entirely clear what you are trying to achieve. MVC passes URL parameters for you through model binding.

public class CustomerController : Controller {

  public ActionResult Edit(int id) {

    int customerId = id //the id in the URL

    return View();
  }

}


public class ProductController : Controller {

  public ActionResult Edit(int id, bool allowed) { 

    int productId = id; // the id in the URL
    bool isAllowed = allowed  // the ?allowed=true in the URL

    return View();
  }

}

Adding a route mapping to your global.asax.cs file before the default will handle the /administration/ part. Or you might want to look into MVC Areas.

routes.MapRoute(
  "Admin", // Route name
  "Administration/{controller}/{action}/{id}", // URL with parameters
  new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults

If it's the raw URL data you are after then you can use one of the various URL and Request properties available in your controller action

string url = Request.RawUrl;
string query= Request.Url.Query;
string isAllowed= Request.QueryString["allowed"];

It sounds like Request.Url.PathAndQuery could be what you want.

If you want access to the raw posted data you can use

string isAllowed = Request.Params["allowed"];
string id = RouteData.Values["id"];

Facebook OAuth "The domain of this URL isn't included in the app's domain"

This same Facebook error happened to me in the Production environment. The reason was I had 2 apps registered with Facebook (Local, Production) but I hardcoded the Local app ID into the source code and forgot to switch it out for the Production app ID before deployment.

Best practice dictates you shouldn't have the app ID hardcoded into the source code but if you do, do not mismatch your various Facebook app IDs like I mistakenly did.

"Unable to find remote helper for 'https'" during git clone

CentOS Minimal usually install version 1.8 git by yum install gitcommand.

The best way is to build & install it from source code. Current version is 2.18.0.

  1. Download the source code from https://mirrors.edge.kernel.org/pub/software/scm/git/ or curl -o git-2.18.0.tar.gz https://mirrors.edge.kernel.org/pub/software/scm/git/git-2.18.0.tar.gz

  2. Unzip by tar -zxf git-2.18.0.tar.gz && cd git-2.18.0

  3. Install the dependency package by executing yum install autoconf curl-devel expat-devel gettext-devel openssl-devel perl-devel zlib-devel asciidoc xmlto openjade perl* texinfo

  4. Install docbook2X, it's not in the rpm repository. Download and install by

    $ curl -o docbook2X-0.8.8-17.el7.x86_64.rpm http://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/d/docbook2X-0.8.8-17.el7.x86_64.rpm $ rpm -Uvh docbook2X-0.8.8-17.el7.x86_64.rpm

And make a unix link name:

ln -s /usr/bin/db2x_docbook2texi /usr/bin/docbook2x-texi
  1. Compile and install, reference to https://git-scm.com/book/en/v2/Getting-Started-Installing-Git

    $ make configure $ ./configure --prefix=/usr $ make all doc info $ sudo make install install-doc install-html install-info

  2. Reboot your server (If not, you may encounter Unable to find remote helper for 'https' error)

    $ reboot now

  3. Test:

    $ git clone https://github.com/volnet/v-labs.git $ cd v-labs $ touch test.txt $ git add . $ git commit -m "test git install" $ git push -u

Extracting just Month and Year separately from Pandas Datetime column

df['year_month']=df.datetime_column.apply(lambda x: str(x)[:7])

This worked fine for me, didn't think pandas would interpret the resultant string date as date, but when i did the plot, it knew very well my agenda and the string year_month where ordered properly... gotta love pandas!

How to get JS variable to retain value after page refresh?

You can do that by storing cookies on client side.

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

Check your computer's Date and Time. If it is wrong, update it to the current time or set it automatically to get the time from the Internet.

Because certificates are tied to a fixed time period, if your clock is wrong, you are likely to get errors like this. In that scenario, by fixing the time, the problem will be fixed.

What does it mean when an HTTP request returns status code 0?

If you are testing on local PC, it won't work. To test Ajax example you need to place the HTML files on a web server.

How to use localization in C#

In addition @Fredrik Mörk's great answer on strings, to add localization to a form do the following:

  • Set the form's property "Localizable" to true
  • Change the form's Language property to the language you want (from a nice drop-down with them all in)
  • Translate the controls in that form and move them about if need be (squash those really long full French sentences in!)

Edit: This MSDN article on Localizing Windows Forms is not the original one I linked ... but might shed more light if needed. (the old one has been taken away)

Find objects between two dates MongoDB

Querying for a Date Range (Specific Month or Day) in the MongoDB Cookbook has a very good explanation on the matter, but below is something I tried out myself and it seems to work.

items.save({
    name: "example",
    created_at: ISODate("2010-04-30T00:00:00.000Z")
})
items.find({
    created_at: {
        $gte: ISODate("2010-04-29T00:00:00.000Z"),
        $lt: ISODate("2010-05-01T00:00:00.000Z")
    }
})
=> { "_id" : ObjectId("4c0791e2b9ec877893f3363b"), "name" : "example", "created_at" : "Sun May 30 2010 00:00:00 GMT+0300 (EEST)" }

Based on my experiments you will need to serialize your dates into a format that MongoDB supports, because the following gave undesired search results.

items.save({
    name: "example",
    created_at: "Sun May 30 18.49:00 +0000 2010"
})
items.find({
    created_at: {
        $gte:"Mon May 30 18:47:00 +0000 2015",
        $lt: "Sun May 30 20:40:36 +0000 2010"
    }
})
=> { "_id" : ObjectId("4c079123b9ec877893f33638"), "name" : "example", "created_at" : "Sun May 30 18.49:00 +0000 2010" }

In the second example no results were expected, but there was still one gotten. This is because a basic string comparison is done.

Text blinking jQuery

Try this :

setInterval( function() { $(".me").fadeOut(500).fadeIn(500) } , 500);

What is the most efficient way to create HTML elements using jQuery?

This is not the correct answer for the question but still I would like to share this...

Using just document.createElement('div') and skipping JQuery will improve the performance a lot when you want to make lot of elements on the fly and append to DOM.

Parsing JSON giving "unexpected token o" error

I had the same problem when I submitted data using jQuery AJAX:

$.ajax({
   url:...
   success:function(data){
      //server response's data is JSON
      //I use jQuery's parseJSON method 
      $.parseJSON(data);//it's ERROR
   }
});

If the response is JSON, and you use this method, the data you get is a JavaScript object, but if you use dataType:"text", data is a JSON string. Then the use of $.parseJSON is okay.

Has an event handler already been added?

If I understand your problem correctly you may have bigger issues. You said that other objects may subscribe to these events. When the object is serialized and deserialized the other objects (the ones that you don't have control of) will lose their event handlers.

If you're not worried about that then keeping a reference to your event handler should be good enough. If you are worried about the side-effects of other objects losing their event handlers, then you may want to rethink your caching strategy.

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

Push an associative item into an array in JavaScript

To make something like associative array in JavaScript you have to use objects. ?

_x000D_
_x000D_
var obj = {}; // {} will create an object
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);
_x000D_
_x000D_
_x000D_

DEMO: http://jsfiddle.net/bz8pK/1/

How do I start an activity from within a Fragment?

Use the Base Context of the Activity in which your fragment resides to start an Intent.

Intent j = new Intent(fBaseCtx, NewactivityName.class);         
startActivity(j);

where fBaseCtx is BaseContext of your current activity. You can get it as fBaseCtx = getBaseContext();

What values for checked and selected are false?

The checked and selected attributes are allowed only two values, which are a copy of the attribute name and (from HTML 5 onwards) an empty string. Giving any other value is an error.

If you don't want to set the attribute, then the entire attribute must be omitted.

Note that in HTML 4 you may omit everything except the value. HTML 5 changed this to omit everything except the name (which makes no practical difference).

Thus, the complete (aside from variations in cAsE) set of valid representations of the attribute are:

<input ... checked="checked"> <!-- All versions of HTML / XHTML -->
<input ...          checked > <!-- Only HTML 4.01 and earlier -->
<input ... checked          > <!-- Only HTML 5 and later -->
<input ... checked=""       > <!-- Only HTML 5 and later -->

Documents served as text/html (HTML or XHTML) will be fed through a tag soup parser, and the presence of a checked attribute (with any value) will be treated as "This element should be checked". Thus, while invalid, checked="true", checked="yes", and checked="false" will all trigger the checked state.

I've not had any inclination to find out what error recovery mechanisms are in place for XML parsing mode should a different value be given to the attribute, but I would expect that the legacy of HTML and/or simple error recovery would treat it in the same way: If the attribute is there then the element is checked.

(And all the above applies equally to selected as it does to checked.)

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

This will work if you are trying to Grant permission to Users or roles.

Using Microsoft SQL Server Management Studio:

  1. Go to: Databases
  2. Right click on dbo.my_database
  3. Choose: Properties
  4. On the left side panel, click on: Permissions
  5. Select the User or Role and in the Name Panel
  6. Find Execute in in permissions and checkmark: Grant,With Grant, or Deny

Deprecated Java HttpClient - How hard can it be?

IMHO the accepted answer is correct but misses some 'teaching' as it does not explain how to come up with the answer. For all deprecated classes look at the JavaDoc (if you do not have it either download it or go online), it will hint at which class to use to replace the old code. Of course it will not tell you everything, but this is a start. Example:

...
 *
 * @deprecated (4.3) use {@link HttpClientBuilder}.  <----- THE HINT IS HERE !
 */
@ThreadSafe
@Deprecated
public class DefaultHttpClient extends AbstractHttpClient {

Now you have the class to use, HttpClientBuilder, as there is no constructor to get a builder instance you may guess that there must be a static method instead: create. Once you have the builder you can also guess that as for most builders there is a build method, thus:

org.apache.http.impl.client.HttpClientBuilder.create().build();

AutoClosable:

As Jules hinted in the comments, the returned class implements java.io.Closable, so if you use Java 7 or above you can now do:

    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {...}

The advantage is that you do not have to deal with finally and nulls.

Other relevant info

Also make sure to read about connection pooling and set the timeouts.

Resolving IP Address from hostname with PowerShell

You can use this code if you have a bunch of hosts in text file

$a = get-content "C:\Users\host.txt"(file path) 

foreach ($i in $a )
    {
$i + "`n" + "==========================";[System.Net.Dns]::GetHostAddresses($i) 

}

Swift error : signal SIGABRT how to solve it

To solve the problem, first clean the project and then rebuild.

To clean the project, go to MenuBar: Product -> Clean

Then to rebuild the project, just click the Run button as usual.

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

First few lines: man head.

Append lines: use the >> operator (?) in Bash:

echo 'This goes at the end of the file' >> file

How abstraction and encapsulation differ?

my 2c

the purpose of encapsulation is to hide implementation details from the user of your class e.g. if you internally keep a std::list of items in your class and then decide that a std::vector would be more effective you can change this without the user caring. That said, the way you interact with the either stl container is thanks to abstraction, both the list and the vector can for instance be traversed in the same way using similar methods (iterators).

Invalid http_host header

settings.py

ALLOWED_HOSTS = ['*']

Get the current date and time

Get Current DateTime

Now.ToShortDateString()
DateTime.Now
Today.Now

align images side by side in html

I suggest to use a container for each img p like this:

<div class="image123">
    <div style="float:left;margin-right:5px;">
        <img src="/images/tv.gif" height="200" width="200"  />
        <p style="text-align:center;">This is image 1</p>
    </div>
    <div style="float:left;margin-right:5px;">
        <img class="middle-img" src="/images/tv.gif/" height="200" width="200" />
        <p style="text-align:center;">This is image 2</p>
    </div>
    <div style="float:left;margin-right:5px;">
        <img src="/images/tv.gif/" height="200" width="200" />
        <p style="text-align:center;">This is image 3</p>
    </div>
</div>

Then apply float:left to each container. I add and 5px margin right so there is a space between each image. Also alway close your elements. Maybe in html img tag is not important to close but in XHTML is.

fiddle

Also a friendly advice. Try to avoid inline styles as much as possible. Take a look here:

html

<div class="image123">
    <div>
        <img src="/images/tv.gif" />
        <p>This is image 1</p>
    </div>
    <div>
        <img class="middle-img" src="/images/tv.gif/" />
        <p>This is image 2</p>
    </div>
    <div>
        <img src="/images/tv.gif/" />
        <p>This is image 3</p>
    </div>
</div>

css

div{
    float:left;
    margin-right:5px;
}

div > img{
   height:200px;
    width:200px;
}

p{
    text-align:center;
}

It's generally recommended that you use linked style sheets because:

  • They can be cached by browsers for performance
  • Generally a lot easier to maintain for a development perspective

source

fiddle

Edit In Place Content Editing

Since this is a common piece of functionality it's a good idea to write a directive for this. In fact, someone already did that and open sourced it. I used editablespan library in one of my projects and it worked perfectly, highly recommended.

Should CSS always preceed Javascript?

Were your tests performed on your personal computer, or on a web server? It is a blank page, or is it a complex online system with images, databases, etc.? Are your scripts performing a simple hover event action, or are they a core component to how your website renders and interacts with the user? There are several things to consider here, and the relevance of these recommendations almost always become rules when you venture into high-caliber web development.

The purpose of the "put stylesheets at the top and scripts at the bottom" rule is that, in general, it's the best way to achieve optimal progressive rendering, which is critical to the user experience.

All else aside: assuming your test is valid, and you really are producing results contrary to the popular rules, it'd come as no surprise, really. Every website (and everything it takes to make the whole thing appear on a user's screen) is different and the Internet is constantly evolving.

jQuery - Call ajax every 10 seconds

setInterval(function()
{ 
    $.ajax({
      type:"post",
      url:"myurl.html",
      datatype:"html",
      success:function(data)
      {
          //do something with response data
      }
    });
}, 10000);//time in milliseconds 

Reset AutoIncrement in SQL Server after Delete

I want to add this answer because the DBCC CHECKIDENT-approach will product problems when you use schemas for tables. Use this to be sure:

DECLARE @Table AS NVARCHAR(500) = 'myschema.mytable';
DBCC CHECKIDENT (@Table, RESEED, 0);

If you want to check the success of the operation, use

SELECT IDENT_CURRENT(@Table);

which should output 0 in the example above.

Quick way to list all files in Amazon S3 bucket?

In PHP you can get complete list of AWS-S3 objects inside specific bucket using following call

$S3 = \Aws\S3\S3Client::factory(array('region' => $region,));
$iterator = $S3->getIterator('ListObjects', array('Bucket' => $bucket));
foreach ($iterator as $obj) {
    echo $obj['Key'];
}

You can redirect output of the above code in to a file to get list of keys.

How to change color of Android ListView separator line?

XML version for @Asher Aslan cool effect.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <gradient
        android:angle="180"
        android:startColor="#00000000"
        android:centerColor="#FFFF0000"
        android:endColor="#00000000"/>

</shape>

Name for that shape as: list_driver.xml under drawable folder

<ListView
        android:id="@+id/category_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 
        android:divider="@drawable/list_driver"
        android:dividerHeight="5sp" />

Java - how do I write a file to a specified directory

Use:

File file = new File("Z:\\results\\results.txt");

You need to double the backslashes in Windows because the backslash character itself is an escape in Java literal strings.

For POSIX system such as Linux, just use the default file path without doubling the forward slash. this is because forward slash is not a escape character in Java.

File file = new File("/home/userName/Documents/results.txt");

Opening a new tab to read a PDF file

Try this, it worked for me.

<td><a href="Docs/Chapter 1_ORG.pdf" target="pdf-frame">Chapter-1 Organizational</a></td>

Alter column in SQL Server

To set a default value to a column, try this:

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status SET DEFAULT 'default value'

How to push changes to github after jenkins build completes?

I followed the below Steps. It worked for me.

In Jenkins execute shell under Build, creating a file and trying to push that file from Jenkins workspace to GitHub.

enter image description here

Download Git Publisher Plugin and Configure as shown below snapshot.

enter image description here

Click on Save and Build. Now you can check your git repository whether the file was pushed successfully or not.

Loop through all the rows of a temp table and call a stored procedure for each row

you could use a cursor:

DECLARE @id int
DECLARE @pass varchar(100)

DECLARE cur CURSOR FOR SELECT Id, Password FROM @temp
OPEN cur

FETCH NEXT FROM cur INTO @id, @pass

WHILE @@FETCH_STATUS = 0 BEGIN
    EXEC mysp @id, @pass ... -- call your sp here
    FETCH NEXT FROM cur INTO @id, @pass
END

CLOSE cur    
DEALLOCATE cur

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

I know this is an old question but I want to share an example that I think explains bounded wildcards pretty well. java.util.Collections offers this method:

public static <T> void sort(List<T> list, Comparator<? super T> c) {
    list.sort(c);
}

If we have a List of T, the List can, of course, contain instances of types that extend T. If the List contains Animals, the List can contain both Dogs and Cats (both Animals). Dogs have a property "woofVolume" and Cats have a property "meowVolume." While we might like to sort based upon these properties particular to subclasses of T, how can we expect this method to do that? A limitation of Comparator is that it can compare only two things of only one type (T). So, requiring simply a Comparator<T> would make this method usable. But, the creator of this method recognized that if something is a T, then it is also an instance of the superclasses of T. Therefore, he allows us to use a Comparator of T or any superclass of T, i.e. ? super T.

Python list directory, subdirectory, and files

A bit simpler one-liner:

import os
from itertools import product, chain

chain.from_iterable([[os.sep.join(w) for w in product([i[0]], i[2])] for i in os.walk(dir)])

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

I am late here, but this might help someone looking for the answer. Typically servletRequest.getRemoteAddr() works.

In many cases your application users might be accessing your web server via a proxy server or maybe your application is behind a load balancer.

So you should access the X-Forwarded-For http header in such a case to get the user's IP address.

e.g. String ipAddress = request.getHeader("X-FORWARDED-FOR");

Hope this helps.

When increasing the size of VARCHAR column on a large table could there be any problems?

Another reason why you should avoid converting the column to varchar(max) is because you cannot create an index on a varchar(max) column.

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

If any one had the same problem as me and the charset was already correct, simply do this:

  1. Copy all the code inside the .html file.
  2. Open notepad (or any basic text editor) and paste the code.
  3. Go "File -> Save As"
  4. Enter you file name "example.html" (Select "Save as type: All Files (.)")
  5. Select Encoding as UTF-8
  6. Hit Save and you can now delete your old .html file and the encoding should be fixed

SQL statement to get column type

For Apache Derby as shown in this answer:

select columndatatype from sys.syscolumns
  where referenceid = (
    select tableid from sys.systables
    where tablename = 'YOUR_TABEL_NAME'
    and columnname= 'YOUR_COLUMN_NAME')

android get all contacts

Get contacts info , photo contacts , photo uri and convert to Class model

1). Sample for Class model :

    public class ContactModel {
        public String id;
        public String name;
        public String mobileNumber;
        public Bitmap photo;
        public Uri photoURI;
    }

2). get Contacts and convert to Model

     public List<ContactModel> getContacts(Context ctx) {
        List<ContactModel> list = new ArrayList<>();
        ContentResolver contentResolver = ctx.getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor cursorInfo = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                    InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(ctx.getContentResolver(),
                            ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));

                    Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id));
                    Uri pURI = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);

                    Bitmap photo = null;
                    if (inputStream != null) {
                        photo = BitmapFactory.decodeStream(inputStream);
                    }
                    while (cursorInfo.moveToNext()) {
                        ContactModel info = new ContactModel();
                        info.id = id;
                        info.name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        info.mobileNumber = cursorInfo.getString(cursorInfo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        info.photo = photo;
                        info.photoURI= pURI;
                        list.add(info);
                    }

                    cursorInfo.close();
                }
            }
            cursor.close();
        }
        return list;
    }

text-align:center won't work with form <label> tag (?)

label is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center but since the label is only as wide as the text you don't notice.

The best thing to do is to apply a specific width to the label that is greater than the width of the content - this will give you the results you want.

phpinfo() is not working on my CentOS server

I accidentally set the wrong file permissions. After chmod 644 phpinfo.php the info indeed showed up as expected.

Error "gnu/stubs-32.h: No such file or directory" while compiling Nachos source code

You're missing the 32 bit libc dev package:

On Ubuntu it's called libc6-dev-i386 - do sudo apt-get install libc6-dev-i386. See below for extra instructions for Ubuntu 12.04.

On Red Hat distros, the package name is glibc-devel.i686 (Thanks to David Gardner's comment).

On CentOS 5.8, the package name is glibc-devel.i386 (Thanks to JimKleck's comment).

On CentOS 6 / 7, the package name is glibc-devel.i686.

On SLES it's called glibc-devel-32bit - do zypper in glibc-devel-32bit.

On Gentoo it's called sys-libs/glibc - do emerge -1a sys-libs/gcc [source] (Note : One may use equery to confirm this is correct; do equery belongs belongs /usr/include/gnu/stubs-32.h)

On ArchLinux, the package name is lib32-glibc - do pacman -S lib32-glibc.


Are you using Ubuntu 12.04? There is a known problem that puts the files in a non standard location. You'll also need to do:

export LIBRARY_PATH=/usr/lib/$(gcc -print-multiarch)
export C_INCLUDE_PATH=/usr/include/$(gcc -print-multiarch)
export CPLUS_INCLUDE_PATH=/usr/include/$(gcc -print-multiarch)

somewhere before you build (say in your .bashrc).


If you are also compiling C++ code, you will also need the 32 bit stdc++ library. If you see this warning:

.... /usr/bin/ld: cannot find -lstdc++ ....

On Ubuntu you will need to do sudo apt-get install g++-multilib

On CentOS 5 you will need to do yum install libstdc++-devel.i386

On CentOS 6 you will need to do yum install libstdc++-devel.i686

Please feel free to edit in the packages for other systems.

General error: 1364 Field 'user_id' doesn't have a default value

Try

'user_id' => auth()->id
or

'user_id' => Auth::user()->id

instead of

'user_id' => auth()->id()

Where can I find php.ini?

Run this in the command line:

php -r "echo php_ini_loaded_file().PHP_EOL;"

How to control border height?

A border will always be at the full length of the containing box (the height of the element plus its padding), it can't be controlled except for adjusting the height of the element to which it applies. If all you need is a vertical divider, you could use:

<div id="left">
  content
</div>
<span class="divider"></span>
<div id="right">
  content
</div>

With css:

span {
 display: inline-block;
 width: 0;
 height: 1em;
 border-left: 1px solid #ccc;
 border-right: 1px solid #ccc;
}

Demo at JS Fiddle, adjust the height of the span.container to adjust the border 'height'.

Or, to use pseudo-elements (::before or ::after), given the following HTML:

<div id="left">content</div>
<div id="right">content</div>

The following CSS adds a pseudo-element before any div element that's the adjacent sibling of another div element:

div {
    display: inline-block;
    position: relative;
}

div + div {
    padding-left: 0.3em;
}

div + div::before {
    content: '';
    border-left: 2px solid #000;
    position: absolute;
    height: 50%;
    left: 0;
    top: 25%;
}

JS Fiddle demo.

Use Excel pivot table as data source for another Pivot Table

Personally, I got around this in a slightly different way - I had a pivot table querying an SQL server source and I was using the timeline slicer to restrict the results to a date range - I then wanted to summarise the pivot results in another table.

I selected the 'source' pivot table and created a named range called 'SourcePivotData'.

Create your summary pivot tables using the named range as a source.

In the worksheet events for the source pivot table, I put the following code:

Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)

'Update the address of the named range
ThisWorkbook.Names("SourcePivotData").RefersTo = "='" & Target.TableRange1.Worksheet.Name & "'!" & Target.TableRange1.AddressLocal

'Refresh any pivot tables that use this as a source
Dim pt As PivotTable
Application.DisplayAlerts = False
For Each pt In Sheet2.PivotTables
    pt.PivotCache.Refresh
Next pt
Application.DisplayAlerts = True

End Sub

Works nicely for me! :)

How to format a float in javascript?

var result = Math.round(original*100)/100;

The specifics, in case the code isn't self-explanatory.

edit: ...or just use toFixed, as proposed by Tim Büthe. Forgot that one, thanks (and an upvote) for reminder :)

Where does R store packages?

Thanks for the direction from the above two answerers. James Thompson's suggestion worked best for Windows users.

  1. Go to where your R program is installed. This is referred to as R_Home in the literature. Once you find it, go to the /etc subdirectory.

    C:\R\R-2.10.1\etc
    
  2. Select the file in this folder named Rprofile.site. I open it with VIM. You will find this is a bare-bones file with less than 20 lines of code. I inserted the following inside the code:

    # my custom library path
    .libPaths("C:/R/library")
    

    (The comment added to keep track of what I did to the file.)

  3. In R, typing the .libPaths() function yields the first target at C:/R/Library

NOTE: there is likely more than one way to achieve this, but other methods I tried didn't work for some reason.

Can't update: no tracked branch

 git commit -m "first commit"

 git remote add origin <linkyourrepository>

 git push -u origin master

will works!

Fatal error: Class 'SoapClient' not found

To install SOAP in PHP-7 run following in your Ubuntu terminal:

sudo apt-get install php7.0-soap

To install SOAP in PHP-7.1 run following in your Ubuntu terminal:

sudo apt-get install php7.1-soap

To install SOAP in PHP-7.2 run following in your Ubuntu terminal:

sudo apt-get install php7.2-soap

To install SOAP in PHP-7.3 run following in your Ubuntu terminal:

sudo apt-get install php7.3-soap

Adding placeholder text to textbox

Attached properties to the rescue:

public static class TextboxExtensions
{
    public static readonly DependencyProperty PlaceholderProperty = 
        DependencyProperty.RegisterAttached(
            "Placeholder", 
            typeof(string), 
            typeof(TextboxExtensions), 
            new PropertyMetadata(default(string), propertyChangedCallback: PlaceholderChanged)
            );

    private static void PlaceholderChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
    {
        var tb = dependencyObject as TextBox;

        if (tb == null)
            return;

        tb.LostFocus -= OnLostFocus;
        tb.GotFocus -= OnGotFocus;

        if (args.NewValue != null)
        {
            tb.GotFocus += OnGotFocus;
            tb.LostFocus += OnLostFocus;
        }

        SetPlaceholder(dependencyObject, args.NewValue as string);

        if (!tb.IsFocused)
            ShowPlaceholder(tb);
    }

    private static void OnLostFocus(object sender, RoutedEventArgs routedEventArgs)
    {
        ShowPlaceholder(sender as TextBox);
    }

    private static void OnGotFocus(object sender, RoutedEventArgs routedEventArgs)
    {
        HidePlaceholder(sender as TextBox);
    }

    [AttachedPropertyBrowsableForType(typeof(TextBox))]
    public static void SetPlaceholder(DependencyObject element, string value)
    {
        element.SetValue(PlaceholderProperty, value);
    }

    [AttachedPropertyBrowsableForType(typeof(TextBox))]
    public static string GetPlaceholder(DependencyObject element)
    {
        return (string)element.GetValue(PlaceholderProperty);
    }

    private static void ShowPlaceholder(TextBox textBox)
    {
        if (string.IsNullOrWhiteSpace(textBox.Text))
        {
            textBox.Text = GetPlaceholder(textBox);
        }
    }

    private static void HidePlaceholder(TextBox textBox)
    {
        string placeholderText = GetPlaceholder(textBox);

        if (textBox.Text == placeholderText)
            textBox.Text = string.Empty;
    }
}

Usage:

<TextBox Text="hi" local:TextboxExtensions.Placeholder="Hello there"></TextBox>

How can I write data attributes using Angular?

About access

<ol class="viewer-nav">
    <li *ngFor="let section of sections" 
        [attr.data-sectionvalue]="section.value"
        (click)="get_data($event)">
        {{ section.text }}
    </li>  
</ol>

And

get_data(event) {
   console.log(event.target.dataset.sectionvalue)
}

Iframe positioning

It's because you're missing position:relative; on #contentframe

<div id="contentframe" style="position:relative; top: 160px; left: 0px;">

position:absolute; positions itself against the closest ancestor that has a position that is not static. Since the default is static that is what was causing your issue.

rand() between 0 and 1

This is entirely implementation specific, but it appears that in the C++ environment you're working in, RAND_MAX is equal to INT_MAX.

Because of this, RAND_MAX + 1 exhibits undefined (overflow) behavior, and becomes INT_MIN. While your initial statement was dividing (random # between 0 and INT_MAX)/(INT_MAX) and generating a value 0 <= r < 1, now it's dividing (random # between 0 and INT_MAX)/(INT_MIN), generating a value -1 < r <= 0

In order to generate a random number 1 <= r < 2, you would want

r = ((double) rand() / (RAND_MAX)) + 1

PostgreSQL delete all content

The content of the table/tables in PostgreSQL database can be deleted in several ways.

Deleting table content using sql:

Deleting content of one table:

TRUNCATE table_name;
DELETE FROM table_name;

Deleting content of all named tables:

TRUNCATE table_a, table_b, …, table_z;

Deleting content of named tables and tables that reference to them (I will explain it in more details later in this answer):

TRUNCATE table_a, table_b CASCADE;

Deleting table content using pgAdmin:

Deleting content of one table:

Right click on the table -> Truncate

Deleting content of table and tables that reference to it:

Right click on the table -> Truncate Cascaded

Difference between delete and truncate:

From the documentation:

DELETE deletes rows that satisfy the WHERE clause from the specified table. If the WHERE clause is absent, the effect is to delete all rows in the table. http://www.postgresql.org/docs/9.3/static/sql-delete.html

TRUNCATE is a PostgreSQL extension that provides a faster mechanism to remove all rows from a table. TRUNCATE quickly removes all rows from a set of tables. It has the same effect as an unqualified DELETE on each table, but since it does not actually scan the tables it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables. http://www.postgresql.org/docs/9.1/static/sql-truncate.html

Working with table that is referenced from other table:

When you have database that has more than one table the tables have probably relationship. As an example there are three tables:

create table customers (
customer_id int not null,
name varchar(20),
surname varchar(30),
constraint pk_customer primary key (customer_id)
);

create table orders (
order_id int not null,
number int not null,
customer_id int not null,
constraint pk_order primary key (order_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);

create table loyalty_cards (
card_id int not null,
card_number varchar(10) not null,
customer_id int not null,
constraint pk_card primary key (card_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);

And some prepared data for these tables:

insert into customers values (1, 'John', 'Smith');

insert into orders values 
(10, 1000, 1),
(11, 1009, 1),
(12, 1010, 1);        

insert into loyalty_cards values (100, 'A123456789', 1);

Table orders references table customers and table loyalty_cards references table customers. When you try to TRUNCATE / DELETE FROM the table that is referenced by other table/s (the other table/s has foreign key constraint to the named table) you get an error. To delete content from all three tables you have to name all these tables (the order is not important)

TRUNCATE customers, loyalty_cards, orders;

or just the table that is referenced with CASCADE key word (you can name more tables than just one)

TRUNCATE customers CASCADE;

The same applies for pgAdmin. Right click on customers table and choose Truncate Cascaded.

Function overloading in Python: Missing

As unwind noted, keyword arguments with default values can go a long way.

I'll also state that in my opinion, it goes against the spirit of Python to worry a lot about what types are passed into methods. In Python, I think it's more accepted to use duck typing -- asking what an object can do, rather than what it is.

Thus, if your method may accept a string or a tuple, you might do something like this:

def print_names(names):
    """Takes a space-delimited string or an iterable"""
    try:
        for name in names.split(): # string case
            print name
    except AttributeError:
        for name in names:
            print name

Then you could do either of these:

print_names("Ryan Billy")
print_names(("Ryan", "Billy"))

Although an API like that sometimes indicates a design problem.

Can't start Eclipse - Java was started but returned exit code=13

I had this issue. I installed Java 8 update 25 via Chrome, and therafter attempting to start Eclipse gave the mentioned error.

Uninstalled that update, and Eclipse works again.

Keras model.summary() result - Understanding the # of Parameters

The easiest way to calculate number of neurons in one layer is: Param value / (number of units * 4)

  • Number of units is in predictivemodel.add(Dense(514,...)
  • Param value is Param in model.summary() function

For example in Paul Lo's answer , number of neurons in one layer is 264710 / (514 * 4 ) = 130

Not able to change TextField Border Color

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

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

ReactJS lifecycle method inside a function Component

if you using react 16.8 you can use react Hooks... React Hooks are functions that let you “hook into” React state and lifecycle features from function components... docs

get the value of "onclick" with jQuery?

This works for me

 var link_click = $('#google').get(0).attributes.onclick.nodeValue;
 console.log(link_click);

How do I create a readable diff of two spreadsheets using git diff?

We faced the exact same issue in our co. Our tests output excel workbooks. Binary diff was not an option. So we rolled out our own simple command line tool. Check out the ExcelCompare project. Infact this allows us to automate our tests quite nicely. Patches / Feature requests quite welcome!

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

As Homebrew is my favorite for macOS although it is possible to have apt-get on macOS using Fink.

Pythonic way of checking if a condition holds for any element of a list

Python has a built in any() function for exactly this purpose.

Replace console output in Python

An easy solution is just writing "\r" before the string and not adding a newline; if the string never gets shorter this is sufficient...

sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()

Slightly more sophisticated is a progress bar... this is something I am using:

def startProgress(title):
    global progress_x
    sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41)
    sys.stdout.flush()
    progress_x = 0

def progress(x):
    global progress_x
    x = int(x * 40 // 100)
    sys.stdout.write("#" * (x - progress_x))
    sys.stdout.flush()
    progress_x = x

def endProgress():
    sys.stdout.write("#" * (40 - progress_x) + "]\n")
    sys.stdout.flush()

You call startProgress passing the description of the operation, then progress(x) where x is the percentage and finally endProgress()

How to disable HTML links

Got the fix in css.

td.disabledAnchor a{
       pointer-events: none !important;
       cursor: default;
       color:Gray;
}

Above css when applied to the anchor tag will disable the click event.

For details checkout this link

json_encode function: special characters

you should use this code:

$json = json_encode(array_map('utf8_encode', $arr))

array_map function converts special characters in UTF8 standard

Find records from one table which don't exist in another

There's several different ways of doing this, with varying efficiency, depending on how good your query optimiser is, and the relative size of your two tables:

This is the shortest statement, and may be quickest if your phone book is very short:

SELECT  *
FROM    Call
WHERE   phone_number NOT IN (SELECT phone_number FROM Phone_book)

alternatively (thanks to Alterlife)

SELECT *
FROM   Call
WHERE  NOT EXISTS
  (SELECT *
   FROM   Phone_book
   WHERE  Phone_book.phone_number = Call.phone_number)

or (thanks to WOPR)

SELECT * 
FROM   Call
LEFT OUTER JOIN Phone_Book
  ON (Call.phone_number = Phone_book.phone_number)
  WHERE Phone_book.phone_number IS NULL

(ignoring that, as others have said, it's normally best to select just the columns you want, not '*')

Choosing the default value of an Enum type without having to change values

The default is the first one in the definition. For example:

public enum MyEnum{His,Hers,Mine,Theirs}

Enum.GetValues(typeOf(MyEnum)).GetValue(0);

This will return His

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

You can use the tee command to redirect output:

/usr/bin/mysqldump -u user -pupasswd my-database | \
tee >(gzip -9 -c > /home/user/backup/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz)  | \
gzip> /home/user/backup2/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz 2>&1

see documentation here

How to make a transparent border using CSS?

Using the :before pseudo-element,
CSS3's border-radius,
and some transparency is quite easy:

LIVE DEMO

enter image description here

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

CSS:

.circle, .circle:before{
  position:absolute;
  border-radius:150px;  
}
.circle{  
  width:200px;
  height:200px;
  z-index:0;
  margin:11%;
  padding:40px;
  background: hsla(0, 100%, 100%, 0.6);   
}
.circle:before{
  content:'';
  display:block;
  z-index:-1;  
  width:200px;
  height:200px;

  padding:44px;
  border: 6px solid hsla(0, 100%, 100%, 0.6);
  /* 4px more padding + 6px border = 10 so... */  
  top:-10px;
  left:-10px; 
}

The :before attaches to our .circle another element which you only need to make (ok, block, absolute, etc...) transparent and play with the border opacity.