Programs & Examples On #Visifire

Visifire is a set of data visualization controls

javascript push multidimensional array

Use []:

cookie_value_add.push([productID,itemColorTitle, itemColorPath]);

or

arrayToPush.push([value1, value2, ..., valueN]);

JavaScript seconds to time string with format hh:mm:ss

I'd upvote artem's answer, but I am a new poster. I did expand on his solution, though not what the OP asked for as follows

    t=(new Date()).toString().split(" ");
    timestring = (t[2]+t[1]+' <b>'+t[4]+'</b> '+t[6][1]+t[7][0]+t[8][0]);

To get

04Oct 16:31:28 PDT

This works for me...

But if you are starting with just a time quantity, I use two functions; one to format and pad, and one to calculate:

function sec2hms(timect){

  if(timect=== undefined||timect==0||timect === null){return ''};
  //timect is seconds, NOT milliseconds
  var se=timect % 60; //the remainder after div by 60
  timect = Math.floor(timect/60);
  var mi=timect % 60; //the remainder after div by 60
  timect = Math.floor(timect/60);
  var hr = timect % 24; //the remainder after div by 24
  var dy = Math.floor(timect/24);
  return padify (se, mi, hr, dy);
}

function padify (se, mi, hr, dy){
  hr = hr<10?"0"+hr:hr;
  mi = mi<10?"0"+mi:mi;
  se = se<10?"0"+se:se;
  dy = dy>0?dy+"d ":"";
  return dy+hr+":"+mi+":"+se;
}

How do I import modules or install extensions in PostgreSQL 9.1+?

The extensions available for each version of Postgresql vary. An easy way to check which extensions are available is, as has been already mentioned:

SELECT * FROM pg_available_extensions;

If the extension that you are looking for is available, you can install it using:

CREATE EXTENSION 'extensionName';

or if you want to drop it use:

DROP EXTENSION 'extensionName';

With psql you can additionally check if the extension has been successfully installed using \dx, and find more details about the extension using \dx+ extensioName. It returns additional information about the extension, like which packages are used with it.

If the extension is not available in your Postgres version, then you need to download the necessary binary files and libraries and locate it them at /usr/share/conrib

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

To complete the answer from Sotorios Delimanolis.

It's true that ResponseEntity gives you more flexibility but in most cases you won't need it and you'll end up with these ResponseEntity everywhere in your controller thus making it difficult to read and understand.

If you want to handle special cases like errors (Not Found, Conflict, etc.), you can add a HandlerExceptionResolver to your Spring configuration. So in your code, you just throw a specific exception (NotFoundException for instance) and decide what to do in your Handler (setting the HTTP status to 404), making the Controller code more clear.

How to output only captured groups with sed?

I believe the pattern given in the question was by way of example only, and the goal was to match any pattern.

If you have a sed with the GNU extension allowing insertion of a newline in the pattern space, one suggestion is:

> set string = "This is a sample 123 text and some 987 numbers"
>
> set pattern = "[0-9][0-9]*"
> echo $string | sed "s/$pattern/\n&\n/g" | sed -n "/$pattern/p"
123
987
> set pattern = "[a-z][a-z]*"
> echo $string | sed "s/$pattern/\n&\n/g" | sed -n "/$pattern/p"
his
is
a
sample
text
and
some
numbers

These examples are with tcsh (yes, I know its the wrong shell) with CYGWIN. (Edit: For bash, remove set, and the spaces around =.)

How can I see the entire HTTP request that's being sent by my Python application?

The verbose configuration option might allow you to see what you want. There is an example in the documentation.

NOTE: Read the comments below: The verbose config options doesn't seem to be available anymore.

When is JavaScript synchronous?

JavaScript is single-threaded, and all the time you work on a normal synchronous code-flow execution.

Good examples of the asynchronous behavior that JavaScript can have are events (user interaction, Ajax request results, etc) and timers, basically actions that might happen at any time.

I would recommend you to give a look to the following article:

That article will help you to understand the single-threaded nature of JavaScript and how timers work internally and how asynchronous JavaScript execution works.

async

Convert HTML Character Back to Text Using Java Standard Library

I'm not aware of any way to do it using the standard library. But I do know and use this class that deals with html entities.

"HTMLEntities is an Open Source Java class that contains a collection of static methods (htmlentities, unhtmlentities, ...) to convert special and extended characters into HTML entitities and vice versa."

http://www.tecnick.com/public/code/cp_dpage.php?aiocp_dp=htmlentities

Converting String to Double in Android

try this:

double d= Double.parseDouble(yourString);

Selecting empty text input using jQuery

You could also do it by defining your own selector:

$.extend($.expr[':'],{
    textboxEmpty: function(el){
        return $(el).val() === "";
    }
});

And then access them like this:

alert($(':text:textboxEmpty').length); //alerts the number of text boxes in your selection

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

After some serious searching it seems i've found the answer to my question:

from: http://www.brunildo.org/test/Overflowxy2.html

In Gecko, Safari, Opera, ‘visible’ becomes ‘auto’ also when combined with ‘hidden’ (in other words: ‘visible’ becomes ‘auto’ when combined with anything else different from ‘visible’). Gecko 1.8, Safari 3, Opera 9.5 are pretty consistent among them.

also the W3C spec says:

The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as their specified values, except that some combinations with ‘visible’ are not possible: if one is specified as ‘visible’ and the other is ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if ‘overflow-y’ is the same; otherwise it is the pair of computed values of ‘overflow-x’ and ‘overflow-y’.

Short Version:

If you are using visible for either overflow-x or overflow-y and something other than visible for the other, the visible value is interpreted as auto.

Leaflet changing Marker color

Write a function which, given a color (or any other characteristics), returns an SVG representation of the desired icon. Then, when creating the marker, reference this function with the appropriate parameter(s).

Convert Set to List without creating new List

I would do :

Map<String, Collection> mainMap = new HashMap<String, Collection>();

for(int i=0; i<something.size(); i++){
  Set set = getSet(...); //return different result each time
  mainMap.put(differentKeyName,set);
}

How do I revert my changes to a git submodule?

This works with our libraries running GIT v1.7.1, where we have a DEV package repo and LIVE package repo. The repositories themselves are nothing but a shell to package the assets for a project. all submodules.

The LIVE is never updated intentionally, however cache files or accidents can occur, leaving the repo dirty. New submodules added to the DEV must be initialized within LIVE as well.

Package Repository in DEV

Here we want to pull all upstream changes that we are not yet aware of, then we will update our package repository.

# Recursively reset to the last HEAD
git submodule foreach --recursive git reset --hard

# Recursively cleanup all files and directories
git submodule foreach --recursive git clean -fd

# Recursively pull the upstream master
git submodule foreach --recursive git pull origin master

# Add / Commit / Push all updates to the package repo
git add .
git commit -m "Updates submodules"
git push   

Package Repository in LIVE

Here we want to pull the changes that are committed to the DEV repository, but not unknown upstream changes.

# Pull changes
git pull

# Pull status (this is required for the submodule update to work)
git status

# Initialize / Update 
git submodule update --init --recursive

How do I rotate text in css?

Using writing-mode and transform.

.rotate {
     writing-mode: vertical-lr;
    -webkit-transform: rotate(-180deg);
    -moz-transform: rotate(-180deg);
}


<span class="rotate">Hello</span>

Iterating Over Dictionary Key Values Corresponding to List in Python

List comprehension can shorten things...

win_percentages = [m**2.0 / (m**2.0 + n**2.0) * 100 for m, n in [a[i] for i in NL_East]]

Where is the documentation for the values() method of Enum?

You can't see this method in javadoc because it's added by the compiler.

Documented in three places :

The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.

  • Enum.valueOf class
    (The special implicit values method is mentioned in description of valueOf method)

All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.

The values function simply list all values of the enumeration.

How to merge 2 List<T> and removing duplicate values from it in C#

Have you had a look at Enumerable.Union

This method excludes duplicates from the return set. This is different behavior to the Concat method, which returns all the elements in the input sequences including duplicates.

List<int> list1 = new List<int> { 1, 12, 12, 5};
List<int> list2 = new List<int> { 12, 5, 7, 9, 1 };
List<int> ulist = list1.Union(list2).ToList();

// ulist output : 1, 12, 5, 7, 9

Python TypeError must be str not int

Python comes with numerous ways of formatting strings:

New style .format(), which supports a rich formatting mini-language:

>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!

Old style % format specifier:

>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!

In Py 3.6 using the new f"" format strings:

>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!

Or using print()s default separator:

>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!

And least effectively, construct a new string by casting it to a str() and concatenating:

>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!

Or join()ing it:

>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!

How to kill a child process after a given timeout in Bash?

Here's an attempt which tries to avoid killing a process after it has already exited, which reduces the chance of killing another process with the same process ID (although it's probably impossible to avoid this kind of error completely).

run_with_timeout ()
{
  t=$1
  shift

  echo "running \"$*\" with timeout $t"

  (
  # first, run process in background
  (exec sh -c "$*") &
  pid=$!
  echo $pid

  # the timeout shell
  (sleep $t ; echo timeout) &
  waiter=$!
  echo $waiter

  # finally, allow process to end naturally
  wait $pid
  echo $?
  ) \
  | (read pid
     read waiter

     if test $waiter != timeout ; then
       read status
     else
       status=timeout
     fi

     # if we timed out, kill the process
     if test $status = timeout ; then
       kill $pid
       exit 99
     else
       # if the program exited normally, kill the waiting shell
       kill $waiter
       exit $status
     fi
  )
}

Use like run_with_timeout 3 sleep 10000, which runs sleep 10000 but ends it after 3 seconds.

This is like other answers which use a background timeout process to kill the child process after a delay. I think this is almost the same as Dan's extended answer (https://stackoverflow.com/a/5161274/1351983), except the timeout shell will not be killed if it has already ended.

After this program has ended, there will still be a few lingering "sleep" processes running, but they should be harmless.

This may be a better solution than my other answer because it does not use the non-portable shell feature read -t and does not use pgrep.

How to check a not-defined variable in JavaScript

In JavaScript, null is an object. There's another value for things that don't exist, undefined. The DOM returns null for almost all cases where it fails to find some structure in the document, but in JavaScript itself undefined is the value used.

Second, no, there is not a direct equivalent. If you really want to check for specifically for null, do:

if (yourvar === null) // Does not execute if yourvar is `undefined`

If you want to check if a variable exists, that can only be done with try/catch, since typeof will treat an undeclared variable and a variable declared with the value of undefined as equivalent.

But, to check if a variable is declared and is not undefined:

if (yourvar !== undefined) // Any scope

Previously, it was necessary to use the typeof operator to check for undefined safely, because it was possible to reassign undefined just like a variable. The old way looked like this:

if (typeof yourvar !== 'undefined') // Any scope

The issue of undefined being re-assignable was fixed in ECMAScript 5, which was released in 2009. You can now safely use === and !== to test for undefined without using typeof as undefined has been read-only for some time.

If you want to know if a member exists independent but don't care what its value is:

if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance

If you want to to know whether a variable is truthy:

if (yourvar)

Source

Generate a sequence of numbers in Python

In python 3.1 you can produce a list in a way

     lst=list(range(100))
     for i in range(100)
        print (lst[i],',',end='')

In python 2.7 you can do it as

     lst=range(100)
     for i in range(100)
        print lst[i]+',' 

Laravel assets url

You have to put all your assets in app/public folder, and to access them from your views you can use asset() helper method.

Ex. you can retrieve assets/images/image.png in your view as following:

<img src="{{asset('assets/images/image.png')}}">

Hide strange unwanted Xcode logs

This solution has been working for me:

  1. Run the app in the simulator
  2. Open the system log (? + /)

This will dump out all of the debug data and also your NSLogs.

To filter just your NSLog statements:

  1. Prefix each with a symbol, for example: NSLog(@"^ Test Log")
  2. Filter the results using the search box on the top right, "^" in the case above

This is what you should get:

Screenshot of console

Create new XML file and write data to it?

With FluidXML you can generate and store an XML document very easily.

$doc = fluidxml();

$doc->add('Album', true)
        ->add('Track', 'Track Title');

$doc->save('album.xml');

Loading a document from a file is equally simple.

$doc = fluidify('album.xml');

$doc->query('//Track')
        ->attr('id', 123);

https://github.com/servo-php/fluidxml

List attributes of an object

Please see the following Python shell scripting execution in sequence, it will give the solution from creation of class to extracting the field names of instances.

>>> class Details:
...       def __init__(self,name,age):
...           self.name=name
...           self.age =age
...       def show_details(self):
...           if self.name:
...              print "Name : ",self.name
...           else:
...              print "Name : ","_"
...           if self.age:
...              if self.age>0:
...                 print "Age  : ",self.age
...              else:
...                 print "Age can't be -ve"
...           else:
...              print "Age  : ","_"
... 
>>> my_details = Details("Rishikesh",24)
>>> 
>>> print my_details
<__main__.Details instance at 0x10e2e77e8>
>>> 
>>> print my_details.name
Rishikesh
>>> print my_details.age
24
>>> 
>>> my_details.show_details()
Name :  Rishikesh
Age  :  24
>>> 
>>> person1 = Details("",34)
>>> person1.name
''
>>> person1.age
34
>>> person1.show_details
<bound method Details.show_details of <__main__.Details instance at 0x10e2e7758>>
>>> 
>>> person1.show_details()
Name :  _
Age  :  34
>>>
>>> person2 = Details("Rob Pike",0)
>>> person2.name
'Rob Pike'
>>> 
>>> person2.age
0
>>> 
>>> person2.show_details()
Name :  Rob Pike
Age  :  _
>>> 
>>> person3 = Details("Rob Pike",-45)
>>> 
>>> person3.name
'Rob Pike'
>>> 
>>> person3.age
-45
>>> 
>>> person3.show_details()
Name :  Rob Pike
Age can't be -ve
>>>
>>> person3.__dict__
{'age': -45, 'name': 'Rob Pike'}
>>>
>>> person3.__dict__.keys()
['age', 'name']
>>>
>>> person3.__dict__.values()
[-45, 'Rob Pike']
>>>

MySQL and GROUP_CONCAT() maximum length

Include this setting in xampp my.ini configuration file:

[mysqld]
group_concat_max_len = 1000000

Then restart xampp mysql

How to call a function, PostgreSQL

you declare your function as returning boolean, but it never returns anything.

ASP.NET postback with JavaScript

If anyone's having trouble with this (as I was), you can get the postback code for a button by adding the UseSubmitBehavior="false" attribute to it. If you examine the rendered source of the button, you'll see the exact javascript you need to execute. In my case it was using the name of the button rather than the id.

Material effect on button with background color

I tried this:

android:backgroundTint:"@color/mycolor"

instead of changing background property. This does not remove the material effect.

How to Parse a JSON Object In Android

In the end I solved it by using JSONObject.get rather than JSONObject.getString and then cast test to a String.

private void saveData(String result) {
    try {
        JSONObject json= (JSONObject) new JSONTokener(result).nextValue();
        JSONObject json2 = json.getJSONObject("results");
        test = (String) json2.get("name");
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Markdown `native` text alignment

It's hacky but if you're using GFM or some other MD syntax which supports building tables with pipes you can use the column alignment features:

|| <!-- empty table header -->
|:--:| <!-- table header/body separator with center formatting -->
| I'm centered! | <!-- cell gets column's alignment -->

This works in marked.

How to specify 64 bit integers in c

Use stdint.h for specific sizes of integer data types, and also use appropriate suffixes for integer literal constants, e.g.:

#include <stdint.h>

int64_t i2 = 0x0000444400004444LL;

How can I convert a string with dot and comma into a float in Python

Here's a simple way I wrote up for you. :)

>>> number = '123,456,789.908'.replace(',', '') # '123456789.908'
>>> float(number)
123456789.908

Printing out a number in assembly language?

DOS Print 32 bit value stored in EAX with hexadecimal output (for 80386+)
(on 64 bit OS use DOSBOX)

.code
    mov ax,@DATA        ; get the address of the data segment
    mov ds,ax           ; store the address in the data segment register
;-----------------------
    mov eax,0FFFFFFFFh  ; 32 bit value (0 - FFFFFFFF) for example
;-----------------------
; convert the value in EAX to hexadecimal ASCIIs
;-----------------------
    mov di,OFFSET ASCII ; get the offset address
    mov cl,8            ; number of ASCII
P1: rol eax,4           ; 1 Nibble (start with highest byte)
    mov bl,al
    and bl,0Fh          ; only low-Nibble
    add bl,30h          ; convert to ASCII
    cmp bl,39h          ; above 9?
    jna short P2
    add bl,7            ; "A" to "F"
P2: mov [di],bl         ; store ASCII in buffer
    inc di              ; increase target address
    dec cl              ; decrease loop counter
    jnz P1              ; jump if cl is not equal 0 (zeroflag is not set)
;-----------------------
; Print string
;-----------------------
    mov dx,OFFSET ASCII ; DOS 1+ WRITE STRING TO STANDARD OUTPUT
    mov ah,9            ; DS:DX->'$'-terminated string
    int 21h             ; maybe redirected under DOS 2+ for output to file
                        ; (using pipe character">") or output to printer

  ; terminate program...

.data
ASCII DB "00000000",0Dh,0Ah,"$" ; buffer for ASCII string

Alternative string output directly to the videobuffer without using software interupts:

;-----------------------
; Print string
;-----------------------
    mov ax,0B800h       ; segment address of textmode video buffer
    mov es,ax           ; store address in extra segment register

    mov si,OFFSET ASCII ; get the offset address of the string

; using a fixed target address for example (screen page 0)
; Position`on screen = (Line_number*80*2) + (Row_number*2)

    mov di,(10*80*2)+(10*2)
    mov cl,8            ; number of ASCII
    cld                 ; clear direction flag

P3: lodsb  ; get the ASCII from the address in DS:SI + increase si
    stosb  ; write ASCII directly to the screen using ES:DI + increase di
    inc di ; step over attribut byte
    dec cl ; decrease counter
    jnz P3 ; repeat (print only 8 ASCII, not used bytes are: 0Dh,0Ah,"$")

; Hint: this directly output to the screen do not touch or move the cursor
; but feel free to modify..

Select a row from html table and send values onclick of a button

This below code will give selected row, you can parse the values from it and send to the AJAX call.

$(".selected").click(function () {
var row = $(this).parent().parent().parent().html();            
});

Calling a phone number in swift

I am using this method in my application and it's working fine. I hope this may help you too.

func makeCall(phone: String) {
    let formatedNumber = phone.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
    let phoneUrl = "tel://\(formatedNumber)"
    let url:NSURL = NSURL(string: phoneUrl)!
    UIApplication.sharedApplication().openURL(url)
}

Very simple log4j2 XML configuration file using Console and File appender

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <File name="MyFile" fileName="all.log" immediateFlush="false" append="false">
            <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="Console" />
            <AppenderRef ref="MyFile"/>
        </Root>
    </Loggers>
</Configuration>

Notes:

  • Put the following content in your configuration file.
  • Name the configuration file log4j2.xml
  • Put the log4j2.xml in a folder which is in the class-path (i.e. your source folder "src")
  • Use Logger logger = LogManager.getLogger(); to initialize your logger
  • I did set the immediateFlush="false" since this is better for SSD lifetime. If you need the log right away in your log-file remove the parameter or set it to true

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Use content="IE=edge,chrome=1"   Skip other X-UA-Compatible modes

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
                                   -------------------------- 
  • No compatibility icon
    The IE9 Address bar does not show up the Compatibility View button
    and the page does not also show up a jumble of out-of-place menus, images, and text boxes.

  • Features
    This meta tag is required to enable javascript::JSON.parse() on IE8
    (even when <!DOCTYPE html> is present)

  • Correctness
    Rendering/Execution of modern HTML/CSS/JavaScript is more valid (nicer).

  • Performance
    The Trident rendering engine should run faster in its edge mode.


Usage

In your HTML

<!DOCTYPE html> 
<html> 
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

Or better in the configuration of your web server:
(see also the RiaD's answer)

  • Apache as proposed by pixeline

    <IfModule mod_setenvif.c>
      <IfModule mod_headers.c>
        BrowserMatch MSIE ie
        Header set X-UA-Compatible "IE=Edge,chrome=1" env=ie
      </IfModule>
    </IfModule>
    <IfModule mod_headers.c>
      Header append Vary User-Agent
    </IfModule>
    
  • Nginx as proposed by Stef Pause

    server {
      #...
      add_header X-UA-Compatible "IE=Edge,chrome=1";
    }
    
  • Varnish proxy as proposed by Lucas Riutzel

    sub vcl_deliver {
      if( resp.http.Content-Type ~ "text/html" ) {
        set resp.http.X-UA-Compatible = "IE=edge,chrome=1";
      }
    }
    
  • IIS (since v7)

    <configuration>
      <system.webServer>
         <httpProtocol>
            <customHeaders>
               <add name="X-UA-Compatible" value="IE=edge,chrome=1" />
            </customHeaders>
         </httpProtocol>
      </system.webServer>
    </configuration>
    

Microsoft recommends Edge mode since IE11

As noticed by Lynda (see comments), the Compatibility changes in IE11 recommends Edge mode:

Starting with IE11, edge mode is the preferred document mode; it represents the highest support for modern standards available to the browser.

But the position of Microsoft was not clear. Another MSDN page did not recommend Edge mode:

Because Edge mode forces all pages to be opened in standards mode, regardless of the version of Internet Explorer, you might be tempted to use this for all pages viewed with Internet Explorer. Don't do this, as the X-UA-Compatible header is only supported starting with Windows Internet Explorer 8.

Instead, Microsoft recommended using <!DOCTYPE html>:

If you want all supported versions of Internet Explorer to open your pages in standards mode, use the HTML5 document type declaration [...]

As Ricardo explains (in the comments below) any DOCTYPE (HTML4, XHTML1...) can be used to trigger Standards Mode, not only HTML5's DOCTYPE. The important thing is to always have a DOCTYPE in the page.

Clara Onager has even noticed in an older version of Specifying legacy document modes:

Edge mode is intended for testing purposes only; do not use it in a production environment.

It is so confusing that Usman Y thought Clara Onager was speaking about:

The [...] example is provided for illustrative purposes only; don't use it in a production environment.

<meta http-equiv="X-UA-Compatible" content="IE=7,9,10" >

Well... In the rest of this answer I give more explanations why using content="IE=edge,chrome=1" is a good practice in production.


History

For many years (2000 to 2008), IE market share was more than 80%. And IE v6 was considered as a de facto standard (80% to 97% market share in 2003, 2004, 2005 and 2006 for IE6 only, more market share with all IE versions).

As IE6 was not respecting Web standards, developers had to test their website using IE6. That situation was great for Microsoft (MS) as web developers had to buy MS products (e.g. IE cannot be used without buying Windows), and it was more profit-making to stay non-compliant (i.e. Microsoft wanted to become the standard excluding other companies).

Therefore many many sites were IE6 compliant only, and as IE was not compliant with web standard, all these web sites was not well rendered on standards compliant browsers. Even worse, many sites required only IE.

However, at this time, Mozilla started Firefox development respecting as much as possible all the web standards (other browser were implemented to render pages as done by IE6). As more and more web developers wanted to use the new web standards features, more and more websites were more supported by Firefox than IE.

When IE market sharing was decreasing, MS realized staying standard incompatible was not a good idea. Therefore MS started to release new IE version (IE8/IE9/IE10) respecting more and more the web standards.


The web-incompatible issue

But the issue is all the websites designed for IE6: Microsoft could not release new IE versions incompatible with these old IE6-designed websites. Instead of deducing the IE version a website has been designed, MS requested developers to add extra data (X-UA-Compatible) in their pages.

IE6 is still used in 2016

Nowadays, IE6 is still used (0.7% in 2016) (4.5% in January 2014), and some internet websites are still IE6-only-compliant. Some intranet website/applications are tested using IE6. Some intranet website are 100% functional only on IE6. These companies/departments prefer to postpone the migration cost: other priorities, nobody no longer knows how the website/application has been implemented, the owner of the legacy website/application went bankrupt...

China represents 50% of IE6 usage in 2013, but it may change in the next years as Chinese Linux distribution is being broadcast.

Be confident with your web skills

If you (try to) respect web standard, you can simply always use http-equiv="X-UA-Compatible" content="IE=edge,chrome=1". To keep compatibility with old browsers, just avoid using latest web features: use the subset supported by the oldest browser you want to support. Or If you want to go further, you may adopt concepts as Graceful degradation, Progressive enhancement and Unobtrusive JavaScript. (You may also be pleased to read What should a web developer consider?.)

Do do not care about the best IE version rendering: this is not your job as browsers have to be compliant with web standards. If your site is standard compliant and use moderately latest features, therefore browsers have to be compliant with your website.

Moreover, as there are many campaigns to kill IE6 (IE6 no more, MS campaign), nowadays you may avoid wasting time with IE testing!

Personal IE6 experience

In 2009-2012, I worked for a company using IE6 as the official single browser allowed. I had to implement an intranet website for IE6 only. I decided to respect web standard but using the IE6-capable subset (HTML/CSS/JS).

It was hard, but when the company switched to IE8, the website was still well rendered because I had used Firefox and firebug to check the web-standard compatibility ;)

UTF-8 byte[] to String

I use this way

String strIn = new String(_bytes, 0, numBytes);

Reset textbox value in javascript

this is might be a possible solution

void 0 != document.getElementById("ad") &&       (document.getElementById("ad").onclick =function(){
 var a = $("#client_id").val();
 var b = $("#contact").val();
 var c = $("#message").val();
 var Qdata = { client_id: a, contact:b, message:c }
 var respo='';
     $("#message").html('');

return $.ajax({

    url: applicationPath ,
    type: "POST",
    data: Qdata,
    success: function(e) {
         $("#mcg").html("msg send successfully");

    }

})

});

Chrome blocks different origin requests

Direct Javascript calls between frames and/or windows are only allowed if they conform to the same-origin policy. If your window and iframe share a common parent domain you can set document.domain to "domain lower") one or both such that they can communicate. Otherwise you'll need to look into something like the postMessage() API.

Output to the same line overwriting previous output?

You can just add '\r' at the end of the string plus a comma at the end of print function. For example:

print(os.path.getsize(file_name)/1024+'KB / '+size+' KB downloaded!\r'),

Counting the number of option tags in a select tag in jQuery

Ok, i had a few problems because i was inside a

$('.my-dropdown').live('click', function(){  
});

I had multiples inside my page that's why i used a class.

My drop down was filled automatically by a ajax request when i clicked it, so i only had the element $(this)

so...

I had to do:

$('.my-dropdown').live('click', function(){
  total_tems = $(this).find('option').length;
});

How to change the status bar color in Android?

Just create a new theme in res/values/styles.xml where you change the "colorPrimaryDark" which is the color of the status bar:

<style name="AppTheme.GrayStatusBar" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimaryDark">@color/colorGray</item>
</style>

And modify the activity theme in AndroidManifest.xml to the one you want, on the next activity you can change the color back to the original one by selecting the original theme:

<activity
    android:name=".LoginActivity"
    android:theme="@style/AppTheme.GrayStatusBar" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

This is how your res/values/colors.xml should look like:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#c6d6f0</color>
    <color name="colorGray">#757575</color>
</resources>

How to get the CUDA version?

If you are running on linux:

dpkg -l | grep cuda

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

INSTALL_FAILED_NO_MATCHING_ABIS is when you are trying to install an app that has native libraries and it doesn't have a native library for your cpu architecture. For example if you compiled an app for armv7 and are trying to install it on an emulator that uses the Intel architecture instead it will not work.

how to change php version in htaccess in server

Try this to switch to php4:

AddHandler application/x-httpd-php4 .php

Upd. Looks like I didn't understand your question correctly. This will not help if you have only php 4 on your server.

Fragment onResume() & onPause() is not called on backstack

getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            List<Fragment> fragments = getFragmentManager().getFragments();
            if (fragments.size() > 0 && fragments.get(fragments.size() - 1) instanceof YoureFragment){
                //todo if fragment visible
            } else {
                //todo if fragment invisible
            }

        }
    });

but be careful if more than one fragment visible

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

Calculating Covariance with Python and Numpy

Thanks to unutbu for the explanation. By default numpy.cov calculates the sample covariance. To obtain the population covariance you can specify normalisation by the total N samples like this:

Covariance = numpy.cov(a, b, bias=True)[0][1]
print(Covariance)

or like this:

Covariance = numpy.cov(a, b, ddof=0)[0][1]
print(Covariance)

Convert a float64 to an int in Go

package main
import "fmt"
func main() {
  var x float64 = 5.7
  var y int = int(x)
  fmt.Println(y)  // outputs "5"
}

How do I load an org.w3c.dom.Document from XML in a string?

To manipulate XML in Java, I always tend to use the Transformer API:

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;

public static Document loadXMLFrom(String xml) throws TransformerException {
    Source source = new StreamSource(new StringReader(xml));
    DOMResult result = new DOMResult();
    TransformerFactory.newInstance().newTransformer().transform(source , result);
    return (Document) result.getNode();
}   

How to remove any URL within a string in Python

The following regular expression in Python works well for detecting URL(s) in the text:

source_text = '''
text1
text2
http://url.com/bla1/blah1/
text3
text4
http://url.com/bla2/blah2/
text5
text6    '''

import re
url_reg  = r'[a-z]*[:.]+\S+'
result   = re.sub(url_reg, '', source_text)
print(result)

Output:

text1
text2

text3
text4

text5
text6

Making a mocked method return an argument that was passed to it

With Java 8, Steve's answer can become

public void testMyFunction() throws Exception {
    Application mock = mock(Application.class);
    when(mock.myFunction(anyString())).thenAnswer(
    invocation -> {
        Object[] args = invocation.getArguments();
        return args[0];
    });

    assertEquals("someString", mock.myFunction("someString"));
    assertEquals("anotherString", mock.myFunction("anotherString"));
}

EDIT: Even shorter:

public void testMyFunction() throws Exception {
    Application mock = mock(Application.class);
    when(mock.myFunction(anyString())).thenAnswer(
        invocation -> invocation.getArgument(0));

    assertEquals("someString", mock.myFunction("someString"));
    assertEquals("anotherString", mock.myFunction("anotherString"));
}

Remove white space above and below large text in an inline-block element

span::before,
span::after {
    content: '';
    display: block;
    height: 0;
    width: 0;
}

span::before{
    margin-top:-6px;
}

span::after{
    margin-bottom:-8px;
}

Find out the margin-top and margin-bottom negative margins with this tool: http://text-crop.eightshapes.com/

The tool also gives you SCSS, LESS and Stylus examples. You can read more about it here: https://medium.com/eightshapes-llc/cropping-away-negative-impacts-of-line-height-84d744e016ce

How to render a DateTime in a specific format in ASP.NET MVC 3?

works for me

<%=Model.MyDateTime.ToString("dd-MMM-yyyy")%>

How do I put my website's logo to be the icon image in browser tabs?

  1. ADD THIS
**<HEAD>**

  < link rel="icon" href="directory/image.png">

Then run and enjoy it

What's the function like sum() but for multiplication? product()?

There isn't one built in, but it's simple to roll your own, as demonstrated here:

import operator
def prod(factors):
    return reduce(operator.mul, factors, 1)

See answers to this question:

Which Python module is suitable for data manipulation in a list?

List distinct values in a vector in R

another way would be to use dplyr package:

x = c(1,1,2,3,4,4,4)
dplyr::distinct(as.data.frame(x))

How to print a date in a regular format?

This is shorter:

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'

internet explorer 10 - how to apply grayscale filter?

Use this jQuery plugin https://gianlucaguarini.github.io/jQuery.BlackAndWhite/

That seems to be the only one cross-browser solution. Plus it has a nice fade in and fade out effect.

$('.bwWrapper').BlackAndWhite({
    hoverEffect : true, // default true
    // set the path to BnWWorker.js for a superfast implementation
    webworkerPath : false,
    // to invert the hover effect
    invertHoverEffect: false,
    // this option works only on the modern browsers ( on IE lower than 9 it remains always 1)
    intensity:1,
    speed: { //this property could also be just speed: value for both fadeIn and fadeOut
        fadeIn: 200, // 200ms for fadeIn animations
        fadeOut: 800 // 800ms for fadeOut animations
    },
    onImageReady:function(img) {
        // this callback gets executed anytime an image is converted
    }
});

Regex not operator

Not quite, although generally you can usually use some workaround on one of the forms

  • [^abc], which is character by character not a or b or c,
  • or negative lookahead: a(?!b), which is a not followed by b
  • or negative lookbehind: (?<!a)b, which is b not preceeded by a

Shell script to set environment variables

I cannot solve it with source ./myscript.sh. It says the source not found error.
Failed also when using . ./myscript.sh. It gives can't open myscript.sh.

So my option is put it in a text file to be called in the next script.

#!/bin/sh
echo "Perform Operation in su mode"
echo "ARCH=arm" >> environment.txt
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export "CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?" >> environment.txt
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...

Tnen call it whenever is needed:

while read -r line; do
    line=$(sed -e 's/[[:space:]]*$//' <<<${line})
    var=`echo $line | cut -d '=' -f1`; test=$(echo $var)
    if [ -z "$(test)" ];then eval export "$line";fi
done <environment.txt

What are the differences between B trees and B+ trees?

The image below helps show the differences between B+ trees and B trees.

Advantages of B+ trees:

  • Because B+ trees don't have data associated with interior nodes, more keys can fit on a page of memory. Therefore, it will require fewer cache misses in order to access data that is on a leaf node.
  • The leaf nodes of B+ trees are linked, so doing a full scan of all objects in a tree requires just one linear pass through all the leaf nodes. A B tree, on the other hand, would require a traversal of every level in the tree. This full-tree traversal will likely involve more cache misses than the linear traversal of B+ leaves.

Advantage of B trees:

  • Because B trees contain data with each key, frequently accessed nodes can lie closer to the root, and therefore can be accessed more quickly.

B and B+ tree

insert data into database with codeigniter

Based on what I see here, you have used lowercase fieldnames in your $data array, and uppercase fieldnames in your database table.

Delete all records in a table of MYSQL in phpMyAdmin

  • Visit phpmyadmin
  • Select your database and click on structure
  • In front of your table, you can see Empty, click on it to clear all the entries from the selected table.

demo-database-structure

Or you can do the same using sql query:

Click on SQL present along side Structure

TRUNCATE tablename; //offers better performance, but used only when all entries need to be cleared
or
DELETE FROM tablename; //returns the number of rows deleted

Refer to DELETE and TRUNCATE for detailed documentaion

get the value of DisplayName attribute

First off, you need to get a MemberInfo object that represents that property. You will need to do some form of reflection:

MemberInfo property = typeof(Class1).GetProperty("Name");

(I'm using "old-style" reflection, but you can also use an expression tree if you have access to the type at compile-time)

Then you can fetch the attribute and obtain the value of the DisplayName property:

var attribute = property.GetCustomAttributes(typeof(DisplayNameAttribute), true)
      .Cast<DisplayNameAttribute>().Single();
string displayName = attribute.DisplayName;

() parentheses are required typo error

SQL Developer is returning only the date, not the time. How do I fix this?

This will get you the hours, minutes and second. hey presto.

select
  to_char(CREATION_TIME,'RRRR') year, 
  to_char(CREATION_TIME,'MM') MONTH, 
  to_char(CREATION_TIME,'DD') DAY, 
  to_char(CREATION_TIME,'HH:MM:SS') TIME,
  sum(bytes) Bytes 
from 
  v$datafile 
group by 
  to_char(CREATION_TIME,'RRRR'), 
  to_char(CREATION_TIME,'MM'), 
  to_char(CREATION_TIME,'DD'), 
  to_char(CREATION_TIME,'HH:MM:SS') 
 ORDER BY 1, 2; 

Proxy with urllib2

You have to install a ProxyHandler

urllib2.install_opener(
    urllib2.build_opener(
        urllib2.ProxyHandler({'http': '127.0.0.1'})
    )
)
urllib2.urlopen('http://www.google.com')

What is the MySQL JDBC driver connection string?

The method Class.forName() is used to register the JDBC driver. A connection string is used to retrieve the connection to the database.

The way to retrieve the connection to the database is shown below. Ideally since you do not want to create multiple connections to the database, limit the connections to one and re-use the same connection. Therefore use the singleton pattern here when handling connections to the database.

Shown Below shows a connection string with the retrieval of the connection:

public class Database {
   
    private String URL = "jdbc:mysql://localhost:3306/your_db_name"; //database url
    private String username = ""; //database username
    private String password = ""; //database password
    private static Database theDatabase = new Database(); 
    private Connection theConnection;
    
    private Database(){
        try{
              Class.forName("com.mysql.jdbc.Driver"); //setting classname of JDBC Driver
              this.theConnection = DriverManager.getConnection(URL, username, password);
        } catch(Exception ex){
            System.out.println("Error Connecting to Database: "+ex);
        }
    }

    public static Database getDatabaseInstance(){
        return theDatabase;
    }
    
    public Connection getTheConnectionObject(){
        return theConnection;
    }
}

How to display Woocommerce Category image?

get_woocommerce_term_meta is depricated since Woo 3.6.0.

so change

$thumbnail_id = get_woocommerce_term_meta($value->term_id, 'thumbnail_id', true );

into: ($value->term_id should be woo category id)

get_term_meta($value->term_id, 'thumbnail_id', true)

see docs for details: https://docs.woocommerce.com/wc-apidocs/function-get_woocommerce_term_meta.html

Which icon sizes should my Windows application's icon include?

Not 96x96, use 64x64 instead. I usually use:

  • 16 - status/titlebar button
  • 32 - desktop icon
  • 48 - folder view
  • 64/128 - Additional sizes

256 works as well on XP, however, old resource compilers sometimes complained about "out of memory" errors.

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

SET @sql = 
CONCAT( 'INSERT INTO <table_name> (', 
    (
        SELECT GROUP_CONCAT( CONCAT('`',COLUMN_NAME,'`') ) 
            FROM information_schema.columns 
            WHERE table_schema = <database_name>
                AND table_name = <table_name>
                AND column_name NOT IN ('id')
    ), ') SELECT ', 
    ( 
        SELECT GROUP_CONCAT(CONCAT('`',COLUMN_NAME,'`')) 
        FROM information_schema.columns 
        WHERE table_schema = <database_name>
            AND table_name = <table_source_name>
            AND column_name NOT IN ('id')  
    ),' from <table_source_name> WHERE <testcolumn> = <testvalue>' );  

PREPARE stmt1 FROM @sql; 
execute stmt1;

Of course replace <> values with real values, and watch your quotes.

Illegal mix of collations MySQL Error

My user account did not have the permissions to alter the database and table, as suggested in this solution.

If, like me, you don't care about the character collation (you are using the '=' operator), you can apply the reverse fix. Run this before your SELECT:

SET collation_connection = 'latin1_swedish_ci';

Launching a website via windows commandline

Ok, The Windows 10 BatchFile is done works just like I had hoped. First press the windows key and R. Type mmc and Enter. In File Add SnapIn>Got to a specific Website and add it to the list. Press OK in the tab, and on the left side console root menu double click your site. Once it opens Add it to favourites. That should place it in C:\Users\user\AppData\Roaming\Microsoft\StartMenu\Programs\Windows Administrative Tools. I made a shortcut of this to a folder on the desktop. Right click the Shortcut and view the properties. In the Shortcut tab of the Properties click advanced and check the Run as Administrator. The Start in Location is also on the Shortcuts Tab you can add that to your batch file if you need. The Batch I made is as follows

@echo off
title Manage SiteEnviro
color 0a
:Clock
cls
echo Date:%date% Time:%time%
pause
cls
c:\WINDOWS\System32\netstat
c:\WINDOWS\System32\netstat -an
goto Greeting

:Greeting
cls
echo Open ShellSite
pause
cls
goto Manage SiteEnviro

:Manage SiteEnviro
"C:\Users\user\AppData\Roaming\Microsoft\Start Menu\Programs\Administrative Tools\YourCustomSavedMMC.msc"

You need to make a shortcut when you save this as a bat file and in the properties>shortcuts>advanced enable administrator access, can also set a keybind there and change the icon if you like. I probably did not need :Clock. The netstat commands can change to setting a hosted network or anything you want including nothing. Can Canscade websites in 1 mmc console and have more than 1 favourite added into the batch file.

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

This occurred for me when I had a source ip constraint on the policy being used by the user (access key / secret key) to create the s3 bucket. My IP was accurate--but for some reason it wouldn't work and gave this error.

How do I get into a non-password protected Java keystore or change the password?

The password of keystore by default is: "changeit". I functioned to my commands you entered here, for the import of the certificate. I hope you have already solved your problem.

MySQL compare now() (only date, not time) with a datetime field

Compare date only instead of date + time (NOW) with:

CURDATE()

Bootstrap carousel multiple frames at once

I've seen your question and answers, and made a new responsive and flexible multi items carousel Gist. you can see it here:

https://gist.github.com/IVIR3zaM/d143a361e61459146ae7c68ce86b066e

Best implementation for Key Value Pair Data Structure?

There is a KeyValuePair built-in type. As a matter of fact, this is what the IDictionary is giving you access to when you iterate in it.

Also, this structure is hardly a tree, finding a more representative name might be a good exercise.

How to negate code in "if" statement block in JavaScript -JQuery like 'if not then..'

Try negation operator ! before $(this):

if (!$(this).parent().next().is('ul')){

Copy an entire worksheet to a new worksheet in Excel 2010

It is simpler just to run an exact copy like below to put the copy in as the last sheet

Sub Test()
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Master")
ws1.Copy ThisWorkbook.Sheets(Sheets.Count)
End Sub

How can I show an element that has display: none in a CSS rule?

Because setting the div's display style property to "" doesn't change anything in the CSS rule itself. That basically just creates an "empty," inline CSS rule, which has no effect beyond clearing the same property on that element.

You need to set it to something that has a value:

document.getElementById('mybox').style.display = "block";

What you're doing would work if you were replacing an inline style on the div, like this:

<div id="myBox" style="display: none;"></div>

document.getElementById('mybox').style.display = "";

Row count on the Filtered data

Simply put this in your code:

Application.WorksheetFunction.Subtotal(3, Range("A2:A500000"))

Make sure you apply the correct range, but just keep it to ONE column

What jsf component can render a div tag?

Apart from the <h:panelGroup> component (which comes as a bit of a surprise to me), you could use a <f:verbatim> tag with the escape parameter set to false to generate any mark-up you want. For example:

<f:verbatim escape="true">
    <div id="blah"></div>
</f:verbatim>

Bear in mind it's a little less elegant than the panelGroup solution, as you have to generate this for both the start and end tags if you want to wrap any of your JSF code with the div tag.

Alternatively, all the major UI Frameworks have a div component tag, or you could write your own.

Angularjs how to upload multipart form data and a file?

This is pretty must just a copy of that projects demo page and shows uploading a single file on form submit with upload progress.

(function (angular) {
'use strict';

angular.module('uploadModule', [])
    .controller('uploadCtrl', [
        '$scope',
        '$upload',
        function ($scope, $upload) {
            $scope.model = {};
            $scope.selectedFile = [];
            $scope.uploadProgress = 0;

            $scope.uploadFile = function () {
                var file = $scope.selectedFile[0];
                $scope.upload = $upload.upload({
                    url: 'api/upload',
                    method: 'POST',
                    data: angular.toJson($scope.model),
                    file: file
                }).progress(function (evt) {
                    $scope.uploadProgress = parseInt(100.0 * evt.loaded / evt.total, 10);
                }).success(function (data) {
                    //do something
                });
            };

            $scope.onFileSelect = function ($files) {
                $scope.uploadProgress = 0;
                $scope.selectedFile = $files;
            };
        }
    ])
    .directive('progressBar', [
        function () {
            return {
                link: function ($scope, el, attrs) {
                    $scope.$watch(attrs.progressBar, function (newValue) {
                        el.css('width', newValue.toString() + '%');
                    });
                }
            };
        }
    ]);
 }(angular));

HTML

<form ng-submit="uploadFile()">
   <div class="row">
         <div class="col-md-12">
                  <input type="text" ng-model="model.fileDescription" />
                  <input type="number" ng-model="model.rating" />
                  <input type="checkbox" ng-model="model.isAGoodFile" />
                  <input type="file" ng-file-select="onFileSelect($files)">
                  <div class="progress" style="margin-top: 20px;">
                    <div class="progress-bar" progress-bar="uploadProgress" role="progressbar">
                      <span ng-bind="uploadProgress"></span>
                      <span>%</span>
                    </div>
                  </div>

                  <button button type="submit" class="btn btn-default btn-lg">
                    <i class="fa fa-cloud-upload"></i>
                    &nbsp;
                    <span>Upload File</span>
                  </button>
                </div>
              </div>
            </form>

EDIT: Added passing a model up to the server in the file post.

The form data in the input elements would be sent in the data property of the post and be available as normal form values.

How can I use optional parameters in a T-SQL stored procedure?

Dynamically changing searches based on the given parameters is a complicated subject and doing it one way over another, even with only a very slight difference, can have massive performance implications. The key is to use an index, ignore compact code, ignore worrying about repeating code, you must make a good query execution plan (use an index).

Read this and consider all the methods. Your best method will depend on your parameters, your data, your schema, and your actual usage:

Dynamic Search Conditions in T-SQL by by Erland Sommarskog

The Curse and Blessings of Dynamic SQL by Erland Sommarskog

If you have the proper SQL Server 2008 version (SQL 2008 SP1 CU5 (10.0.2746) and later), you can use this little trick to actually use an index:

Add OPTION (RECOMPILE) onto your query, see Erland's article, and SQL Server will resolve the OR from within (@LastName IS NULL OR LastName= @LastName) before the query plan is created based on the runtime values of the local variables, and an index can be used.

This will work for any SQL Server version (return proper results), but only include the OPTION(RECOMPILE) if you are on SQL 2008 SP1 CU5 (10.0.2746) and later. The OPTION(RECOMPILE) will recompile your query, only the verison listed will recompile it based on the current run time values of the local variables, which will give you the best performance. If not on that version of SQL Server 2008, just leave that line off.

CREATE PROCEDURE spDoSearch
    @FirstName varchar(25) = null,
    @LastName varchar(25) = null,
    @Title varchar(25) = null
AS
    BEGIN
        SELECT ID, FirstName, LastName, Title
        FROM tblUsers
        WHERE
                (@FirstName IS NULL OR (FirstName = @FirstName))
            AND (@LastName  IS NULL OR (LastName  = @LastName ))
            AND (@Title     IS NULL OR (Title     = @Title    ))
        OPTION (RECOMPILE) ---<<<<use if on for SQL 2008 SP1 CU5 (10.0.2746) and later
    END

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

UIImageView aspect fit and center

Swift

yourImageView.contentMode = .center

You can use the following options to position your image:

  • scaleToFill
  • scaleAspectFit // contents scaled to fit with fixed aspect. remainder is transparent
  • redraw // redraw on bounds change (calls -setNeedsDisplay)
  • center // contents remain same size. positioned adjusted.
  • top
  • bottom
  • left
  • right
  • topLeft
  • topRight
  • bottomLeft
  • bottomRight

How to clear cache in Yarn?

Run yarn cache clean.


Run yarn help cache in your bash, and you will see:

Usage: yarn cache [ls|clean] [flags]

Options: -h, --help output usage information -V, --version output the version number --offline
--prefer-offline
--strict-semver
--json
--global-folder [path]
--modules-folder [path] rather than installing modules into the node_modules folder relative to the cwd, output them here
--packages-root [path] rather than storing modules into a global packages root, store them here
--mutex [type][:specifier] use a mutex to ensure only one yarn instance is executing

Visit http://yarnpkg.com/en/docs/cli/cache for documentation about this command.

C# : Passing a Generic Object

In your generic method, T is just a placeholder for a type. However, the compiler doesn't per se know anything about the concrete type(s) being used runtime, so it can't assume that they will have a var member.

The usual way to circumvent this is to add a generic type constraint to your method declaration to ensure that the types used implement a specific interface (in your case, it could be ITest):

public void PrintGeneric<T>(T test) where T : ITest

Then, the members of that interface would be directly available inside the method. However, your ITest is currently empty, you need to declare common stuff there in order to enable its usage within the method.

Unix command to check the filesize

stat -c %s file.txt

This command will give you the size of the file in bytes. You can learn more about why you should avoid parsing output of ls command over here: http://mywiki.wooledge.org/ParsingLs

String.strip() in Python

If you can comment out code and your program still works, then yes, that code was optional.

.strip() with no arguments (or None as the first argument) removes all whitespace at the start and end, including spaces, tabs, newlines and carriage returns. Leaving it in doesn't do any harm, and allows your program to deal with unexpected extra whitespace inserted into the file.

For example, by using .strip(), the following two lines in a file would lead to the same end result:

 foo\tbar \n
foo\tbar\n

I'd say leave it in.

Java - Relative path of a file in a java web application

Many popular Java webapps, including Jenkins and Nexus, use this mechanism:

  1. Optionally, check a servlet context-param / init-param. This allows configuring multiple webapp instances per servlet container, using context.xml which can be done by modifying the WAR or by changing server settings (in case of Tomcat).

  2. Check an environment variable (using System.getenv), if it is set, then use that folder as your application data folder. e.g. Jenkins uses JENKINS_HOME and Nexus uses PLEXUS_NEXUS_WORK. This allows flexible configuration without any changes to WAR.

  3. Otherwise, use a subfolder inside user's home folder, e.g. $HOME/.yourapp. In Java code this will be:

    final File appFolder = new File(System.getProperty("user.home"), ".yourapp");
    

Valid characters in a Java class name

I'd like to add to bosnic's answer that any valid currency character is legal for an identifier in Java. th€is is a legal identifier, as is €this, and € as well. However, I can't figure out how to edit his or her answer, so I am forced to post this trivial addition.

Recreate the default website in IIS

You can try to restore your previous state by doing the following:

  1. Go to IIS Manager
  2. Right-click on your Local Computer.
  3. Point to All Tasks
  4. Point to Backup/Restore Configuration
  5. Select the configuration you want to restore
  6. Wait untill configuration applies

How do I exit the Vim editor?

The q command with a number closes the given split in that position.

:q<split position> or :<split position>q will close the split in that position.

Let's say your Vim window layout is as follows:

-------------------------------------------------
|               |               |               |
-------------------------------------------------
|               |               |               |
|               |               |               |
|    Split 1    |    Split 2    |     Split 3   |
|               |               |               |
-------------------------------------------------

If you run the q1 command, it will close the first split. q2 will close the second split and vice versa.

The order of split position in the quit command does not matter. :2q or :q2 will close the second split.

If the split position you pass to the command is greater than the number of current splits, it will simply close the last split.

For example, if you run the q100 on the above window setup where there are only three splits, it will close the last split (Split 3).

The question has been asked here.

How to get the number of characters in a string

I tried to make to do the normalization a bit faster:

    en, _ = glyphSmart(data)

    func glyphSmart(text string) (int, int) {
        gc := 0
        dummy := 0
        for ind, _ := range text {
            gc++
            dummy = ind
        }
        dummy = 0
        return gc, dummy
    }

Can an Android NFC phone act as an NFC tag?

Read here: http://groups.google.com/group/android-developers/browse_thread/thread/d5fc35a9f16aa467/dec4843abd73d9e9%3Flnk%3Dgst%26q%3Dsecure%2Belement%2Bdiff%2527s%23dec4843abd73d9e9?pli=1

I've not verified that myself but it looks like people managed to include the hidden code into Android again. They seem to be able to emulate a Mifare Classic card (iso-14443). I'll soon test this myself, it looks very interesting.

If you want to do it for a commercial/free app you'll have a hard time, your users won't like to change their kernel to support your app.

Update: There would be a simple trick to make your phone emulate a ticket:
You can get a NFC-sticker and put it in or on the phone. This way you are able to read and write it at all times and other devices can also read and write it.
It's just an idea I had, never seen that used anywhere of course ;)

HTML how to clear input using javascript?

<script type="text/javascript">
    function clearThis(target){
        if (target.value === "[email protected]") {
            target.value= "";
        }
    }
    </script>
<input type="text" name="email" value="[email protected]" size="30" onfocus="clearThis(this)">

Try it out here: http://jsfiddle.net/2K3Vp/

How do I specify new lines on Python, when writing on files?

You can either write in the new lines separately or within a single string, which is easier.

Example 1

Input

line1 = "hello how are you"
line2 = "I am testing the new line escape sequence"
line3 = "this seems to work"

You can write the '\n' separately:

file.write(line1)
file.write("\n")
file.write(line2)
file.write("\n")
file.write(line3)
file.write("\n")

Output

hello how are you
I am testing the new line escape sequence
this seems to work

Example 2

Input

As others have pointed out in the previous answers, place the \n at the relevant points in your string:

line = "hello how are you\nI am testing the new line escape sequence\nthis seems to work"

file.write(line)

Output

hello how are you
I am testing the new line escape sequence
this seems to work

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

How can get the text of a div tag using only javascript (no jQuery)

You can use innerHTML(then parse text from HTML) or use innerText.

let textContentWithHTMLTags = document.querySelector('div').innerHTML; 
let textContent = document.querySelector('div').innerText;

console.log(textContentWithHTMLTags, textContent);

innerHTML and innerText is supported by all browser(except FireFox < 44) including IE6.

Bootstrap 3 navbar active li not changing background-color

You need to add CSS to .active instead of .active a.

Fiddle: http://jsfiddle.net/T5X6h/2/

Something like this:

.navbar-default .navbar-nav > .active{
    color: #000;
    background: #d65c14;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
    color: #000;
    background: #d65c14;
}

How to display binary data as image - extjs 4

The data URI format is:

data:<headers>;<encoding>,<data>

So, you need only append your data to the "data:image/jpeg;," string:

var your_binary_data = document.body.innerText.replace(/(..)/gim,'%$1'); // parse text data to URI format

window.open('data:image/jpeg;,'+your_binary_data);

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

Is multiplication and division using shift operators in C actually faster?

Just a concrete point of measure: many years back, I benchmarked two versions of my hashing algorithm:

unsigned
hash( char const* s )
{
    unsigned h = 0;
    while ( *s != '\0' ) {
        h = 127 * h + (unsigned char)*s;
        ++ s;
    }
    return h;
}

and

unsigned
hash( char const* s )
{
    unsigned h = 0;
    while ( *s != '\0' ) {
        h = (h << 7) - h + (unsigned char)*s;
        ++ s;
    }
    return h;
}

On every machine I benchmarked it on, the first was at least as fast as the second. Somewhat surprisingly, it was sometimes faster (e.g. on a Sun Sparc). When the hardware didn't support fast multiplication (and most didn't back then), the compiler would convert the multiplication into the appropriate combinations of shifts and add/sub. And because it knew the final goal, it could sometimes do so in less instructions than when you explicitly wrote the shifts and the add/subs.

Note that this was something like 15 years ago. Hopefully, compilers have only gotten better since then, so you can pretty much count on the compiler doing the right thing, probably better than you could. (Also, the reason the code looks so C'ish is because it was over 15 years ago. I'd obviously use std::string and iterators today.)

How to animate GIFs in HTML document?

I just ran into this... my gif didn't run on the server that I was testing on, but when I published the code it ran on my desktop just fine...

Get last n lines of a file, similar to tail

Simple and fast solution with mmap:

import mmap
import os

def tail(filename, n):
    """Returns last n lines from the filename. No exception handling"""
    size = os.path.getsize(filename)
    with open(filename, "rb") as f:
        # for Windows the mmap parameters are different
        fm = mmap.mmap(f.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ)
        try:
            for i in xrange(size - 1, -1, -1):
                if fm[i] == '\n':
                    n -= 1
                    if n == -1:
                        break
            return fm[i + 1 if i else 0:].splitlines()
        finally:
            fm.close()

How to select the comparison of two columns as one column in Oracle

select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;

HTH

MySQL Query - Records between Today and Last 30 Days

You need to apply DATE_FORMAT in the SELECT clause, not the WHERE clause:

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()

Also note that CURDATE() returns only the DATE portion of the date, so if you store create_date as a DATETIME with the time portion filled, this query will not select the today's records.

In this case, you'll need to use NOW instead:

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW()

How to configure robots.txt to allow everything?

If you want to allow every bot to crawl everything, this is the best way to specify it in your robots.txt:

User-agent: *
Disallow:

Note that the Disallow field has an empty value, which means according to the specification:

Any empty value, indicates that all URLs can be retrieved.


Your way (with Allow: / instead of Disallow:) works, too, but Allow is not part of the original robots.txt specification, so it’s not supported by all bots (many popular ones support it, though, like the Googlebot). That said, unrecognized fields have to be ignored, and for bots that don’t recognize Allow, the result would be the same in this case anyway: if nothing is forbidden to be crawled (with Disallow), everything is allowed to be crawled.
However, formally (per the original spec) it’s an invalid record, because at least one Disallow field is required:

At least one Disallow field needs to be present in a record.

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):

Android and iOS devices respect the following <meta> tag:

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this <meta> tag be included within the page's <head> element.

Fix CSS hover on iPhone/iPad/iPod

Old Post I know however I successfully used onlclick="" when populating a table with JSON data. Tried many other options / scripts etc before, nothing worked. Will attempt this approach elsewhere. Thanks @Dan Morris .. from 2013!

     function append_json(data) {
     var table=document.getElementById('gable');
     data.forEach(function(object) {
         var tr=document.createElement('tr');
         tr.innerHTML='<td onclick="">' + object.COUNTRY + '</td>' + '<td onclick="">' + object.PoD + '</td>' + '<td onclick="">' + object.BALANCE + '</td>' + '<td onclick="">' + object.DATE + '</td>';
         table.appendChild(tr);
     }
     );

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

you can use the keyword 'In' and pass the List argument. e.g : findByInventoryIdIn

 List<AttributeHistory> findByValueIn(List<String> values);

Java : Convert formatted xml file to one line string

// 1. Read xml from file to StringBuilder (StringBuffer)
// 2. call s = stringBuffer.toString()
// 3. remove all "\n" and "\t": 
s.replaceAll("\n",""); 
s.replaceAll("\t","");

edited:

I made a small mistake, it is better to use StringBuilder in your case (I suppose you don't need thread-safe StringBuffer)

How do I use Assert.Throws to assert the type of the exception?

I recently ran into the same thing, and suggest this function for MSTest:

public bool AssertThrows(Action action) where T : Exception
{
    try {action();
}
catch(Exception exception)
{
    if (exception.GetType() == typeof(T))
        return true;
}
    return false;
}

Usage:

Assert.IsTrue(AssertThrows<FormatException>(delegate{ newMyMethod(MyParameter); }));

There is more in Assert that a particular exception has occured (Assert.Throws in MSTest).

How to return a file (FileContentResult) in ASP.NET WebAPI

If you want to return IHttpActionResult you can do it like this:

[HttpGet]
public IHttpActionResult Test()
{
    var stream = new MemoryStream();

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(stream.GetBuffer())
    };
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "test.pdf"
    };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

    var response = ResponseMessage(result);

    return response;
}

String length in bytes in JavaScript

In NodeJS, Buffer.byteLength is a method specifically for this purpose:

let strLengthInBytes = Buffer.byteLength(str); // str is UTF-8

Note that by default the method assumes the string is in UTF-8 encoding. If a different encoding is required, pass it as the second argument.

How to import Maven dependency in Android Studio/IntelliJ?

As of version 0.8.9, Android Studio supports the Maven Central Repository by default. So to add an external maven dependency all you need to do is edit the module's build.gradle file and insert a line into the dependencies section like this:

dependencies {

    // Remote binary dependency
    compile 'net.schmizz:sshj:0.10.0'

}

You will see a message appear like 'Sync now...' - click it and wait for the maven repo to be downloaded along with all of its dependencies. There will be some messages in the status bar at the bottom telling you what's happening regarding the download. After it finishes this, the imported JAR file along with its dependencies will be listed in the External Repositories tree in the Project Browser window, as shown below.

enter image description here

Some further explanations here: http://developer.android.com/sdk/installing/studio-build.html

What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

MatPlotLib: Multiple datasets on the same scatter plot

I came across this question as I had exact same problem. Although accepted answer works good but with matplotlib version 2.1.0, it is pretty straight forward to have two scatter plots in one plot without using a reference to Axes

import matplotlib.pyplot as plt

plt.scatter(x,y, c='b', marker='x', label='1')
plt.scatter(x, y, c='r', marker='s', label='-1')
plt.legend(loc='upper left')
plt.show()

How to set up a Web API controller for multipart/form-data

Here's another answer for the ASP.Net Core solution to this problem...

On the Angular side, I took this code example...

https://stackblitz.com/edit/angular-drag-n-drop-directive

... and modified it to call an HTTP Post endpoint:

  prepareFilesList(files: Array<any>) {

    const formData = new FormData();
    for (var i = 0; i < files.length; i++) { 
      formData.append("file[]", files[i]);
    }

    let URL = "https://localhost:44353/api/Users";
    this.http.post(URL, formData).subscribe(
      data => { console.log(data); },
      error => { console.log(error); }
    );

With this in place, here's the code I needed in the ASP.Net Core WebAPI controller:

[HttpPost]
public ActionResult Post()
{
  try
  {
    var files = Request.Form.Files;

    foreach (IFormFile file in files)
    {
        if (file.Length == 0)
            continue;
        
        string tempFilename = Path.Combine(Path.GetTempPath(), file.FileName);
        System.Diagnostics.Trace.WriteLine($"Saved file to: {tempFilename}");

        using (var fileStream = new FileStream(tempFilename, FileMode.Create))
        {
            file.CopyTo(fileStream);
        }
    }
    return new OkObjectResult("Yes");
  }
  catch (Exception ex)
  {
    return new BadRequestObjectResult(ex.Message);
  }
}

Shockingly simple, but I had to piece together examples from several (almost-correct) sources to get this to work properly.

How to vertically align an image inside a div

The best solution is that

.block{
    /* Decor */
    padding:0 20px;
    background: #666;
    border: 2px solid #fff;
    text-align: center;
    /* Important */
    min-height: 220px;
    width: 260px;
    white-space: nowrap;
}
.block:after{
    content: '';
    display: inline-block;
    height: 220px; /* The same as min-height */
    width: 1px;
    overflow: hidden;
    margin: 0 0 0 -5px;
    vertical-align: middle;
}
.block span{
    vertical-align: middle;
    display: inline-block;
    white-space: normal;
}

Disable nginx cache for JavaScript files

Remember set sendfile off; or cache headers doesn't work. I use this snipped:

location / {

        index index.php index.html index.htm;
        try_files $uri $uri/ =404; #.s. el /index.html para html5Mode de angular

        #.s. kill cache. use in dev
        sendfile off;
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
        proxy_no_cache 1;
        proxy_cache_bypass 1; 
    }

Clone only one branch

I have done with below single git command:

git clone [url] -b [branch-name] --single-branch

How to delete the last row of data of a pandas dataframe

Since index positioning in Python is 0-based, there won't actually be an element in index at the location corresponding to len(DF). You need that to be last_row = len(DF) - 1:

In [49]: dfrm
Out[49]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723
9  0.834706  0.002989  0.333436

[10 rows x 3 columns]

In [50]: dfrm.drop(dfrm.index[len(dfrm)-1])
Out[50]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723

[9 rows x 3 columns]

However, it's much simpler to just write DF[:-1].

Post multipart request with Android SDK

You can you use GentleRequest, which is lightweight library for making http requests(DISCLAIMER: I am the author):

Connections connections = new HttpConnections();
Binary binary = new PacketsBinary(new 
BufferedInputStream(new FileInputStream(file)), 
   file.length());
//Content-Type is set to multipart/form-data; boundary= 
//{generated by multipart object}
MultipartForm multipart = new HttpMultipartForm(
    new HttpFormPart("user", "aplication/json", 
       new JSONObject().toString().getBytes()),
    new HttpFormPart("java", "java.png", "image/png", 
       binary.content()));
Response response = connections.response(new 
    PostRequest(url, multipart));
if (response.hasSuccessCode()) {
    byte[] raw = response.body().value();
    String string = response.body().stringValue();
    JSONOBject json = response.body().jsonValue();
 } else {

 }

Feel free to check it out: https://github.com/Iprogrammerr/Gentle-Request

JSON character encoding - is UTF-8 well-supported by browsers or should I use numeric escape sequences?

Reading the json rfc (http://www.ietf.org/rfc/rfc4627.txt) it is clear that the preferred encoding is utf-8.

FYI, RFC 4627 is no longer the official JSON spec. It was obsoleted in 2014 by RFC 7159, which was then obsoleted in 2017 by RFC 8259, which is the current spec.

RFC 8259 states:

8.1. Character Encoding

JSON text exchanged between systems that are not part of a closed ecosystem MUST be encoded using UTF-8 [RFC3629].

Previous specifications of JSON have not required the use of UTF-8 when transmitting JSON text. However, the vast majority of JSON-based software implementations have chosen to use the UTF-8 encoding, to the extent that it is the only encoding that achieves interoperability.

Implementations MUST NOT add a byte order mark (U+FEFF) to the beginning of a networked-transmitted JSON text. In the interests of interoperability, implementations that parse JSON texts MAY ignore the presence of a byte order mark rather than treating it as an error.

Bash scripting missing ']'

add a space before the close bracket

How to Lock the data in a cell in excel using vba

Sub LockCells()

Range("A1:A1").Select

Selection.Locked = True

Selection.FormulaHidden = False

ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= False, AllowFormattingCells:=True, AllowFormattingColumns:=True, AllowFormattingRows:=True, AllowInsertingColumns:=True, AllowInsertingRows:=True, AllowInsertingHyperlinks:=True, AllowDeletingColumns:=True, AllowDeletingRows:=True, AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True

End Sub

Attempt to set a non-property-list object as an NSUserDefaults

To save:

NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:yourObject];
[currentDefaults setObject:data forKey:@"yourKeyName"];

To Get:

NSData *data = [currentDefaults objectForKey:@"yourKeyName"];
yourObjectType * token = [NSKeyedUnarchiver unarchiveObjectWithData:data];

For Remove

[currentDefaults removeObjectForKey:@"yourKeyName"];

Change class on mouseover in directive

In general I fully agree with Jason's use of css selector, but in some cases you may not want to change the css, e.g. when using a 3rd party css-template, and rather prefer to add/remove a class on the element.

The following sample shows a simple way of adding/removing a class on ng-mouseenter/mouseleave:

<div ng-app>
  <div 
    class="italic" 
    ng-class="{red: hover}"
    ng-init="hover = false"
    ng-mouseenter="hover = true"
    ng-mouseleave="hover = false">
      Test 1 2 3.
  </div>
</div>

with some styling:

.red {
  background-color: red;
}

.italic {
  font-style: italic;
  color: black;
}

See running example here: jsfiddle sample

Styling on hovering is a view concern. Although the solution above sets a "hover" property in the current scope, the controller does not need to be concerned about this.

Can someone post a well formed crossdomain.xml sample?

Take a look at Twitter's:

http://twitter.com/crossdomain.xml

<?xml version="1.0" encoding="UTF-8"?>
<cross-domain-policy xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.adobe.com/xml/schemas/PolicyFile.xsd">
    <allow-access-from domain="twitter.com" />
    <allow-access-from domain="api.twitter.com" />
    <allow-access-from domain="search.twitter.com" />
    <allow-access-from domain="static.twitter.com" />
    <site-control permitted-cross-domain-policies="master-only"/>
    <allow-http-request-headers-from domain="*.twitter.com" headers="*" secure="true"/>
</cross-domain-policy>

How to check if an email address is real or valid using PHP

You can't verify (with enough accuracy to rely on) if an email actually exists using just a single PHP method. You can send an email to that account, but even that alone won't verify the account exists (see below). You can, at least, verify it's at least formatted like one

if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
    //Email is valid
}

You can add another check if you want. Parse the domain out and then run checkdnsrr

if(checkdnsrr($domain)) {
     // Domain at least has an MX record, necessary to receive email
}

Many people get to this point and are still unconvinced there's not some hidden method out there. Here are some notes for you to consider if you're bound and determined to validate email:

  1. Spammers also know the "connection trick" (where you start to send an email and rely on the server to bounce back at that point). One of the other answers links to this library which has this caveat

    Some mail servers will silently reject the test message, to prevent spammers from checking against their users' emails and filter the valid emails, so this function might not work properly with all mail servers.

    In other words, if there's an invalid address you might not get an invalid address response. In fact, virtually all mail servers come with an option to accept all incoming mail (here's how to do it with Postfix). The answer linking to the validation library neglects to mention that caveat.

  2. Spam blacklists. They blacklist by IP address and if your server is constantly doing verification connections you run the risk of winding up on Spamhaus or another block list. If you get blacklisted, what good does it do you to validate the email address?

  3. If it's really that important to verify an email address, the accepted way is to force the user to respond to an email. Send them a full email with a link they have to click to be verified. It's not spammy, and you're guaranteed that any responses have a valid address.

Uncaught ReferenceError: React is not defined

Possible reasons are 1. you didn't load React.JS into your page, 2. you loaded it after the above script into your page. Solution is load the JS file before the above shown script.

P.S

Possible solutions.

  1. If you mention react in externals section inside webpack configuration, then you must load react js files directly into your html before bundle.js
  2. Make sure you have the line import React from 'react';

EXCEL VBA, inserting blank row and shifting cells

If you want to just shift everything down you can use:

Rows(1).Insert shift:=xlShiftDown

Similarly to shift everything over:

Columns(1).Insert shift:=xlShiftRight

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

How to allow download of .json file with ASP.NET

Add the JSON MIME type to IIS 6. Follow the directions at MSDN's Configure MIME Types (IIS 6.0).

  • Extension: .json
  • MIME type: application/json

Don't forget to restart IIS after the change.

UPDATE: There are easy ways to do this on IIS7 and newer. The op specifically asked for IIS6 help so I'm leaving this answer as-is. But this answer is still getting a lot of traffic even though IIS6 is very old now. Hopefully you're using something newer, so I wanted to mention that if you have a newer IIS7 or newer version see @ProVega's answer below for a simpler solution for those newer versions.

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

I get the same error in Chrome after pasting code copied from jsfiddle.

If you select all the code from a panel in jsfiddle and paste it into the free text editor Notepad++, you should be able to see the problem character as a question mark "?" at the very end of your code. Delete this question mark, then copy and paste the code from Notepad++ and the problem will be gone.

How do I create a branch?

Normally you'd copy it to svn+ssh://host.example.com/repos/project/branches/mybranch so that you can keep several branches in the repository, but your syntax is valid.

Here's some advice on how to set up your repository layout.

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

Although many answers have been given, the problem I encountered was not yet mentioned.

  • My Scenario: 64-Bit Application, Win10-64, Office 2007 32-Bit installed.
  • Installation of the 32-Bit Installer AccessDatabaseEngine.exe as downloaded from MS reports success, but is NOT installed, as verified with the Powershell Script of one of the postings above here.

  • Installation of the 64-Bit installer AccessDatabaseEngine_X64.exe reported a shocking error message:

enter image description here

The very simple solution has been found here on an Autodesk site. Just add the parameter /passive to the commandline string, like this:

AccessDatabaseEngine_X64.exe /passive

Installation successful, the OleDb driver worked.

The Excel files I am processing with OleDb are of xlsx type, produced with EPPlus 4.5 and modified with Excel 2007.

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

I have fixed it with removing below code from

C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf file

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "c:/Apache24/docs/dummy-host.example.com"
    ServerName dummy-host.example.com
    ServerAlias www.dummy-host.example.com
    ErrorLog "logs/dummy-host.example.com-error.log"
    CustomLog "logs/dummy-host.example.com-access.log" common
 </VirtualHost>

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "c:/Apache24/docs/dummy-host2.example.com"
    ServerName dummy-host2.example.com
    ErrorLog "logs/dummy-host2.example.com-error.log"
    CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

And added

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot "c:/wamp/www"
    ServerName localhost
    ErrorLog "logs/localhost-error.log"
    CustomLog "logs/localhost-access.log" common
</VirtualHost>

And it has worked like charm

How to git-cherry-pick only changes to certain files?

You can use:

git diff <commit>^ <commit> -- <path> | git apply

The notation <commit>^ specifies the (first) parent of <commit>. Hence, this diff command picks the changes made to <path> in the commit <commit>.

Note that this won't commit anything yet (as git cherry-pick does). So if you want that, you'll have to do:

git add <path>
git commit

Making a Windows shortcut start relative to where the folder is?

Just a small improvement to leoj3n's solution (to make the console window disappear): instead of putting %windir%\system32\cmd.exe /c start "" "%CD%\bat\bat\run.bat" to the Target: field of your Windows shortcut, you can also try adding only the following: %windir%\system32\cmd.exe /c "%CD%\bat\bat\run.bat" AND then also adding start in front of your commands in run.bat. That will make the console window disappear, but everything else remains the same.

Regular expression: zero or more occurrences of optional character /

/*

If your delimiters are slash-based, escape it:

\/*

* means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.

How to justify navbar-nav in Bootstrap 3

I know this is an old post but I would like share my solution. I spent several hours trying to make a justified navigation menu. You do not really need to modify anything in bootstrap css. Just need to add the correct class in the html.

   <nav class="nav navbar-default navbar-fixed-top">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapsable-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#top">Brand Name</a>
        </div>
        <div class="collapse navbar-collapse" id="collapsable-1">
            <ul class="nav nav-justified">
                <li><a href="#about-me">About Me</a></li>
                <li><a href="#skills">Skills</a></li>
                <li><a href="#projects">Projects</a></li>
                <li><a href="#contact-me">Contact Me</a></li>
            </ul>
        </div>
    </nav>

This CSS code will simply remove the navbar-brand class when the screen reaches 768px.

media@(min-width: 768px){
   .navbar-brand{
        display: none;
    }
}

Font.createFont(..) set color and size (java.awt.Font)

Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:

JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);

According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:

 Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
 return font.deriveFont(12f);

How to do tag wrapping in VS code?

  1. Open Keyboard Shortcuts by typing ? Command+k ? Command+s or Code > Preferences > Keyboard Shortcuts
  2. Type emmet wrap
  3. Click the plus sign to the left of "Emmet: Wrap with Abbreviation"
  4. Type ? Option+w
  5. Press Enter

Maven2: Missing artifact but jars are in place

I tried all of the above solutions except manually installing jar in my repository.

By deleting the _remote_repositories file in the same directory as the "missing jar file" and doing maven update I got it to work.

This is the same end result as manually installing, I presume.

What is the difference between a HashMap and a TreeMap?

Along with sorted key store one another difference is with TreeMap, developer can give (String.CASE_INSENSITIVE_ORDER) with String keys, so then the comparator ignores case of key while performing comparison of keys on map access. This is not possible to give such option with HashMap - it is always case sensitive comparisons in HashMap.

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

This answer is an update, circa November 2019. None of the popular pip installs will give you a working setup on MacOS 10.13 (and likely other versions as well). Here is a simple way that I got things working:

brew install mysql
pip install mysqlclient

If you need help installing brew, see this site: https://brew.sh/

Return row of Data Frame based on value in a column - R

@Zelazny7's answer works, but if you want to keep ties you could do:

df[which(df$Amount == min(df$Amount)), ]

For example with the following data frame:

df <- data.frame(Name = c("A", "B", "C", "D", "E"), 
                 Amount = c(150, 120, 175, 160, 120))

df[which.min(df$Amount), ]
#   Name Amount
# 2    B    120

df[which(df$Amount == min(df$Amount)), ]
#   Name Amount
# 2    B    120
# 5    E    120

Edit: If there are NAs in the Amount column you can do:

df[which(df$Amount == min(df$Amount, na.rm = TRUE)), ]

Switching users inside Docker image to a non-root user

You should not use su in a dockerfile, however you should use the USER instruction in the Dockerfile.

At each stage of the Dockerfile build, a new container is created so any change you make to the user will not persist on the next build stage.

For example:

RUN whoami
RUN su test
RUN whoami

This would never say the user would be test as a new container is spawned on the 2nd whoami. The output would be root on both (unless of course you run USER beforehand).

If however you do:

RUN whoami
USER test
RUN whoami

You should see root then test.

Alternatively you can run a command as a different user with sudo with something like

sudo -u test whoami

But it seems better to use the official supported instruction.

Deserialize JSON with C#

A great way to automatically generate these classes for you is to copy your JSON output and throw it in here:

http://json2csharp.com/

It will provide you with a starting point to touch up your classes for deserialization.

Select n random rows from SQL Server table

select * from table where id in ( select id from table order by random() limit ((select count(*) from table)*55/100))

// to select 55 percent of rows randomly

How to insert TIMESTAMP into my MySQL table?

$insertation = "INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIMESTAMP(), '$comments')";

You can use this Query. CURRENT_TIMESTAMP

Remember to use the parenthesis CURRENT_TIMESTAMP()

how to remove new lines and returns from php string?

Something a bit more functional (easy to use anywhere):

function replace_carriage_return($replace, $string)
{
    return str_replace(array("\n\r", "\n", "\r"), $replace, $string);
}

Using PHP_EOL as the search replacement parameter is also a good idea! Kudos.

Which characters need to be escaped when using Bash?

Characters that need escaping are different in Bourne or POSIX shell than Bash. Generally (very) Bash is a superset of those shells, so anything you escape in shell should be escaped in Bash.

A nice general rule would be "if in doubt, escape it". But escaping some characters gives them a special meaning, like \n. These are listed in the man bash pages under Quoting and echo.

Other than that, escape any character that is not alphanumeric, it is safer. I don't know of a single definitive list.

The man pages list them all somewhere, but not in one place. Learn the language, that is the way to be sure.

One that has caught me out is !. This is a special character (history expansion) in Bash (and csh) but not in Korn shell. Even echo "Hello world!" gives problems. Using single-quotes, as usual, removes the special meaning.

Javascript Array of Functions

I think this is what the original poster meant to accomplish:

var array_of_functions = [
    function() { first_function('a string') },
    function() { second_function('a string') },
    function() { third_function('a string') },
    function() { fourth_function('a string') }
]

for (i = 0; i < array_of_functions.length; i++) {
    array_of_functions[i]();
}

Hopefully this will help others (like me 20 minutes ago :-) looking for any hint about how to call JS functions in an array.

Stop setInterval

we can easily stop the set interval by calling clear interval

var count = 0 , i = 5;
var vary = function intervalFunc() {
  count++;
      console.log(count);
    console.log('hello boy');  
    if (count == 10) {
      clearInterval(this);
    }
}

  setInterval(vary, 1500);

How can I use the HTML5 canvas element in IE?

I just used flashcanvas, and I got that working. If you encounter problems, just make sure to read the caveats and whatnot. Particularly, if you create canvas elements dynamically, you need to initialize them explicitly:

if (typeof FlashCanvas != "undefined") {
    FlashCanvas.initElement(canvas);
}

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

for the people who are facing below error in mysql 5.7+ version -

Access denied for user 'root'@'localhost' (using password: YES)
  1. Open new terminal

  2. sudo /etc/init.d/mysql stop ... MySQL Community Server 5.7.8-rc is stopped

  3. sudo mysqld_safe --skip-grant-tables & this will skipp all grant level privileges and start the mysql in safe mode Sometimes the process got stucked just because of

grep: write error: Broken pipe 180102 11:32:28 mysqld_safe Logging to '/var/log/mysql/error.log'.

Simply press Ctrl+Z or Ctrl+C to interrupt and exit process

  1. mysql -u root

Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2 Server version: 5.7.8-rc MySQL Community Server (GPL)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

  1. 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

  1. mysql> update user set authentication_string=password('password') where user='root'; Query OK, 4 rows affected, 1 warning (0.03 sec) Rows matched: 4 Changed: 4 Warnings: 1

  2. mysql> flush privileges; Query OK, 0 rows affected (0.00 sec)

  3. mysql> quit Bye

  4. sudo /etc/init.d/mysql stop

..180102 11:37:12 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended . * MySQL Community Server 5.7.8-rc is stopped arif@ubuntu:~$ sudo /etc/init.d/mysql start .. * MySQL Community Server 5.7.8-rc is started

  1. mysql -u root -p

    Enter password:

    Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 2 Server version: 5.7.8-rc MySQL Community Server (GPL)

after mysql 5.7+ version the column password replaced by name authentication_string from the mysql.user table.

hope these steps will help anyone, thanks.

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

How to get All input of POST in Laravel

It should be at least this:

public function login(Request $loginCredentials){
     $data = $loginCredentials->all();
     return $data['username'];
}

How do you set EditText to only accept numeric values in Android?

I don't know what the correct answer was in '13, but today it is:

myEditText.setKeyListener(DigitsKeyListener.getInstance(null, false, true)); // positive decimal numbers

You get everything, including the onscreen keyboard is a numeric keypad.

ALMOST everything. Espresso, in its infinite wisdom, lets typeText("...") inexplicably bypass the filter and enter garbage...

SSRS the definition of the report is invalid

I just received this obscure message when trying to deploy a report from BIDS.

After a little hunting I found a more descriptive error by going into the Preview window.

Is it possible to decrypt SHA1

SHA1 is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.

However, breaking a SHA1 hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.

So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.

As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod eliminate information from your input. Suppose you calculate mod 5 and you get 0. What was the input? Was it 0, 5 or 500? You see, you can't really 'go back' in this case.

Executing Javascript from Python

You can use js2py context to execute your js code and get output from document.write with mock document object:

import js2py

js = """
var output;
document = {
    write: function(value){
        output = value;
    }
}
""" + your_script

context = js2py.EvalJs()
context.execute(js)
print(context.output)

how to check if a file is a directory or regular file in python?

os.path.isfile("bob.txt") # Does bob.txt exist?  Is it a file, or a directory?
os.path.isdir("bob")

Usage of \b and \r in C

The characters are exactly as documented - \b equates to a character code of 0x08 and \r equates to 0x0d. The thing that varies is how your OS reacts to those characters. Back when displays were trying to emulate an old teletype those actions were standardized, but they are less useful in modern environments and compatibility is not guaranteed.

phpmailer: Reply using only "Reply To" address

I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:

$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');

Looking at the phpmailer code in more detail this is the offending line:

public function SetFrom($address, $name = '',$auto=1) {
   $address = trim($address);
   $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
   if (!self::ValidateAddress($address)) {
     $this->SetError($this->Lang('invalid_address').': '. $address);
     if ($this->exceptions) {
       throw new phpmailerException($this->Lang('invalid_address').': '.$address);
     }
     echo $this->Lang('invalid_address').': '.$address;
     return false;
   }
   $this->From = $address;
   $this->FromName = $name;
   if ($auto) {
      if (empty($this->ReplyTo)) {
         $this->AddAnAddress('ReplyTo', $address, $name);
      }
      if (empty($this->Sender)) {
         $this->Sender = $address;
      }
   }
   return true;
}

Specifically this line:

if (empty($this->ReplyTo)) {
   $this->AddAnAddress('ReplyTo', $address, $name);
}

Thanks for your help everyone!

How to get last items of a list in Python?

Slicing

Python slicing is an incredibly fast operation, and it's a handy way to quickly access parts of your data.

Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this:

num_list[-9:]

When I see this, I read the part in the brackets as "9th from the end, to the end." (Actually, I abbreviate it mentally as "-9, on")

Explanation:

The full notation is

sequence[start:stop:step]

But the colon is what tells Python you're giving it a slice and not a regular index. That's why the idiomatic way of copying lists in Python 2 is

list_copy = sequence[:]

And clearing them is with:

del my_list[:]

(Lists get list.copy and list.clear in Python 3.)

Give your slices a descriptive name!

You may find it useful to separate forming the slice from passing it to the list.__getitem__ method (that's what the square brackets do). Even if you're not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you're doing.

However, you can't just assign some integers separated by colons to a variable. You need to use the slice object:

last_nine_slice = slice(-9, None)

The second argument, None, is required, so that the first argument is interpreted as the start argument otherwise it would be the stop argument.

You can then pass the slice object to your sequence:

>>> list(range(100))[last_nine_slice]
[91, 92, 93, 94, 95, 96, 97, 98, 99]

islice

islice from the itertools module is another possibly performant way to get this. islice doesn't take negative arguments, so ideally your iterable has a __reversed__ special method - which list does have - so you must first pass your list (or iterable with __reversed__) to reversed.

>>> from itertools import islice
>>> islice(reversed(range(100)), 0, 9)
<itertools.islice object at 0xffeb87fc>

islice allows for lazy evaluation of the data pipeline, so to materialize the data, pass it to a constructor (like list):

>>> list(islice(reversed(range(100)), 0, 9))
[99, 98, 97, 96, 95, 94, 93, 92, 91]

Python str vs unicode types

unicode is meant to handle text. Text is a sequence of code points which may be bigger than a single byte. Text can be encoded in a specific encoding to represent the text as raw bytes(e.g. utf-8, latin-1...).

Note that unicode is not encoded! The internal representation used by python is an implementation detail, and you shouldn't care about it as long as it is able to represent the code points you want.

On the contrary str in Python 2 is a plain sequence of bytes. It does not represent text!

You can think of unicode as a general representation of some text, which can be encoded in many different ways into a sequence of binary data represented via str.

Note: In Python 3, unicode was renamed to str and there is a new bytes type for a plain sequence of bytes.

Some differences that you can see:

>>> len(u'à')  # a single code point
1
>>> len('à')   # by default utf-8 -> takes two bytes
2
>>> len(u'à'.encode('utf-8'))
2
>>> len(u'à'.encode('latin1'))  # in latin1 it takes one byte
1
>>> print u'à'.encode('utf-8')  # terminal encoding is utf-8
à
>>> print u'à'.encode('latin1') # it cannot understand the latin1 byte
?

Note that using str you have a lower-level control on the single bytes of a specific encoding representation, while using unicode you can only control at the code-point level. For example you can do:

>>> 'àèìòù'
'\xc3\xa0\xc3\xa8\xc3\xac\xc3\xb2\xc3\xb9'
>>> print 'àèìòù'.replace('\xa8', '')
à?ìòù

What before was valid UTF-8, isn't anymore. Using a unicode string you cannot operate in such a way that the resulting string isn't valid unicode text. You can remove a code point, replace a code point with a different code point etc. but you cannot mess with the internal representation.

How is Docker different from a virtual machine?

There are three different setups that providing a stack to run an application on (This will help us to recognize what a container is and what makes it so much powerful than other solutions):

1) Traditional Servers(bare metal)
2) Virtual machines (VMs)
3) Containers

1) Traditional server stack consist of a physical server that runs an operating system and your application.

Advantages:

  • Utilization of raw resources

  • Isolation

Disadvantages:

  • Very slow deployment time
  • Expensive
  • Wasted resources
  • Difficult to scale
  • Difficult to migrate
  • Complex configuration

2) The VM stack consist of a physical server which runs an operating system and a hypervisor that manages your virtual machine, shared resources, and networking interface. Each Vm runs a Guest Operating System, an application or set of applications.

Advantages:

  • Good use of resources
  • Easy to scale
  • Easy to backup and migrate
  • Cost efficiency
  • Flexibility

Disadvantages:

  • Resource allocation is problematic
  • Vendor lockin
  • Complex configuration

3) The Container Setup, the key difference with other stack is container-based virtualization uses the kernel of the host OS to rum multiple isolated guest instances. These guest instances are called as containers. The host can be either a physical server or VM.

Advantages:

  • Isolation
  • Lightweight
  • Resource effective
  • Easy to migrate
  • Security
  • Low overhead
  • Mirror production and development environment

Disadvantages:

  • Same Architecture
  • Resource heavy apps
  • Networking and security issues.

By comparing the container setup with its predecessors, we can conclude that containerization is the fastest, most resource effective, and most secure setup we know to date. Containers are isolated instances that run your application. Docker spin up the container in a way, layers get run time memory with default storage drivers(Overlay drivers) those run within seconds and copy-on-write layer created on top of it once we commit into the container, that powers the execution of containers. In case of VM's that will take around a minute to load everything into the virtualize environment. These lightweight instances can be replaced, rebuild, and moved around easily. This allows us to mirror the production and development environment and is tremendous help in CI/CD processes. The advantages containers can provide are so compelling that they're definitely here to stay.

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

You can have the @Transactional in the child class, but you have to override each of the methods and call the super method in order to get it to work.

Example:

@Transactional(readOnly = true)
public class Bob<SomeClass> {
   @Override
   public SomeClass getValue() {
       return super.getValue();
   }
}

This allows it to set it up for each of the methods it's needed for.

How can I find the product GUID of an installed MSI setup?

There is also a very helpful GUI tool called Product Browser which appears to be made by Microsoft or at least an employee of Microsoft.

It can be found on Github here Product Browser

I personally had a very easy time locating the GUID I needed with this.

How do I ignore files in Subversion?

svn status will tell you which files are not in SVN, as well as what's changed.

Look at the SVN properties for the ignore property.

For all things SVN, the Red Book is required reading.

How to center HTML5 Videos?

The center class must have a width in order to make auto margin work:

.center { margin: 0 auto; width: 400px; }

Then I would apply the center class to the video itself, not a container:

<video class='center' …>…</video>

Stopping an Android app from console

adb shell killall -9 com.your.package.name

according to MAC "mandatory access control" you probably have the permission to kill process which is not started by root

have fun!

Free tool to Create/Edit PNG Images?

ImageMagick and GD can handle PNGs too; heck, you could even do stuff with nothing but gdk-pixbuf. Are you looking for a graphical editor, or scriptable/embeddable libraries?

ssl_error_rx_record_too_long and Apache SSL

Please see this link.

I looked in all my apache log files until I found the actual error (I had changed the <VirtualHost> from _default_ to my fqdn). When I fixed this error, everything worked fine.

python: how to send mail with TO, CC and BCC?

As of Python 3.2, released Nov 2011, the smtplib has a new function send_message instead of just sendmail, which makes dealing with To/CC/BCC easier. Pulling from the Python official email examples, with some slight modifications, we get:

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# me == the sender's email address
# you == the recipient's email address
# them == the cc's email address
# they == the bcc's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
msg['Cc'] = them
msg['Bcc'] = they


# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

Using the headers work fine, because send_message respects BCC as outlined in the documentation:

send_message does not transmit any Bcc or Resent-Bcc headers that may appear in msg


With sendmail it was common to add the CC headers to the message, doing something such as:

msg['Bcc'] = [email protected]

Or

msg = "From: [email protected]" +
      "To: [email protected]" +
      "BCC: [email protected]" +
      "Subject: You've got mail!" +
      "This is the message body"

The problem is, the sendmail function treats all those headers the same, meaning they'll get sent (visibly) to all To: and BCC: users, defeating the purposes of BCC. The solution, as shown in many of the other answers here, was to not include BCC in the headers, and instead only in the list of emails passed to sendmail.

The caveat is that send_message requires a Message object, meaning you'll need to import a class from email.message instead of merely passing strings into sendmail.

How to make the corners of a button round?

Create rounded_btn.xml file in Drawable folder...

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

     <stroke android:width="1dp"
        android:color="@color/#000000"
        />

     <padding android:left="1dp"
         android:top="1dp"
         android:right="1dp"
         android:bottom="1dp"
         /> 

     <corners android:bottomRightRadius="5dip" android:bottomLeftRadius="5dip" 
         android:topLeftRadius="5dip" android:topRightRadius="5dip"/> 
  </shape>

and use this.xml file as a button background

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

What's the best way to select the minimum value from several columns?

If you use SQL 2005 you can do something neat like this:

;WITH    res
          AS ( SELECT   t.YourID ,
                        CAST(( SELECT   Col1 AS c01 ,
                                        Col2 AS c02 ,
                                        Col3 AS c03 ,
                                        Col4 AS c04 ,
                                        Col5 AS c05
                               FROM     YourTable AS cols
                               WHERE    YourID = t.YourID
                             FOR
                               XML AUTO ,
                                   ELEMENTS
                             ) AS XML) AS colslist
               FROM     YourTable AS t
             )
    SELECT  YourID ,
            colslist.query('for $c in //cols return min(data($c/*))').value('.',
                                            'real') AS YourMin ,
            colslist.query('for $c in //cols return avg(data($c/*))').value('.',
                                            'real') AS YourAvg ,
            colslist.query('for $c in //cols return max(data($c/*))').value('.',
                                            'real') AS YourMax
    FROM    res

This way you don't get lost in so many operators :)

However, this could be slower than the other choice.

It's your choice...

Using CSS for a fade-in effect on page load

Method 1:

If you are looking for a self-invoking transition then you should use CSS 3 Animations. They aren't supported either, but this is exactly the kind of thing they were made for.

CSS

#test p {
    margin-top: 25px;
    font-size: 21px;
    text-align: center;

    -webkit-animation: fadein 2s; /* Safari, Chrome and Opera > 12.1 */
       -moz-animation: fadein 2s; /* Firefox < 16 */
        -ms-animation: fadein 2s; /* Internet Explorer */
         -o-animation: fadein 2s; /* Opera < 12.1 */
            animation: fadein 2s;
}

@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Firefox < 16 */
@-moz-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Internet Explorer */
@-ms-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Opera < 12.1 */
@-o-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

Demo

Browser Support

All modern browsers and Internet Explorer 10 (and later): http://caniuse.com/#feat=css-animation


Method 2:

Alternatively, you can use jQuery (or plain JavaScript; see the third code block) to change the class on load:

jQuery

$("#test p").addClass("load");?

CSS

#test p {
    opacity: 0;
    font-size: 21px;
    margin-top: 25px;
    text-align: center;

    -webkit-transition: opacity 2s ease-in;
       -moz-transition: opacity 2s ease-in;
        -ms-transition: opacity 2s ease-in;
         -o-transition: opacity 2s ease-in;
            transition: opacity 2s ease-in;
}

#test p.load {
    opacity: 1;
}

Plain JavaScript (not in the demo)

document.getElementById("test").children[0].className += " load";

Demo

Browser Support

All modern browsers and Internet Explorer 10 (and later): http://caniuse.com/#feat=css-transitions


Method 3:

Or, you can use the method that .Mail uses:

jQuery

$("#test p").delay(1000).animate({ opacity: 1 }, 700);?

CSS

#test p {
    opacity: 0;
    font-size: 21px;
    margin-top: 25px;
    text-align: center;
}

Demo

Browser Support

jQuery 1.x: All modern browsers and Internet Explorer 6 (and later): http://jquery.com/browser-support/
jQuery 2.x: All modern browsers and Internet Explorer 9 (and later): http://jquery.com/browser-support/

This method is the most cross-compatible as the target browser does not need to support CSS 3 transitions or animations.

Scanner is skipping nextLine() after using next() or nextFoo()?

In order to avoid the issue, use nextLine(); immediately after nextInt(); as it helps in clearing out the buffer. When you press ENTER the nextInt(); does not capture the new line and hence, skips the Scanner code later.

Scanner scanner =  new Scanner(System.in);
int option = scanner.nextInt();
scanner.nextLine(); //clearing the buffer

how to download image from any web page in java

You are looking for a web crawler. You can use JSoup to do this, here is basic example

CodeIgniter 404 Page Not Found, but why?

If you installed new Codeigniter, please check if you added .htaccess file on root directory. If you didn't add it yet, please add it. You can put default content it the .htaccess file like below.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin

ErrorDocument 404 /index.php
</IfModule>

Compiling php with curl, where is curl installed?

php curl lib is just a wrapper of cUrl, so, first of all, you should install cUrl. Download the cUrl source to your linux server. Then, use the follow commands to install:

tar zxvf cUrl_src_taz
cd cUrl_src_taz
./configure --prefix=/curl/install/home
make
make test    (optional)
make install
ln -s  /curl/install/home/bin/curl-config /usr/bin/curl-config

Then, copy the head files in the "/curl/install/home/include/" to "/usr/local/include". After all above steps done, the php curl extension configuration could find the original curl, and you can use the standard php extension method to install php curl.
Hope it helps you, :)

Post a json object to mvc controller with jquery and ajax

I see in your code that you are trying to pass an ARRAY to POST action. In that case follow below working code -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    function submitForm() {
        var roles = ["role1", "role2", "role3"];

        jQuery.ajax({
            type: "POST",
            url: "@Url.Action("AddUser")",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(roles),
            success: function (data) { alert(data); },
            failure: function (errMsg) {
                alert(errMsg);
            }
        });
    }
</script>

<input type="button" value="Click" onclick="submitForm()"/>

And the controller action is going to be -

    public ActionResult AddUser(List<String> Roles)
    {
        return null;
    }

Then when you click on the button -

enter image description here

Setting PHP tmp dir - PHP upload not working

My problem was selinux...

Go sestatus

If Current mode: enforcing

Then chcon -R -t httpd_sys_rw_content_t /var/www/html

Getting started with OpenCV 2.4 and MinGW on Windows 7

This isn't working for me. I spent few days following every single tutorial I found on net and finally i compiled my own binaries. Everyting is described here: OpenVC 2.4.5, eclipse CDT Juno, MinGW error 0xc0000005

After many trials and errors I decided to follow this tutorial and to compile my own binaries as it seems that too many people are complaining that precompiled binaries are NOT working for them. Eclipse CDT Juno was already installed.

My procedure was as follows:

  1. Download and install MinGW and add to the system PATH with c:/mingw/bin
  2. Download cmake from http://www.cmake.org and install it
  3. Download OpenCV2.4.5 Windows version
  4. Install/unzip Opencv to C:\OpenCV245PC\ (README,index.rst and CMakeLists.txt are there with all subfolders)
  5. Run CMake GUI tool, then
  6. Choose C:\OpenCV245PC\ as source
  7. Choose the destination, C:\OpenCV245MinGW\x86 where to build the binaries
  8. Press Configure button, choose MinGW Makefiles as the generator. There are some red highlights in the window, choose options as you need.
  9. Press the Configure button again. Configuring is now done.
  10. Press the Generate button.
  11. Exit the program when the generating is done.
  12. Exit the Cmake program.
  13. Run the command line mode (cmd.exe) and go to the destination directory C:\OpenCV245MinGW\x86
  14. Type "mingw32-make". You will see a progress of building binaries. If the command is not found, you must make sure that the system PATH is added with c:/mingw/bin. The build continues according the chosen options to a completion.
  15. In Windows system PATH (My Computer > Right button click > Properties > Advanced > Environment Variables > Path) add the destination's bin directory, C:\OpenCV245MinGW\x86\bin
  16. RESTART COMPUTER
  17. Go to the Eclipse CDT IDE, create a C++ program using the sample OpenCV code (You can use code from top of this topic).
  18. Go to Project > Properties > C/C++ Build > Settings > GCC C++ Compiler > Includes, and add the source OpenCV folder "C:\OpenCV245PC\build\include"
  19. Go to Project > Properties > C/C++ Build > Settings > MinGW C++ Linker > Libraries, and add to the Libraries (-l) ONE BY ONE (this could vary from project to project, you can add all of them if you like or some of them just the ones that you need for your project): opencv_calib3d245 opencv_contrib245 opencv_core245 opencv_features2d245 opencv_flann245 opencv_gpu245 opencv_highgui245 opencv_imgproc245 opencv_legacy245 opencv_ml245 opencv_nonfree245 opencv_objdetect245 opencv_photo245 opencv_stitching245 opencv_video245 opencv_videostab245
  20. Add the built OpenCV library folder, "C:\OpenCV245MinGW\x86\lib" to Library search path (-L).

You can use this code to test your setup:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main()
{

Mat img = imread("c:/lenna.png", CV_LOAD_IMAGE_COLOR);

namedWindow("MyWindow", CV_WINDOW_AUTOSIZE);
imshow("MyWindow", img);

waitKey(0);
return 0;
}

Don't forget to put image to the C:/ (or wherever you might find suitable, just be sure that eclipse have read acess.

Passing argument to alias in bash

An alias will expand to the string it represents. Anything after the alias will appear after its expansion without needing to be or able to be passed as explicit arguments (e.g. $1).

$ alias foo='/path/to/bar'
$ foo some args

will get expanded to

$ /path/to/bar some args

If you want to use explicit arguments, you'll need to use a function

$ foo () { /path/to/bar "$@" fixed args; }
$ foo abc 123

will be executed as if you had done

$ /path/to/bar abc 123 fixed args

To undefine an alias:

unalias foo

To undefine a function:

unset -f foo

To see the type and definition (for each defined alias, keyword, function, builtin or executable file):

type -a foo

Or type only (for the highest precedence occurrence):

type -t foo

How to reset the use/password of jenkins on windows?

This is for windows environment:

I got the Initial Admin password under C:\Users\Deepak("MyUser").jenkins\secrets\initialAdminPassword

I was able to login with user "admin" and above password. Then under Jenkins> people I edited the password of the user and clicked on apply to reflect the changes.

How to remove carriage returns and new lines in Postgresql?

In the case you need to remove line breaks from the begin or end of the string, you may use this:

UPDATE table 
SET field = regexp_replace(field, E'(^[\\n\\r]+)|([\\n\\r]+$)', '', 'g' );

Have in mind that the hat ^ means the begin of the string and the dollar sign $ means the end of the string.

Hope it help someone.

'Field required a bean of type that could not be found.' error spring restful API using mongodb

I followed all steps and instructions followed by OP here, took care of blank space around username and password(even though spring takes care of whitespaces in properties file), still was either facing

could not find bean for ___Repository

(you interface which extends JPARepository)

OR after adding @EnableJPARepository

could not find bean for EntityManagerFactory

i solved it by changing spring boot starter parent version from 2.3.2 to 2.2.1 in pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.1.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

and adding following dependency

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

I did not need to add any of following, spring boot does it itself

  1. @EnableJPAReposity - since i already had all class with same root package
  2. spring.data.jpa.repositories.enabled in application.properties
  3. spring.datasource.driverClassName=com.mysql.jdbc.Driver in application properties