Programs & Examples On #Mime types

A MIME type after MIME (Multipurpose Internet Mail Extensions) is a two-part identifier for file formats on the Internet.

Proper MIME type for .woff2 fonts

font/woff2

For nginx add the following to the mime.types file:

font/woff2 woff2;


Old Answer

The mime type (sometime written as mimetype) for WOFF2 fonts has been proposed as application/font-woff2.

Also, if you refer to the spec (http://dev.w3.org/webfonts/WOFF2/spec/) you will see that font/woff2 is being discussed. I suspect that the filal mime type for all fonts will eventually be the more logical font/* (font/ttf, font/woff2 etc)...

N.B. WOFF2 is still in 'Working Draft' status -- not yet adopted officially.

When to use the JavaScript MIME type application/javascript instead of text/javascript?

In theory, according to RFC 4329, application/javascript.

The reason it is supposed to be application is not anything to do with whether the type is readable or executable. It's because there are custom charset-determination mechanisms laid down by the language/type itself, rather than just the generic charset parameter. A subtype of text should be capable of being transcoded by a proxy to another charset, changing the charset parameter. This is not true of JavaScript because:

a. the RFC says user-agents should be doing BOM-sniffing on the script to determine type (I'm not sure if any browsers actually do this though);

b. browsers use other information—the including page's encoding and in some browsers the script charset attribute—to determine the charset. So any proxy that tried to transcode the resource would break its users. (Of course in reality no-one ever uses transcoding proxies anyway, but that was the intent.)

Therefore the exact bytes of the file must be preserved exactly, which makes it a binary application type and not technically character-based text.

For the same reason, application/xml is officially preferred over text/xml: XML has its own in-band charset signalling mechanisms. And everyone ignores application for XML, too.

text/javascript and text/xml may not be the official Right Thing, but there are what everyone uses today for compatibility reasons, and the reasons why they're not the right thing are practically speaking completely unimportant.

Add MIME mapping in web.config for IIS Express

I know this is an old question, but...

I was just noticing my instance of IISExpress wasn't serving woff files, so I wen't searching (Found this) and then found:

http://www.tomasmcguinness.com/2011/07/06/adding-support-for-svg-to-iis-express/

I suppose my install has support for SVG since I haven't had issue with that. But the instructions are trivially modifiable for woff:

  • Open a console application with administrator privilages.
  • Navigation to the IIS Express directory. This lives under Program Files or Program Files (x86)
  • Run the command:

    appcmd set config /section:staticContent /+[fileExtension='woff',mimeType='application/x-woff']

Solved my problem, and I didn't have to mess with some crummy config (like I had to to add support for the PUT and DELETE verbs). Yay!

Interface/enum listing standard mime-type constants

There is now also the class org.apache.http.entity.ContentType from package org.apache.httpcomponents.httpcore, starting from 4.2 up.

What is correct content-type for excel files?

Do keep in mind that the file.getContentType could also output application/octet-stream instead of the required application/vnd.openxmlformats-officedocument.spreadsheetml.sheet when you try to upload the file that is already open.

.rar, .zip files MIME Type

As extension might contain more or less that three characters the following will test for an extension regardless of the length of it.

Try this:

$allowedExtensions = array( 'mkv', 'mp3', 'flac' );

$temp = explode(".", $_FILES[$file]["name"]);
$extension = strtolower(end($temp));

if( in_array( $extension, $allowedExtensions ) ) { ///

to check for all characters after the last '.'

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

Check your js files actually exist on the server. I had this problem and discovered the js files hadn't been uploaded to the server and the server was actually returning the html page instead - which was the default document configured on the server (eg default.html)

Using .NET, how can you find the mime type of a file based on the file signature not the extension

I ended up using Winista MimeDetector from Netomatix. The sources can be downloaded for free after you created an account: http://www.netomatix.com/Products/DocumentManagement/MimeDetector.aspx

MimeTypes g_MimeTypes = new MimeTypes("mime-types.xml");
sbyte [] fileData = null;

using (System.IO.FileStream srcFile = new System.IO.FileStream(strFile, System.IO.FileMode.Open))
{
    byte [] data = new byte[srcFile.Length];
    srcFile.Read(data, 0, (Int32)srcFile.Length);
    fileData = Winista.Mime.SupportUtil.ToSByteArray(data);
}

MimeType oMimeType = g_MimeTypes.GetMimeType(fileData);

This is part of another question answered here: Alternative to FindMimeFromData method in Urlmon.dll one which has more MIME types The best solution to this problem in my opinion.

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

For those it might help, I use this list as a reference to define my content-type when I have to deal with images on my app.

It says that jpg extension can be declared with Content-type : image/jpeg

There isn't any image/jpg attribute for content-type.

How to determine MIME type of file in android?

Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
                        File file = new File(filePatch); 
                        Uri uris = Uri.fromFile(file);
                        String mimetype = null;
                        if 
(uris.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
                            ContentResolver cr = 
getApplicationContext().getContentResolver();
                            mimetype = cr.getType(uris);
                        } else {
                            String fileExtension = 
MimeTypeMap.getFileExtensionFromUrl(uris.toString());
mimetype =  MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());
                        }

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.

What Content-Type value should I send for my XML sitemap?

As a rule of thumb, the safest bet towards making your document be treated properly by all web servers, proxies, and client browsers, is probably the following:

  1. Use the application/xml content type
  2. Include a character encoding in the content type, probably UTF-8
  3. Include a matching character encoding in the encoding attribute of the XML document itself.

In terms of the RFC 3023 spec, which some browsers fail to implement properly, the major difference in the content types is in how clients are supposed to treat the character encoding, as follows:

For application/xml, application/xml-dtd, application/xml-external-parsed-entity, or any one of the subtypes of application/xml such as application/atom+xml, application/rss+xml or application/rdf+xml, the character encoding is determined in this order:

  1. the encoding given in the charset parameter of the Content-Type HTTP header
  2. the encoding given in the encoding attribute of the XML declaration within the document,
  3. utf-8.

For text/xml, text/xml-external-parsed-entity, or a subtype like text/foo+xml, the encoding attribute of the XML declaration within the document is ignored, and the character encoding is:

  1. the encoding given in the charset parameter of the Content-Type HTTP header, or
  2. us-ascii.

Most parsers don't implement the spec; they ignore the HTTP Context-Type and just use the encoding in the document. With so many ill-formed documents out there, that's unlikely to change any time soon.

What does "Content-type: application/json; charset=utf-8" really mean?

To substantiate @deceze's claim that the default JSON encoding is UTF-8...

From IETF RFC4627:

JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.

Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets.

      00 00 00 xx  UTF-32BE
      00 xx 00 xx  UTF-16BE
      xx 00 00 00  UTF-32LE
      xx 00 xx 00  UTF-16LE
      xx xx xx xx  UTF-8

Stylesheet not loaded because of MIME-type

Adding to a long list of answers, this issue also happened to me because I did not realize the path was wrong from a browser-sync point of view.

Given this simple folder structure:

package.json
app
  |-index.html
  |-styles
      |-style.css

the href attribute inside <link> in index.html has to be app/styles/style.css and not styles/style.css

File input 'accept' attribute - is it useful?

Yes, it is extremely useful in browsers that support it, but the "limiting" is as a convenience to users (so they are not overwhelmed with irrelevant files) rather than as a way to prevent them from uploading things you don't want them uploading.

It is supported in

  • Chrome 16 +
  • Safari 6 +
  • Firefox 9 +
  • IE 10 +
  • Opera 11 +

Here is a list of content types you can use with it, followed by the corresponding file extensions (though of course you can use any file extension):

application/envoy   evy
application/fractals    fif
application/futuresplash    spl
application/hta hta
application/internet-property-stream    acx
application/mac-binhex40    hqx
application/msword  doc
application/msword  dot
application/octet-stream    *
application/octet-stream    bin
application/octet-stream    class
application/octet-stream    dms
application/octet-stream    exe
application/octet-stream    lha
application/octet-stream    lzh
application/oda oda
application/olescript   axs
application/pdf pdf
application/pics-rules  prf
application/pkcs10  p10
application/pkix-crl    crl
application/postscript  ai
application/postscript  eps
application/postscript  ps
application/rtf rtf
application/set-payment-initiation  setpay
application/set-registration-initiation setreg
application/vnd.ms-excel    xla
application/vnd.ms-excel    xlc
application/vnd.ms-excel    xlm
application/vnd.ms-excel    xls
application/vnd.ms-excel    xlt
application/vnd.ms-excel    xlw
application/vnd.ms-outlook  msg
application/vnd.ms-pkicertstore sst
application/vnd.ms-pkiseccat    cat
application/vnd.ms-pkistl   stl
application/vnd.ms-powerpoint   pot
application/vnd.ms-powerpoint   pps
application/vnd.ms-powerpoint   ppt
application/vnd.ms-project  mpp
application/vnd.ms-works    wcm
application/vnd.ms-works    wdb
application/vnd.ms-works    wks
application/vnd.ms-works    wps
application/winhlp  hlp
application/x-bcpio bcpio
application/x-cdf   cdf
application/x-compress  z
application/x-compressed    tgz
application/x-cpio  cpio
application/x-csh   csh
application/x-director  dcr
application/x-director  dir
application/x-director  dxr
application/x-dvi   dvi
application/x-gtar  gtar
application/x-gzip  gz
application/x-hdf   hdf
application/x-internet-signup   ins
application/x-internet-signup   isp
application/x-iphone    iii
application/x-javascript    js
application/x-latex latex
application/x-msaccess  mdb
application/x-mscardfile    crd
application/x-msclip    clp
application/x-msdownload    dll
application/x-msmediaview   m13
application/x-msmediaview   m14
application/x-msmediaview   mvb
application/x-msmetafile    wmf
application/x-msmoney   mny
application/x-mspublisher   pub
application/x-msschedule    scd
application/x-msterminal    trm
application/x-mswrite   wri
application/x-netcdf    cdf
application/x-netcdf    nc
application/x-perfmon   pma
application/x-perfmon   pmc
application/x-perfmon   pml
application/x-perfmon   pmr
application/x-perfmon   pmw
application/x-pkcs12    p12
application/x-pkcs12    pfx
application/x-pkcs7-certificates    p7b
application/x-pkcs7-certificates    spc
application/x-pkcs7-certreqresp p7r
application/x-pkcs7-mime    p7c
application/x-pkcs7-mime    p7m
application/x-pkcs7-signature   p7s
application/x-sh    sh
application/x-shar  shar
application/x-shockwave-flash   swf
application/x-stuffit   sit
application/x-sv4cpio   sv4cpio
application/x-sv4crc    sv4crc
application/x-tar   tar
application/x-tcl   tcl
application/x-tex   tex
application/x-texinfo   texi
application/x-texinfo   texinfo
application/x-troff roff
application/x-troff t
application/x-troff tr
application/x-troff-man man
application/x-troff-me  me
application/x-troff-ms  ms
application/x-ustar ustar
application/x-wais-source   src
application/x-x509-ca-cert  cer
application/x-x509-ca-cert  crt
application/x-x509-ca-cert  der
application/ynd.ms-pkipko   pko
application/zip zip
audio/basic au
audio/basic snd
audio/mid   mid
audio/mid   rmi
audio/mpeg  mp3
audio/x-aiff    aif
audio/x-aiff    aifc
audio/x-aiff    aiff
audio/x-mpegurl m3u
audio/x-pn-realaudio    ra
audio/x-pn-realaudio    ram
audio/x-wav wav
image/bmp   bmp
image/cis-cod   cod
image/gif   gif
image/ief   ief
image/jpeg  jpe
image/jpeg  jpeg
image/jpeg  jpg
image/pipeg jfif
image/svg+xml   svg
image/tiff  tif
image/tiff  tiff
image/x-cmu-raster  ras
image/x-cmx cmx
image/x-icon    ico
image/x-portable-anymap pnm
image/x-portable-bitmap pbm
image/x-portable-graymap    pgm
image/x-portable-pixmap ppm
image/x-rgb rgb
image/x-xbitmap xbm
image/x-xpixmap xpm
image/x-xwindowdump xwd
message/rfc822  mht
message/rfc822  mhtml
message/rfc822  nws
text/css    css
text/h323   323
text/html   htm
text/html   html
text/html   stm
text/iuls   uls
text/plain  bas
text/plain  c
text/plain  h
text/plain  txt
text/richtext   rtx
text/scriptlet  sct
text/tab-separated-values   tsv
text/webviewhtml    htt
text/x-component    htc
text/x-setext   etx
text/x-vcard    vcf
video/mpeg  mp2
video/mpeg  mpa
video/mpeg  mpe
video/mpeg  mpeg
video/mpeg  mpg
video/mpeg  mpv2
video/quicktime mov
video/quicktime qt
video/x-la-asf  lsf
video/x-la-asf  lsx
video/x-ms-asf  asf
video/x-ms-asf  asr
video/x-ms-asf  asx
video/x-msvideo avi
video/x-sgi-movie   movie
x-world/x-vrml  flr
x-world/x-vrml  vrml
x-world/x-vrml  wrl
x-world/x-vrml  wrz
x-world/x-vrml  xaf
x-world/x-vrml  xof

How to set MimeBodyPart ContentType to "text/html"?

For me, I set two times:

(MimeBodyPart)messageBodyPart.setContent(content, text/html)
(Multipart)multipart.addBodyPart(messageBodyPart)
(MimeMessage)msg.setContent(multipart, text/html)

and its been working fine.

What is a correct MIME type for .docx, .pptx, etc.?

Alternatively, if you're working in .NET v4.5 or above, try using System.Web.MimeMapping.GetMimeMapping(yourFileName) to get MIME types. It is much better than hard-coding strings.

How to check file MIME type with javascript before upload?

This is what you have to do

var fileVariable =document.getElementsById('fileId').files[0];

If you want to check for image file types then

if(fileVariable.type.match('image.*'))
{
 alert('its an image');
}

HTTP Error 404.3-Not Found in IIS 7.5

In my case, along with Mekanik's suggestions, I was receiving this error in Windows Server 2012 and I had to tick "HTTP Activation" in "Add Role Services".

Correct MIME Type for favicon.ico?

When you're serving an .ico file to be used as a favicon, it doesn't matter. All major browsers recognize both mime types correctly. So you could put:

<!-- IE -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<!-- other browsers -->
<link rel="icon" type="image/x-icon" href="favicon.ico" />

or the same with image/vnd.microsoft.icon, and it will work with all browsers.

Note: There is no IANA specification for the MIME-type image/x-icon, so it does appear that it is a little more unofficial than image/vnd.microsoft.icon.

The only case in which there is a difference is if you were trying to use an .ico file in an <img> tag (which is pretty unusual). Based on previous testing, some browsers would only display .ico files as images when they were served with the MIME-type image/x-icon. More recent tests show: Chromium, Firefox and Edge are fine with both content types, IE11 is not. If you can, just avoid using ico files as images, use png.

Debug message "Resource interpreted as other but transferred with MIME type application/javascript"

I found out that the naming of my css files was in conflict with the proxy filters

www.dating.com (which is not my site) was blocked and my css and js files were called dating.css and dating.js. The filter was blocking this. Maybe that is the case with some of you, working on corporates systems.

Why write <script type="text/javascript"> when the mime type is set by the server?

It allows browsers to determine if they can handle the scripting/style language before making a request for the script or stylesheet (or, in the case of embedded script/style, identify which language is being used).

This would be much more important if there had been more competition among languages in browser space, but VBScript never made it beyond IE and PerlScript never made it beyond an IE specific plugin while JSSS was pretty rubbish to begin with.

The draft of HTML5 makes the attribute optional.

What MIME type should I use for CSV?

You should use "text/csv" according to RFC 4180.

Which mime type should I use for mp3

I had a problem with mime types and where making tests for few file types. It looks like each browser sends it's variation of a mime type for a specific file. I was trying to upload mp3 and zip files with open source php class, that what I have found:

  • Firefox (mp3): audio/mpeg
  • Firefox (zip): application/zip
  • Chrome (mp3): audio/mp3
  • Chrome (zip): application/octet-stream
  • Opera (mp3): audio/mp3
  • Opera (zip): application/octet-stream
  • IE (mp3): audio/mpeg
  • IE (zip): application/x-zip-compressed

So if you need several file types to upload, you better make some tests so that every browser could upload a file and pass mime type check.

Which MIME type to use for a binary file that's specific to my program?

mimetype headers are recognised by the browser for the purpose of a (fast) possible identifying a handler to use the downloaded file as target, for example, PDF would be downloaded and your Adobe Reader program would be executed with the path of the PDF file as an argument,

If your needs are to write a browser extension to handle your downloaded file, through your operation-system, or you simply want to make you project a more 'professional looking' go ahead and select a unique mimetype for you to use, it would make no difference since the operation-system would have no handle to open it with (some browsers has few bundled-plugins, for example new Google Chrome versions has a built-in PDF-reader),

if you want to make sure the file would be downloaded have a look at this answer: https://stackoverflow.com/a/34758866/257319

if you want to make your file type especially organised, it might be worth adding a few letters in the first few bytes of the file, for example, every JPG has this at it's file start:

if you can afford a jump of 4 or 8 bytes it could be very helpful for you in the rest of the way

:)

What is a MIME type?

A MIME type is a label used to identify a type of data. It is used so software can know how to handle the data. It serves the same purpose on the Internet that file extensions do on Microsoft Windows.

So if a server says "This is text/html" the client can go "Ah, this is an HTML document, I can render that internally", while if the server says "This is application/pdf" the client can go "Ah, I need to launch the FoxIt PDF Reader plugin that the user has installed and that has registered itself as the application/pdf handler."

You'll most commonly find them in the headers of HTTP messages (to describe the content that an HTTP server is responding with or the formatting of the data that is being POSTed in a request) and in email headers (to describe the message format and attachments).

How can I find out a file's MIME type (Content-Type)?

Use file. Examples:

> file --mime-type image.png
image.png: image/png

> file -b --mime-type image.png
image/png

> file -i FILE_NAME
image.png: image/png; charset=binary

Correct mime type for .mp4

video/mp4should be used when you have video content in your file. If there is none, but there is audio, you should use audio/mp4. If no audio and no video is used, for instance if the file contains only a subtitle track or a metadata track, the MIME should be application/mp4. Also, as a server, you should try to include the codecs or profiles parameters as defined in RFC6381, as this will help clients determine if they can play the file, prior to downloading it.

Print Combining Strings and Numbers

The other answers explain how to produce a string formatted like in your example, but if all you need to do is to print that stuff you could simply write:

first = 10
second = 20
print "First number is", first, "and second number is", second

Using ls to list directories and their total sizes

place in init script like .bashrc ... adjust def as needed.

duh() {
  # shows disk utilization for a path and depth level
  path="${1:-$PWD}"
  level="${2:-0}"
  du "$path" -h --max-depth="$level"
}

MySQL Delete all rows from table and reset ID to zero

If table has foreign keys then I always use following code:

SET FOREIGN_KEY_CHECKS = 0; -- disable a foreign keys check
SET AUTOCOMMIT = 0; -- disable autocommit
START TRANSACTION; -- begin transaction

/*
DELETE FROM table_name;
ALTER TABLE table_name AUTO_INCREMENT = 1;
-- or
TRUNCATE table_name;
-- or
DROP TABLE table_name;
CREATE TABLE table_name ( ... );
*/

SET FOREIGN_KEY_CHECKS = 1; -- enable a foreign keys check
COMMIT;  -- make a commit
SET AUTOCOMMIT = 1 ;

But difference will be in execution time. Look at above Sorin's answer.

Where is Python language used?

Your categorization is not correct:

php, asp and ColdFusion are mostly used for websites, that is correct, but .net is definetly much more than asp you can build desktop applications, too (Paint.NET). I don't know about ColdFusion, but PHP can also be used to write desktop applications.

On the other hand C,C++ are not really often used for web programming, But it can be used for web programming (cgit). Java is definetly a language to develop web applications (spring and much more).

Python is a scripting language like PHP, Perl, Ruby and so much more. It can be used for web programming (django, Zope, Google App Engine, and much more). But it also can be used for desktop applications (Blender 3D, or even for games pygame).

Python can also be translated into binary code like java.

scale Image in an UIButton to AspectFit?

The cleanest solution is to use Auto Layout. I lowered Content Compression Resistance Priority of my UIButton and set the image (not Background Image) via Interface Builder. After that I added a couple of constraints that define size of my button (quite complex in my case) and it worked like a charm.

How do I use Ruby for shell scripting?

In ruby, the constant __FILE__ will always give you the path of the script you're running.

On Linux, /usr/bin/env is your friend:

#! /usr/bin/env ruby
# Extension of this script does not matter as long
# as it is executable (chmod +x)
puts File.expand_path(__FILE__)

On Windows it depends whether or not .rb files are associated with ruby. If they are:

# This script filename must end with .rb
puts File.expand_path(__FILE__)

If they are not, you have to explicitly invoke ruby on them, I use a intermediate .cmd file:

my_script.cmd:

@ruby %~dp0\my_script.rb

my_script.rb:

puts File.expand_path(__FILE__)

Storage permission error in Marshmallow

Seems user has declined the permission and app tries to write to external disk, causing error.

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

Check https://developer.android.com/training/permissions/requesting.html

This video will give you a better idea about UX, handling Runtime permissions https://www.youtube.com/watch?v=iZqDdvhTZj0

Truncating a table in a stored procedure

try the below code

execute immediate 'truncate table tablename' ;

How to setup Main class in manifest file in jar produced by NetBeans project

In 7.3 just enable Properties/Build/Package/Copy Dependent Libraries and main class will be added to manifest when building depending on selected target.

Reading a simple text file

This is how I do it:

public static String readFromAssets(Context context, String filename) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(filename)));

    // do reading, usually loop until end of file reading  
    StringBuilder sb = new StringBuilder();
    String mLine = reader.readLine();
    while (mLine != null) {
        sb.append(mLine); // process line
        mLine = reader.readLine();
    }
    reader.close();
    return sb.toString();
}

use it as follows:

readFromAssets(context,"test.txt")

Calculating width from percent to pixel then minus by pixel in LESS CSS

I think width: -moz-calc(25% - 1em); is what you are looking for. And you may want to give this Link a look for any further assistance

Login to website, via C#

Matthew Brindley, your code worked very good for some website I needed (with login), but I needed to change to HttpWebRequest and HttpWebResponse otherwise I get a 404 Bad Request from the remote server. Also I would like to share my workaround using your code, and is that I tried it to login to a website based on moodle, but it didn't work at your step "GETting the page behind the login form" because when successfully POSTing the login, the Header 'Set-Cookie' didn't return anything despite other websites does.

So I think this where we need to store cookies for next Requests, so I added this.


To the "POSTing to the login form" code block :

var cookies = new CookieContainer();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(formUrl);
req.CookieContainer = cookies;


And To the "GETting the page behind the login form" :

HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(resp.Cookies);
getRequest.Headers.Add("Cookie", cookieHeader);


Doing this, lets me Log me in and get the source code of the "page behind login" (website based moodle) I know this is a vague use of the CookieContainer and HTTPCookies because we may ask first is there a previously set of cookies saved before sending the request to the server. This works without problem anyway, but here's a good info to read about WebRequest and WebResponse with sample projects and tutorial:
Retrieving HTTP content in .NET
How to use HttpWebRequest and HttpWebResponse in .NET

SQL Server : export query as a .txt file

Another way is from command line, using the osql:

OSQL -S SERVERNAME -E -i thequeryfile.sql -o youroutputfile.txt

This can be used from a BAT file and shceduled by a windows user to authenticated.

Compiling and Running Java Code in Sublime Text 2

I am using Windows 7. The below solution works for me!!

**Open** the file JavaC.sublime-build and replace all the code in the file with the code below:

{
 "cmd": ["javac", "$file_name","&&","java", "$file_base_name"],
 "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
 **"path": "C:\\Program Files\\Java\\jdk1.6.0\\bin\\",**
 "selector": "source.java",
 "shell": true
 }

Remember to replace "C:\Program Files\Java\jdk1.6.0\bin\" with the path where you put your jdk. And make sure to add the path of you java JDK to the environment variable "PATH". Refer to bunnyDrug's post to set up the environment variable. Best!!

Post an object as data using Jquery Ajax

[object Object] This means somewhere the object is being converted to a string.

Converted to a string:

//Copy and paste in the browser console to see result

var product = {'name':'test'};
JSON.stringify(product + ''); 

Not converted to a string:

//Copy and paste in the browser console to see result

var product = {'name':'test'};
JSON.stringify(product);

Bootstrap 3 Flush footer to bottom. not fixed

None of these solutions exactly worked for me perfectly because I used navbar-inverse class in my footer. But I did get a solution that worked and Javascript-free. Used Chrome to aid in forming media queries. The height of the footer changes as the screen resizes so you have to pay attention to that and adjust accordingly. Your footer content (I set id="footer" to define my content) should use postion=absolute and bottom=0 to keep it at the bottom. Also width:100%. Here is my CSS with media queries. You'll have to adjust min-width and max-width and add or remove some elements:

#footer {
  position: absolute;
  color:  #ffffff;
  width: 100%;
  bottom: 0; 
}
@media only screen and (min-width:1px) and (max-width: 407px)  {
    body {
        margin-bottom: 275px;
    }

    #footer {
        height: 270px; 
    }
}
@media only screen and (min-width:408px) and (max-width: 768px)  {
    body {
        margin-bottom: 245px;
    }

    #footer {
        height: 240px; 
    }
}
@media only screen and (min-width:769px)   {
    body {
        margin-bottom: 125px;
    }

    #footer {
        height: 120px; 
    }
}

Reverse Contents in Array

First of all what value do you have in this pice of code? int temp;? You can't tell because in every single compilation it will have different value - you should initialize your value to not have trash value from memory. Next question is: why you assign this temp value to your array? If you want to stick with your solution I would change reverse function like this:

void reverse(int arr[], int count)
{
    int temp = 0;
    for (int i = 0; i < count/2; ++i)
    {
        temp = arr[count - i - 1];
        arr[count - i - 1] = arr[i];
        arr[i] = temp;
    }

    for (int i = 0; i < count; ++i)
    {
        std::cout << arr[i] << " ";
    }
}

Now it will works but you have other options to handle this problem.

Solution using pointers:

void reverse(int arr[], int count)
{
    int* head = arr;
    int* tail = arr + count - 1;
    for (int i = 0; i < count/2; ++i)
    {
        if (head < tail)
        {
            int tmp = *tail;
            *tail = *head;
            *head = tmp;

            head++; tail--;
        }
    }

    for (int i = 0; i < count; ++i)
    {
        std::cout << arr[i] << " ";
    }
}

And ofc like Carlos Abraham says use build in function in algorithm library

Use Fieldset Legend with bootstrap

That's because Bootstrap by default sets the width of the legend element to 100%. You can fix this by changing your legend.scheduler-border to also use:

legend.scheduler-border {
    width:inherit; /* Or auto */
    padding:0 10px; /* To give a bit of padding on the left and right */
    border-bottom:none;
}

JSFiddle example.

You'll also need to ensure your custom stylesheet is being added after Bootstrap to prevent Bootstrap overriding your styling - although your styles here should have higher specificity.

You may also want to add margin-bottom:0; to it as well to reduce the gap between the legend and the divider.

Script parameters in Bash

I needed to make sure that my scripts are entirely portable between various machines, shells and even cygwin versions. Further, my colleagues who were the ones I had to write the scripts for, are programmers, so I ended up using this:

for ((i=1;i<=$#;i++)); 
do

    if [ ${!i} = "-s" ] 
    then ((i++)) 
        var1=${!i};

    elif [ ${!i} = "-log" ];
    then ((i++)) 
        logFile=${!i};  

    elif [ ${!i} = "-x" ];
    then ((i++)) 
        var2=${!i};    

    elif [ ${!i} = "-p" ]; 
    then ((i++)) 
        var3=${!i};

    elif [ ${!i} = "-b" ];
    then ((i++)) 
        var4=${!i};

    elif [ ${!i} = "-l" ];
    then ((i++)) 
        var5=${!i}; 

    elif [ ${!i} = "-a" ];
    then ((i++)) 
        var6=${!i};
    fi

done;

Rationale: I included a launcher.sh script as well, since the whole operation had several steps which were quasi independent on each other (I'm saying "quasi", because even though each script could be run on its own, they were usually all run together), and in two days I found out, that about half of my colleagues, being programmers and all, were too good to be using the launcher file, follow the "usage", or read the HELP which was displayed every time they did something wrong and they were making a mess of the whole thing, running scripts with arguments in the wrong order and complaining that the scripts didn't work properly. Being the choleric I am I decided to overhaul all my scripts to make sure that they are colleague-proof. The code segment above was the first thing.

Text not wrapping in p tag

Word wrapping only occurs when there is a word break.

If you have a "word" that is as long as that, then there is no place for it to break.

The proper solution is to write real content and not nonsense strings of characters. If you are using user generated content, then add a check for exceptionally long words and disallow them (or cut out part of them for URLs while keeping the whole thing in a link).

Alternatively, you can use the word-break CSS property to tell the browser to line break in the middle of words.

p { word-break: break-all }

(Note browser support).

Alternatively, you can use overflow to truncate the text if it won't fit in the container.

Windows ignores JAVA_HOME: how to set JDK as default?

I had Java 7 and 8 installed and I want to redirect to java 7 but the java version in my cmd prompt window shows Java 8.
Added Java 7 bin directory path (C:\Program Files\Java\jdk1.7.0_10\bin) to PATH variable at the end, but did not work out and shows Java 8. So I changed the Java 7 path to the starting of the path value and it worked.
Opened a new cmd prompt window and checked my java version and now it shows Java 7

Convert date time string to epoch in Bash

get_curr_date () {
    # get unix time
    DATE=$(date +%s)
    echo "DATE_CURR : "$DATE
}

conv_utime_hread () {
    # convert unix time to human readable format
    DATE_HREAD=$(date -d @$DATE +%Y%m%d_%H%M%S)
    echo "DATE_HREAD          : "$DATE_HREAD
}

Multi-character constant warnings

This warning is useful for programmers that would mistakenly write 'test' where they should have written "test".

This happen much more often than programmers that do actually want multi-char int constants.

Changing cursor to waiting in javascript/jquery

A colleague suggested an approach that I find preferable to the chosen solution here. First, in CSS, add this rule:

body.waiting * {
    cursor: progress;
}

Then, to turn on the progress cursor, say:

$('body').addClass('waiting');

and to turn off the progress cursor, say:

$('body').removeClass('waiting');

The advantage of this approach is that when you turn off the progress cursor, whatever other cursors may have been defined in your CSS will be restored. If the CSS rule is not powerful enough in precedence to overrule other CSS rules, you can add an id to the body and to the rule, or use !important.

Creating/writing into a new file in Qt

That is weird, everything looks fine, are you sure it does not work for you? Because this main surely works for me, so I would look somewhere else for the source of your problem.

#include <QFile>
#include <QTextStream>


int main()
{
    QString filename = "Data.txt";
    QFile file(filename);
    if (file.open(QIODevice::ReadWrite)) {
        QTextStream stream(&file);
        stream << "something" << endl;
    }
}

The code you provided is also almost the same as the one provided in detailed description of QTextStream so I am pretty sure, that the problem is elsewhere :)

Also note, that the file is not called Data but Data.txt and should be created/located in the directory from which the program was run (not necessarily the one where the executable is located).

What is the difference between dict.items() and dict.iteritems() in Python2?

dict.items() returns a list of 2-tuples ([(key, value), (key, value), ...]), whereas dict.iteritems() is a generator that yields 2-tuples. The former takes more space and time initially, but accessing each element is fast, whereas the second takes less space and time initially, but a bit more time in generating each element.

Change window location Jquery

If you want to use the back button, check this out. https://stackoverflow.com/questions/116446/what-is-the-best-back-button-jquery-plugin

Use document.location.href to change the page location, place it in the function on a successful ajax run.

Styling Form with Label above Inputs

There is no need to add any extra div wrapper as others suggest.

The simplest way is to wrap your input element inside a related label tag and set input style to display:block.

Bonus point earned: now you don't need to set the labels for attribute. Because every label target the nested input.

<form name="message" method="post">
    <section>
        <label class="left">
            Name
            <input id="name" type="text" name="name">
        </label>
        <label class="right">
            Email
            <input id="email" type="text" name="email">
        </label>
    </section>
</form>

https://jsfiddle.net/Tomanek1/sguh5k17/15/

Given a URL to a text file, what is the simplest way to read the contents of the text file?

There's really no need to read line-by-line. You can get the whole thing like this:

import urllib
txt = urllib.urlopen(target_url).read()

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

1) in a query window in SQL Server Management Studio, run the command:

SET SHOWPLAN_ALL ON

2) run your slow query

3) your query will not run, but the execution plan will be returned. store this output

4) run your fast version of the query

5) your query will not run, but the execution plan will be returned. store this output

6) compare the slow query version output to the fast query version output.

7) if you still don't know why one is slower, post both outputs in your question (edit it) and someone here can help from there.

python pandas: apply a function with arguments to a series

Newer versions of pandas do allow you to pass extra arguments (see the new documentation). So now you can do:

my_series.apply(your_function, args=(2,3,4), extra_kw=1)

The positional arguments are added after the element of the series.


For older version of pandas:

The documentation explains this clearly. The apply method accepts a python function which should have a single parameter. If you want to pass more parameters you should use functools.partial as suggested by Joel Cornett in his comment.

An example:

>>> import functools
>>> import operator
>>> add_3 = functools.partial(operator.add,3)
>>> add_3(2)
5
>>> add_3(7)
10

You can also pass keyword arguments using partial.

Another way would be to create a lambda:

my_series.apply((lambda x: your_func(a,b,c,d,...,x)))

But I think using partial is better.

Using iFrames In ASP.NET

You can think of an iframe as an embedded browser window that you can put on an HTML page to show another URL inside it. This URL can be totally distinct from your web site/app.

You can put an iframe in any HTML page, so you could put one inside a contentplaceholder in a webform that has a Masterpage and it will appear with whatever URL you load into it (via Javascript, or C# if you turn your iframe into a server-side control (runat='server') on the final HTML page that your webform produces when requested.

And you can load a URL into your iframe that is a .aspx page.

But - iframes have nothing to do with the ASP.net mechanism. They are HTML elements that can be made to run server-side, but they are essentially 'dumb' and unmanaged/unconnected to the ASP.Net mechanisms - don't confuse a Contentplaceholder with an iframe.

Incidentally, the use of iframes is still contentious - do you really need to use one? Can you afford the negative trade-offs associated with them e.g. lack of navigation history ...?

Could not create the Java virtual machine

Just be careful. You will get this message if you try to enter a command that doesn't exist like this

/usr/bin/java -v

Ellipsis for overflow text in dropdown boxes

If you are finding this question because you have a custom arrow on your select box and the text is going over your arrow, I found a solution that works in some browsers. Just add some padding, to the select, on the right side.

Before:

enter image description here

After:

enter image description here

CSS:

select {
    padding:0 30px 0 10px !important;
    -webkit-padding-end: 30px !important;
    -webkit-padding-start: 10px !important;
}

iOS ignores the padding properties but uses the -webkit- properties instead.

http://jsfiddle.net/T7ST2/4/

Checking if a folder exists using a .bat file

I think the answer is here (possibly duplicate):

How to test if a file is a directory in a batch script?

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

Log4j, configuring a Web App to use a relative path

My solution is similar to Iker Jimenez's solution, but instead of using System.setProperty(...) I use org.apache.log4j.PropertyConfigurator.configure(Properties). For that I also need log4j to be unable to find its configuration on its own and I load it manually (both points described in Wolfgang Liebich's answer).

This works for Jetty and Tomcat, standalone or run from IDE, requires zero configuration, allows to put each app's logs in their own folder, no matter how many apps inside the container (which is the problem with the System-based solution). This way one can also put the log4j config file anywhere inside the web app (e.g. in one project we had all config files inside WEB-INF/).

Details:

  1. I have my properties in the log4j-no-autoload.properties file in the classpath (e.g. in my Maven project it's originally in src/main/resources, gets packaged into WEB-INF/classes),
  2. It has the file appender configured as e.g.:

    log4j.appender.MyAppFileAppender = org.apache.log4j.FileAppender
    log4j.appender.MyAppFileAppender.file = ${webAppRoot}/WEB-INF/logs/my-app.log
    ...
    
  3. And I have a context listener like this (gets much shorter with Java 7's "try-with-resource" syntax):

    @WebListener
    public class ContextListener implements ServletContextListener {
        @Override
        public void contextInitialized(final ServletContextEvent event) {
            Properties props = new Properties();
            InputStream strm =
                ContextListener.class.getClassLoader()
                    .getResourceAsStream("log4j-no-autoload.properties");
            try {
                props.load(strm);
            } catch (IOException propsLoadIOE) {
                throw new Error("can't load logging config file", propsLoadIOE);
            } finally {
                try {
                    strm.close();
                } catch (IOException configCloseIOE) {
                    throw new Error("error closing logging config file", configCloseIOE);
                }
            }
            props.put("webAppRoot", event.getServletContext().getRealPath("/"));
            PropertyConfigurator.configure(props);
            // from now on, I can use LoggerFactory.getLogger(...)
        }
        ...
    }
    

Why is list initialization (using curly braces) better than the alternatives?

There are already great answers about the advantages of using list initialization, however my personal rule of thumb is NOT to use curly braces whenever possible, but instead make it dependent on the conceptual meaning:

  • If the object I'm creating conceptually holds the values I'm passing in the constructor (e.g. containers, POD structs, atomics, smart pointers etc.), then I'm using the braces.
  • If the constructor resembles a normal function call (it performs some more or less complex operations that are parametrized by the arguments) then I'm using the normal function call syntax.
  • For default initialization I always use curly braces.
    For one, that way I'm always sure that the object gets initialized irrespective of whether it e.g. is a "real" class with a default constructor that would get called anyway or a builtin / POD type. Second it is - in most cases - consistent with the first rule, as a default initialized object often represents an "empty" object.

In my experience, this ruleset can be applied much more consistently than using curly braces by default, but having to explicitly remember all the exceptions when they can't be used or have a different meaning than the "normal" function-call syntax with parenthesis (calls a different overload).

It e.g. fits nicely with standard library-types like std::vector:

vector<int> a{10,20};   //Curly braces -> fills the vector with the arguments

vector<int> b(10,20);   //Parentheses -> uses arguments to parametrize some functionality,                          
vector<int> c(it1,it2); //like filling the vector with 10 integers or copying a range.

vector<int> d{};      //empty braces -> default constructs vector, which is equivalent
                      //to a vector that is filled with zero elements

Send POST request with JSON data using Volley

    final String url = "some/url";

instead of:

    final JSONObject jsonBody = "{\"type\":\"example\"}";

you can use:

  JSONObject jsonBody = new JSONObject();
    try {
        jsonBody.put("type", "my type");
    } catch (JSONException e) {
        e.printStackTrace();
    }
new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });

How to revert the last migration?

If you are facing trouble while reverting back the migration, and somehow have messed it, you can perform fake migrations.

./manage.py migrate <name> --ignore-ghost-migrations --merge --fake

For django version < 1.7 this will create entry in south_migrationhistory table, you need to delete that entry.

Now you'll be able to revert back the migration easily.

PS: I was stuck for a lot of time and performing fake migration and then reverting back helped me out.

How do I open the "front camera" on the Android platform?

All older answers' methods are deprecated by Google (supposedly because of troubles like this), since API 21 you need to use the Camera 2 API:

This class was deprecated in API level 21. We recommend using the new android.hardware.camera2 API for new applications.

In the newer API you have almost complete power over the Android device camera and documentation explicitly advice to

String[] getCameraIdList()

and then use obtained CameraId to open the camera:

void openCamera(String cameraId, CameraDevice.StateCallback callback, Handler handler)

99% of the frontal cameras have id = "1", and the back camera id = "0" according to this:

Non-removable cameras use integers starting at 0 for their identifiers, while removable cameras have a unique identifier for each individual device, even if they are the same model.

However, this means if device situation is rare like just 1-frontal -camera tablet you need to count how many embedded cameras you have, and place the order of the camera by its importance ("0"). So CAMERA_FACING_FRONT == 1 CAMERA_FACING_BACK == 0, which implies that the back camera is more important than frontal.

I don't know about a uniform method to identify the frontal camera on all Android devices. Simply said, the Android OS inside the device can't really find out which camera is exactly where for some reasons: maybe the only camera hardcoded id is an integer representing its importance or maybe on some devices whichever side you turn will be .. "back".

Documentation: https://developer.android.com/reference/android/hardware/camera2/package-summary.html

Explicit Examples: https://github.com/googlesamples/android-Camera2Basic


For the older API (it is not recommended, because it will not work on modern phones newer Android version and transfer is a pain-in-the-arse). Just use the same Integer CameraID (1) to open frontal camera like in this answer:

cam = Camera.open(1);

If you trust OpenCV to do the camera part:

Inside

    <org.opencv.android.JavaCameraView
    ../>

use the following for the frontal camera:

        opencv:camera_id="1"

How to present popover properly in iOS 8

I found a complete example of how to get this all to work so that you can always display a popover no matter the device/orientation https://github.com/frogcjn/AdaptivePopover_iOS8_Swift.

The key is to implement UIAdaptivePresentationControllerDelegate

func adaptivePresentationStyleForPresentationController(PC: UIPresentationController!) -> UIModalPresentationStyle {
    // This *forces* a popover to be displayed on the iPhone
    return .None
}

Then extend the example above (from Imagine Digital):

nav.popoverPresentationController!.delegate = implOfUIAPCDelegate

Customize the Authorization HTTP header

This is a bit dated but there may be others looking for answers to the same question. You should think about what protection spaces make sense for your APIs. For example, you may want to identify and authenticate client application access to your APIs to restrict their use to known, registered client applications. In this case, you can use the Basic authentication scheme with the client identifier as the user-id and client shared secret as the password. You don't need proprietary authentication schemes just clearly identify the one(s) to be used by clients for each protection space. I prefer only one for each protection space but the HTTP standards allow both multiple authentication schemes on each WWW-Authenticate header response and multiple WWW-Authenticate headers in each response; this will be confusing for API clients which options to use. Be consistent and clear then your APIs will be used.

How do I delete everything in Redis?

Open redis-cli and type:

FLUSHALL

Redirecting from HTTP to HTTPS with PHP

This is a good way to do it:

<?php
if (!(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || 
   $_SERVER['HTTPS'] == 1) ||  
   isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&   
   $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))
{
   $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
   header('HTTP/1.1 301 Moved Permanently');
   header('Location: ' . $redirect);
   exit();
}
?>

How to catch a specific SqlException error?

If you are looking for a better way to handle SQLException, there are a couple things you could do. First, Spring.NET does something similar to what you are looking for (I think). Here is a link to what they are doing:

http://springframework.net/docs/1.2.0/reference/html/dao.html

Also, instead of looking at the message, you could check the error code (sqlEx.Number). That would seem to be a better way of identifying which error occurred. The only problem is that the error number returned might be different for each database provider. If you plan to switch providers, you will be back to handling it the way you are or creating an abstraction layer that translates this information for you.

Here is an example of a guy who used the error code and a config file to translate and localize user-friendly error messages:

https://web.archive.org/web/20130731181042/http://weblogs.asp.net/guys/archive/2005/05/20/408142.aspx

Using FileSystemWatcher to monitor a directory

You did not supply the file handling code, but I assume you made the same mistake everyone does when first writing such a thing: the filewatcher event will be raised as soon as the file is created. However, it will take some time for the file to be finished. Take a file size of 1 GB for example. The file may be created by another program (Explorer.exe copying it from somewhere) but it will take minutes to finish that process. The event is raised at creation time and you need to wait for the file to be ready to be copied.

You can wait for a file to be ready by using this function in a loop.

What's the difference between a Python module and a Python package?

A late answer, yet another definition:

A package is represented by an imported top-entity which could either be a self-contained module, or the __init__.py special module as the top-entity from a set of modules within a sub directory structure.

So physically a package is a distribution unit, which provides one or more modules.

Convert list of ints to one number?

def magic(number):
    return int(''.join(str(i) for i in number))

Assign width to half available screen width declaratively

give width as 0dp to make sure its size is exactly as per its weight this will make sure that even if content of child views get bigger, they'll still be limited to exactly half(according to is weight)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1"
     >

    <Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="click me"
    android:layout_weight="0.5"/>


    <TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Hello World"
    android:layout_weight="0.5"/>
  </LinearLayout>

How to get Time from DateTime format in SQL?

select cast (as time(0))

would be a good clause. For example:

(select cast(start_date as time(0))) AS 'START TIME'

How to copy a collection from one database to another in MongoDB

This can be done using Mongo's db.copyDatabase method:

db.copyDatabase(fromdb, todb, fromhost, username, password)

Reference: http://docs.mongodb.org/manual/reference/method/db.copyDatabase/

How to resolve "Error: bad index – Fatal: index file corrupt" when using Git

You may have accidentally corrupted the .git/index file with a sed on your project root (refactoring perhaps?) with something like:

sed -ri -e "s/$SEACHPATTERN/$REPLACEMENTTEXT/g" $(grep -Elr "$SEARCHPATERN" "$PROJECTROOT")

to avoid this in the future, just ignore binary files with your grep/sed:

sed -ri -e "s/$SEACHPATTERN/$REPLACEMENTTEXT/g" $(grep -Elr --binary-files=without-match "$SEARCHPATERN" "$PROJECTROOT")

Using C# to read/write Excel files (.xls/.xlsx)

**Reading the Excel File:**

string filePath = @"d:\MyExcel.xlsx";
Excel.Application xlApp = new Excel.Application();  
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(filePath);  
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);  

Excel.Range xlRange = xlWorkSheet.UsedRange;  
int totalRows = xlRange.Rows.Count;  
int totalColumns = xlRange.Columns.Count;  

string firstValue, secondValue;   
for (int rowCount = 1; rowCount <= totalRows; rowCount++)  
{  
    firstValue = Convert.ToString((xlRange.Cells[rowCount, 1] as Excel.Range).Text);  
    secondValue = Convert.ToString((xlRange.Cells[rowCount, 2] as Excel.Range).Text);  
    Console.WriteLine(firstValue + "\t" + secondValue);  
}  
xlWorkBook.Close();  
xlApp.Quit(); 


**Writting the Excel File:**

Excel.Application xlApp = new Excel.Application();
object misValue = System.Reflection.Missing.Value;  

Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);  
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);  

xlWorkSheet.Cells[1, 1] = "ID";  
xlWorkSheet.Cells[1, 2] = "Name";  
xlWorkSheet.Cells[2, 1] = "100";  
xlWorkSheet.Cells[2, 2] = "John";  
xlWorkSheet.Cells[3, 1] = "101";  
xlWorkSheet.Cells[3, 2] = "Herry";  

xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue,  
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);  



xlWorkBook.Close();  
xlApp.Quit();  

The zip() function in Python 3

The zip() function in Python 3 returns an iterator. That is the reason why when you print test1 you get - <zip object at 0x1007a06c8>. From documentation -

Make an iterator that aggregates elements from each of the iterables.

But once you do - list(test1) - you have exhausted the iterator. So after that anytime you do list(test1) would only result in empty list.

In case of test2, you have already created the list once, test2 is a list, and hence it will always be that list.

Print debugging info from stored procedure in MySQL

One workaround is just to use select without any other clauses.

http://lists.mysql.com/mysql/197901

How to dynamically add rows to a table in ASP.NET?

You need to use JavaScript in your HTML and make sure you are using forms so that. You may finally serialize the data using Ajax method to push the data from HTML into database

How to change a Git remote on Heroku

If you're working on the heroku remote (default):

heroku git:remote -a [app name]

If you want to specify a different remote, use the -r argument:

heroku git:remote -a [app name] -r [remote] 

EDIT: thanks to ??????? ???????? For pointing it out that there's no need to delete the old remote.

HTML table headers always visible at top of window when viewing a large table

The most simple answer only using CSS :D !!!

_x000D_
_x000D_
table {_x000D_
  /* Not required only for visualizing */_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
table thead tr th {_x000D_
  /* you could also change td instead th depending your html code */_x000D_
  background-color: green;_x000D_
  position: sticky;_x000D_
  z-index: 100;_x000D_
  top: 0;_x000D_
}_x000D_
_x000D_
td {_x000D_
  /* Not required only for visualizing */_x000D_
  padding: 1em;_x000D_
}
_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Col1</th>_x000D_
      <th>Col2</th>_x000D_
      <th>Col3</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
       <td>data</td>_x000D_
     </tr>_x000D_
     <tr>_x000D_
       <td>david</td>_x000D_
       <td>castro</td>_x000D_
       <td>rocks!</td>_x000D_
     </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Implementing autocomplete

I know you already have several answers, but I was on a similar situation where my team didn't want to depend on a heavy libraries or anything related to bootstrap since we are using material so I made our own autocomplete control, using material-like styles, you can use my autocomplete or at least you can give a look to give you some guiadance, there was not much documentation on simple examples on how to upload your components to be shared on NPM.

Cannot set property 'innerHTML' of null

I have had the same problem and it turns out that the null error was because I had not saved the html I was working with.

If the element referred to has not been saved once the page is loaded is 'null', because the document does not contain it at the time of load. Using window.onload also helps debugging.

I hope this was useful to you.

How to use an arraylist as a prepared statement parameter

You may want to use setArray method as mentioned in the javadoc below:

http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setArray(int, java.sql.Array)

Sample Code:

PreparedStatement pstmt = 
                conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", new Object[]{"1", "2","3"});
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();

Getting the SQL from a Django QuerySet

This middleware will output every SQL query to your console, with color highlighting and execution time, it's been invaluable for me in optimizing some tricky requests

http://djangosnippets.org/snippets/290/

How to use a TRIM function in SQL Server

TRIM all SPACE's TAB's and ENTER's:

DECLARE @Str VARCHAR(MAX) = '      
          [         Foo    ]       
          '

DECLARE @NewStr VARCHAR(MAX) = ''
DECLARE @WhiteChars VARCHAR(4) =
      CHAR(13) + CHAR(10) -- ENTER
    + CHAR(9) -- TAB
    + ' ' -- SPACE

;WITH Split(Chr, Pos) AS (
    SELECT
          SUBSTRING(@Str, 1, 1) AS Chr
        , 1 AS Pos
    UNION ALL
    SELECT
          SUBSTRING(@Str, Pos, 1) AS Chr
        , Pos + 1 AS Pos
    FROM Split
    WHERE Pos <= LEN(@Str)
)
SELECT @NewStr = @NewStr + Chr
FROM Split
WHERE
    Pos >= (
        SELECT MIN(Pos)
        FROM Split
        WHERE CHARINDEX(Chr, @WhiteChars) = 0
    )
    AND Pos <= (
        SELECT MAX(Pos)
        FROM Split
        WHERE CHARINDEX(Chr, @WhiteChars) = 0
    )

SELECT '"' + @NewStr + '"'

As Function

CREATE FUNCTION StrTrim(@Str VARCHAR(MAX)) RETURNS VARCHAR(MAX) BEGIN
    DECLARE @NewStr VARCHAR(MAX) = NULL

    IF (@Str IS NOT NULL) BEGIN
        SET @NewStr = ''

        DECLARE @WhiteChars VARCHAR(4) =
              CHAR(13) + CHAR(10) -- ENTER
            + CHAR(9) -- TAB
            + ' ' -- SPACE

        IF (@Str LIKE ('%[' + @WhiteChars + ']%')) BEGIN

            ;WITH Split(Chr, Pos) AS (
                SELECT
                      SUBSTRING(@Str, 1, 1) AS Chr
                    , 1 AS Pos
                UNION ALL
                SELECT
                      SUBSTRING(@Str, Pos, 1) AS Chr
                    , Pos + 1 AS Pos
                FROM Split
                WHERE Pos <= LEN(@Str)
            )
            SELECT @NewStr = @NewStr + Chr
            FROM Split
            WHERE
                Pos >= (
                    SELECT MIN(Pos)
                    FROM Split
                    WHERE CHARINDEX(Chr, @WhiteChars) = 0
                )
                AND Pos <= (
                    SELECT MAX(Pos)
                    FROM Split
                    WHERE CHARINDEX(Chr, @WhiteChars) = 0
                )
        END
    END

    RETURN @NewStr
END

Example

-- Test
DECLARE @Str VARCHAR(MAX) = '      
          [         Foo    ]       
              '

SELECT 'Str', '"' + dbo.StrTrim(@Str) + '"'
UNION SELECT 'EMPTY', '"' + dbo.StrTrim('') + '"'
UNION SELECT 'EMTPY', '"' + dbo.StrTrim('      ') + '"'
UNION SELECT 'NULL', '"' + dbo.StrTrim(NULL) + '"'

Result

+-------+----------------+
| Test  | Result         |
+-------+----------------+
| EMPTY | ""             |
| EMTPY | ""             |
| NULL  | NULL           |
| Str   | "[   Foo    ]" |
+-------+----------------+

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

What is lazy loading in Hibernate?

Surprisingly, none of answers talk about how it is achieved by hibernate behind the screens.

Lazy loading is a design pattern that is effectively used in hibernate for performance reasons which involves following techniques.


1. Byte code instrumentation:

Enhances the base class definition with hibernate hooks to intercept all the calls to that entity object.

Done either at compile time or run[load] time

1.1 Compile time

  • Post compile time operation

  • Mostly by maven/ant plugins

1.2 Run time

  • If no compile time instrumentation is done, this is created at run time Using libraries like javassist

2. Proxies

The entity object that Hibernate returns are proxy of the real type.

See also: Javassist. What is the main idea and where real use?

Toggle input disabled attribute using jQuery

Quite a while later, and thanks to @arne, I created this similar small function to handle where the input should be disabled AND hidden, or enabled AND shown:

function toggleInputState(el, on) {
  // 'on' = true(visible) or false(hidden)
  // If a field is to be shown, enable it; if hidden, disable it.
  // Disabling will prevent the field's value from being submitted
  $(el).prop('disabled', !on).toggle(on);
}

Then a jQuery object (such as $('input[name="something"]') ) is simply switched using:

toggleInputState(myElement, myBoolean)

'do...while' vs. 'while'

I am programming about 12 years and only 3 months ago I have met a situation where it was really convenient to use do-while as one iteration was always necessary before checking a condition. So guess your big-time is ahead :).

What is VanillaJS?

There's no difference at all, VanillaJS is just a way to refer to native (non-extended and standards-based) JavaScript. Generally speaking it's a term of contrast when using libraries and frameworks like jQuery and React. Website www.vanilla-js.com lays emphasis on it as a joke, by talking 'bout VanillaJS as though it were a fast, lightweight, and cross-platform framework. That muddies the waters! Thus, it can be a little philosophical question: "how many things do I compile to Vanilla JavaScript without being VanillaJS themselves?" So, a mere guideline for that is: if you can write the code and run it in any current web-browser without additional tools or so called compile steps, it might be VanillaJS.

How do I apply a perspective transform to a UIView?

You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.

Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

You can use a user defined type containing an array of strings which will be the inner array. Then you can use an array of this user defined type as your outer array.

Have a look at the following test project:

'1 form with:
'  command button: name=Command1
'  command button: name=Command2
Option Explicit

Private Type MyArray
  strInner() As String
End Type

Private mudtOuter() As MyArray

Private Sub Command1_Click()
  'change the dimensens of the outer array, and fill the extra elements with "1"
  Dim intOuter As Integer
  Dim intInner As Integer
  Dim intOldOuter As Integer
  intOldOuter = UBound(mudtOuter)
  ReDim Preserve mudtOuter(intOldOuter + 2) As MyArray
  For intOuter = intOldOuter + 1 To UBound(mudtOuter)
    ReDim mudtOuter(intOuter).strInner(intOuter) As String
    For intInner = 0 To UBound(mudtOuter(intOuter).strInner)
      mudtOuter(intOuter).strInner(intInner) = "1"
    Next intInner
  Next intOuter
End Sub

Private Sub Command2_Click()
  'change the dimensions of the middle inner array, and fill the extra elements with "2"
  Dim intOuter As Integer
  Dim intInner As Integer
  Dim intOldInner As Integer
  intOuter = UBound(mudtOuter) / 2
  intOldInner = UBound(mudtOuter(intOuter).strInner)
  ReDim Preserve mudtOuter(intOuter).strInner(intOldInner + 5) As String
  For intInner = intOldInner + 1 To UBound(mudtOuter(intOuter).strInner)
    mudtOuter(intOuter).strInner(intInner) = "2"
  Next intInner
End Sub

Private Sub Form_Click()
  'clear the form and print the outer,inner arrays
  Dim intOuter As Integer
  Dim intInner As Integer
  Cls
  For intOuter = 0 To UBound(mudtOuter)
    For intInner = 0 To UBound(mudtOuter(intOuter).strInner)
      Print CStr(intOuter) & "," & CStr(intInner) & " = " & mudtOuter(intOuter).strInner(intInner)
    Next intInner
    Print "" 'add an empty line between the outer array elements
  Next intOuter
End Sub

Private Sub Form_Load()
  'init the arrays
  Dim intOuter As Integer
  Dim intInner As Integer
  ReDim mudtOuter(5) As MyArray
  For intOuter = 0 To UBound(mudtOuter)
    ReDim mudtOuter(intOuter).strInner(intOuter) As String
    For intInner = 0 To UBound(mudtOuter(intOuter).strInner)
      mudtOuter(intOuter).strInner(intInner) = CStr((intOuter + 1) * (intInner + 1))
    Next intInner
  Next intOuter
  WindowState = vbMaximized
End Sub

Run the project, and click on the form to display the contents of the arrays.

Click on Command1 to enlarge the outer array, and click on the form again to show the results.

Click on Command2 to enlarge an inner array, and click on the form again to show the results.

Be careful though: when you redim the outer array, you also have to redim the inner arrays for all the new elements of the outer array

Change button text from Xcode?

myapp.h

{
UIButton *myButton;
}
@property (nonatomic,retain)IBoutlet UIButton *myButton;

myapp.m

@synthesize myButton;

-(IBAction)buttonTitle{
[myButton setTitle:@"Play" forState:UIControlStateNormal];
}

The import android.support cannot be resolved

Android Studio 2.2.3 Linux Mint 18.1

Inside your 'project view' open Gradle Scripts -> build.gradle(Module:app) and put your mouse pointer inside the word dependencies.

Click on the light bulb and click "add library dependency" and for me all the libraries I wanted were listed there.

example libraries that came up for me: compile 'com.android.support:gridlayout-v7:25.1.0' compile 'com.android.support:support-v13:25.1.0'

I am now looking to add android support by default in Gradles default configuration.

Where is the Microsoft.IdentityModel dll

I had a similar problem. I got an exception "Type is not resolved for member 'Microsoft.IdentityModel.Claims.ClaimsPrincipal, Microsoft.IdentityModel, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35'.".

I tried to run the ASP.NET application from Visual Studio, which was a reference to a local copy of Microsoft.IdentityModel.dll.

I did not want to install the SDK and I had to copy the library to the directory "C: \ Program Files \ Common Files \ Microsoft Shared \ DevServer \ 10.0" and restart Visual Studio.

Getting value of HTML text input

Yes, you can use jQuery to make this done, the idea is

Use a hidden value in your form, and copy the value from external text box to this hidden value just before submitting the form.

<form name="input" action="handle_email.php" method="post">
  <input type="hidden" name="email" id="email" />
  <input type="submit" value="Submit" />
</form> 

<script>
   $("form").submit(function() {
     var emailFromOtherTextBox = $("#email_textbox").val();
     $("#email").val(emailFromOtherTextBox ); 
     return true;
  });
</script>

also see http://api.jquery.com/submit/

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

This is what solved my problem
Add the following line to WebApiConfig.cs

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

Set variable in jinja

Nice shorthand for Multiple variable assignments

{% set label_cls, field_cls = "col-md-7", "col-md-3" %}

Using wire or reg with input or output in Verilog

seeing it in digital circuit domain

  1. A Wire will create a wire output which can only be assigned any input by using assign statement as assign statement creates a port/pin connection and wire can be joined to the port/pin
  2. A reg will create a register(D FLIP FLOP ) which gets or recieve inputs on basis of sensitivity list either it can be clock (rising or falling ) or combinational edge .

so it completely depends on your use whether you need to create a register and tick it according to sensitivity list or you want to create a port/pin assignment

Get selected element's outer HTML

2014 Edit : The question and this reply are from 2010. At the time, no better solution was widely available. Now, many of the other replies are better : Eric Hu's, or Re Capcha's for example.

This site seems to have a solution for you : jQuery: outerHTML | Yelotofu

jQuery.fn.outerHTML = function(s) {
    return s
        ? this.before(s).remove()
        : jQuery("<p>").append(this.eq(0).clone()).html();
};

How do I use Apache tomcat 7 built in Host Manager gui?

Just a note that all the above may not work for you with tomcat7 unless you've also done this:

sudo apt-get install tomcat7-admin

How to get a value of an element by name instead of ID

Only one thing more: when you´re using the "crasis variable assignment" you need to use double cotes too AND you do not need to use the "input" word!:

valInput  = $(`[name="${inputNameHere}"]`).val();

What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

Html.Label - Just creates a label tag with whatever the string passed into the constructor is

Html.LabelFor - Creates a label for that specific property. This is strongly typed. By default, this will just do the name of the property (in the below example, it'll output MyProperty if that Display attribute wasn't there). Another benefit of this is you can set the display property in your model and that's what will be put here:

public class MyModel
{
    [Display(Name="My property title")
    public class MyProperty{get;set;}
}

In your view:

Html.LabelFor(x => x.MyProperty) //Outputs My property title

In the above, LabelFor will display <label for="MyProperty">My property title</label>. This works nicely so you can define in one place what the label for that property will be and have it show everywhere.

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

Add JSTL library as dependency to your project (javax.servlet.jsp.jstl.core.Config is a part of this package). For example, if you were using Gradle, you could write in a build.gradle:

dependencies {
    compile 'javax.servlet:jstl:1.2'
}

how to compare two string dates in javascript?

If your date is not in format standar yyyy-mm-dd (2017-02-06) for example 20/06/2016. You can use this code

var parts ='01/07/2016'.val().split('/');
var d1 = Number(parts[2] + parts[1] + parts[0]);
parts ='20/06/2016'.val().split('/');
var d2 = Number(parts[2] + parts[1] + parts[0]);
return d1 > d2

Making an array of integers in iOS

If you want to use a NSArray, you need an Objective-C class to put in it - hence the NSNumber requirement.

That said, Obj-C is still C, so you can use regular C arrays and hold regular ints instead of NSNumbers if you need to.

How to specify maven's distributionManagement organisation wide?

There's no need for a parent POM.

You can omit the distributionManagement part entirely in your poms and set it either on your build server or in settings.xml.

To do it on the build server, just pass to the mvn command:

-DaltSnapshotDeploymentRepository=snapshots::default::https://YOUR_NEXUS_URL/snapshots
-DaltReleaseDeploymentRepository=releases::default::https://YOUR_NEXUS_URL/releases

See https://maven.apache.org/plugins/maven-deploy-plugin/deploy-mojo.html for details which options can be set.

It's also possible to set this in your settings.xml.

Just create a profile there which is enabled and contains the property.

Example settings.xml:

<settings>
[...]
  <profiles>
    <profile>
      <id>nexus</id>
      <properties>
        <altSnapshotDeploymentRepository>snapshots::default::https://YOUR_NEXUS_URL/snapshots</altSnapshotDeploymentRepository>
        <altReleaseDeploymentRepository>releases::default::https://YOUR_NEXUS_URL/releases</altReleaseDeploymentRepository>
      </properties>
    </profile>
  </profiles>

  <activeProfiles>
    <activeProfile>nexus</activeProfile>
  </activeProfiles>

</settings>

Make sure that credentials for "snapshots" and "releases" are in the <servers> section of your settings.xml

The properties altSnapshotDeploymentRepository and altReleaseDeploymentRepository are introduced with maven-deploy-plugin version 2.8. Older versions will fail with the error message

Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter

To fix this, you can enforce a newer version of the plug-in:

        <build>
          <pluginManagement>
            <plugins>
              <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8</version>
              </plugin>
            </plugins>
          </pluginManagement>
        </build>

R - " missing value where TRUE/FALSE needed "

check the command : NA!=NA : you'll get the result NA, hence the error message.

You have to use the function is.na for your ifstatement to work (in general, it is always better to use this function to check for NA values) :

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

Google Play app description formatting

As a matter of fact, HTML character entites also work : http://www.w3.org/TR/html4/sgml/entities.html.

It lets you insert special characters like bullets '•' (&bull;), '™' (&trade;), ... the HTML way.

Note that you can also (and probably should) type special characters directly in the form fields if you can enter international characters.

=> one consideration here is whether or not you care about third-party sites that collect data on your app from Google Play : some might simply take it as HTML content, others might insert it in a native application that just understand plain Unicode...

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

I find this to be the most efficient for finding if a value exists, logic can easily be inverted to find if a value doesn't exist (ie IS NULL);

SELECT * FROM primary_table st1
LEFT JOIN comparision_table st2 ON (st1.relevant_field = st2.relevant_field)
WHERE st2.primaryKey IS NOT NULL

*Replace relevant_field with the name of the value that you want to check exists in your table

*Replace primaryKey with the name of the primary key column on the comparison table.

How to extract custom header value in Web API message handler?

request.Headers.FirstOrDefault( x => x.Key == "MyCustomID" ).Value.FirstOrDefault()

modern variant :)

__init__ and arguments in Python

In python you must always pass in at least one argument to class methods, the argument is self and it is not meaningless its a reference to the instance itself

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

Thank you all for this thread! My colleague and I just discovered that the default_value property is a Constant, not a Variable.

In other React forms I've built, the default value for a Select was preset in an associated Context. So the first time the Select was rendered, default_value was set to the correct value.

But in my latest React form (a small modal), I'm passing the values for the form as props and then using a useEffect to populate the associated Context. So the FIRST time the Select is rendered, default_value is set to null. Then when the Context is populated and the Select is supposed to be re-rendered, default_value cannot be changed and thus the initial default value is not set.

The solution was ultimately simple: Use the value property instead. But figuring out why default_value didn't work like it did with my other forms took some time.

I'm posting this to help others in the community.

Meaning of $? (dollar question mark) in shell scripts

See The Bash Manual under 3.4.2 Special Parameters:

? - Expands to the exit status of the most recently executed foreground pipeline.

It is a little hard to find because it is not listed as $? (the variable name is "just" ?). Also see the exit status section, of course ;-)

Happy coding.

Vagrant ssh authentication failure

If you are using default SSH setup in your VagrantFile and started seeing SSH authentication errors after re-associating your VM box due to crash, try replacing public key in your vagrant machine.

Vagrant replaces public key associated with insecure private key pair at each log out due to security reasons. If you didn't properly shut down your machine, public/private key pair can go out of sync, causing SSH authentication error.

To resolve this issue, simply load up the current insecure private key and then copy the public key pair into your VM's authorized_keys file.

Parse an URL in JavaScript

function parse_url(str, component) {
  //       discuss at: http://phpjs.org/functions/parse_url/
  //      original by: Steven Levithan (http://blog.stevenlevithan.com)
  // reimplemented by: Brett Zamir (http://brett-zamir.me)
  //         input by: Lorenzo Pisani
  //         input by: Tony
  //      improved by: Brett Zamir (http://brett-zamir.me)
  //             note: original by http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
  //             note: blog post at http://blog.stevenlevithan.com/archives/parseuri
  //             note: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
  //             note: Does not replace invalid characters with '_' as in PHP, nor does it return false with
  //             note: a seriously malformed URL.
  //             note: Besides function name, is essentially the same as parseUri as well as our allowing
  //             note: an extra slash after the scheme/protocol (to allow file:/// as in PHP)
  //        example 1: parse_url('http://username:password@hostname/path?arg=value#anchor');
  //        returns 1: {scheme: 'http', host: 'hostname', user: 'username', pass: 'password', path: '/path', query: 'arg=value', fragment: 'anchor'}

  var query, key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port',
      'relative', 'path', 'directory', 'file', 'query', 'fragment'
    ],
    ini = (this.php_js && this.php_js.ini) || {},
    mode = (ini['phpjs.parse_url.mode'] &&
      ini['phpjs.parse_url.mode'].local_value) || 'php',
    parser = {
      php: /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
      strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
      loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // Added one optional slash to post-scheme to catch file:/// (should restrict this)
    };

  var m = parser[mode].exec(str),
    uri = {},
    i = 14;
  while (i--) {
    if (m[i]) {
      uri[key[i]] = m[i];
    }
  }

  if (component) {
    return uri[component.replace('PHP_URL_', '')
      .toLowerCase()];
  }
  if (mode !== 'php') {
    var name = (ini['phpjs.parse_url.queryKey'] &&
      ini['phpjs.parse_url.queryKey'].local_value) || 'queryKey';
    parser = /(?:^|&)([^&=]*)=?([^&]*)/g;
    uri[name] = {};
    query = uri[key[12]] || '';
    query.replace(parser, function($0, $1, $2) {
      if ($1) {
        uri[name][$1] = $2;
      }
    });
  }
  delete uri.source;
  return uri;
}

reference

Is there a cross-domain iframe height auto-resizer that works?

I found another server side solution for web dev using PHP to get the size of an iframe.

First is using server script PHP to an external call via internal function: (like a file_get_contents with but curl and dom).

function curl_get_file_contents($url,$proxyActivation=false) {
    global $proxy;
    $c = curl_init();
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($c, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7");
    curl_setopt($c, CURLOPT_REFERER, $url);
    curl_setopt($c, CURLOPT_URL, $url);
    curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
    if($proxyActivation) {
        curl_setopt($c, CURLOPT_PROXY, $proxy);
    }
    $contents = curl_exec($c);
    curl_close($c);
    $dom = new DOMDocument();
    $dom->preserveWhiteSpace = false;
    @$dom->loadHTML($contents);
    $form = $dom->getElementsByTagName("body")->item(0);
    if ($contents) //si on a du contenu
        return $dom->saveHTML();
    else
        return FALSE;
}
$url = "http://www.google.com"; //Exernal url test to iframe
<html>
    <head>
    <script type="text/javascript">

    </script>
    <style type="text/css">
    #iframe_reserve {
        width: 560px;
        height: 228px
    }
    </style>
    </head>

    <body>
        <div id="iframe_reserve"><?php echo curl_get_file_contents($url); ?></div>

        <iframe id="myiframe" src="http://www.google.com" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"  style="overflow:none; width:100%; display:none"></iframe>

        <script type="text/javascript">
            window.onload = function(){
            document.getElementById("iframe_reserve").style.display = "block";
            var divHeight = document.getElementById("iframe_reserve").clientHeight;
            document.getElementById("iframe_reserve").style.display = "none";
            document.getElementById("myiframe").style.display = "block";
            document.getElementById("myiframe").style.height = divHeight;
            alert(divHeight);
            };
        </script>
    </body>
</html>

You need to display under the div (iframe_reserve) the html generated by the function call by using a simple echo curl_get_file_contents("location url iframe","activation proxy")

After doing this a body event function onload with javascript take height of the page iframe just with a simple control of the content div (iframe_reserve)

So I used divHeight = document.getElementById("iframe_reserve").clientHeight; to get height of the page external we are going to call after masked the div container (iframe_reserve). After this we load the iframe with its good height that's all.

Convert JSON String to Pretty Print JSON output using Jackson

You can achieve this using bellow ways:

1. Using Jackson from Apache

    String formattedData=new ObjectMapper().writerWithDefaultPrettyPrinter()
.writeValueAsString(YOUR_JSON_OBJECT);

Import bellow class:

import com.fasterxml.jackson.databind.ObjectMapper;

It's gradle dependency is :

compile 'com.fasterxml.jackson.core:jackson-core:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.3'

2. Using Gson from Google

String formattedData=new GsonBuilder().setPrettyPrinting()
    .create().toJson(YOUR_OBJECT);

Import bellow class:

import com.google.gson.Gson;

It's gradle is:

compile 'com.google.code.gson:gson:2.8.2'

Here, you can also download correct updated version from repository.

How to get everything after a certain character?

strtok is an overlooked function for this sort of thing. It is meant to be quite fast.

$s = '233718_This_is_a_string';
$firstPart = strtok( $s, '_' );
$allTheRest = strtok( '' ); 

Empty string like this will force the rest of the string to be returned.

NB if there was nothing at all after the '_' you would get a FALSE value for $allTheRest which, as stated in the documentation, must be tested with ===, to distinguish from other falsy values.

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

Gantt chart is wrong... First process P3 has arrived so it will execute first. Since the burst time of P3 is 3sec after the completion of P3, processes P2,P4, and P5 has been arrived. Among P2,P4, and P5 the shortest burst time is 1sec for P2, so P2 will execute next. Then P4 and P5. At last P1 will be executed.

Gantt chart for this ques will be:

| P3 | P2 | P4 | P5 | P1 |

1    4    5    7   11   14

Average waiting time=(0+2+2+3+3)/5=2

Average Turnaround time=(3+3+4+7+6)/5=4.6

Where can I get a list of Ansible pre-defined variables?

I know this question has been answered already, but I feel like there are a whole other set of pre-defined variables not covered by the ansible_* facts. This documentation page covers the directives (variables that modify Ansible's behavior), which I was looking for when I came across this page.

This includes some common and some specific use-case directives:

  • become: Controls privilege escalation (sudo)
  • delegate_to: run task on another host (like running on localhost)
  • serial: allows you to run a play across a specific number/percentage of hosts before moving onto next set

How to get last key in an array?

I prefer

end(array_keys($myarr))

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

I spent hours last night working out why my programmatically generated table crashed on [myTable setDataSource:self]; It was OK commenting out and popping up an empty table, but crashed every time I tried to reach the datasource;

I had the delegation set up in the h file: @interface myViewController : UIViewController

I had the data source code in my implementation and still BOOM!, crash every time! THANK YOU to "xxd" (nr 9): adding that line of code solved it for me! In fact I am launching a table from a IBAction button, so here is my full code:

    - (IBAction)tapButton:(id)sender {

    UIViewController* popoverContent = [[UIViewController alloc]init];

    UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 300)];
    popoverView.backgroundColor = [UIColor greenColor];
    popoverContent.view = popoverView;

    //Add the table
    UITableView *table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 200, 300)         style:UITableViewStylePlain];

   // NEXT THE LINE THAT SAVED MY SANITY Without it the program built OK, but crashed when      tapping the button!

    [table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    table.delegate=self;
    [table setDataSource:self];
    [popoverView addSubview:table];
    popoverContent.contentSizeForViewInPopover =
    CGSizeMake(200, 300);

    //create a popover controller
    popoverController3 = [[UIPopoverController alloc]
                          initWithContentViewController:popoverContent];
    CGRect popRect = CGRectMake(self.tapButton.frame.origin.x,
                                self.tapButton.frame.origin.y,
                                self.tapButton.frame.size.width,
                                self.tapButton.frame.size.height);


    [popoverController3 presentPopoverFromRect:popRect inView:self.view   permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];



   }


   #Table view data source in same m file

   - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
   {
    NSLog(@"Sections in table");
    // Return the number of sections.
    return 1;
   }

   - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
  {
    NSLog(@"Rows in table");

    // Return the number of rows in the section.
    return myArray.count;
   }

   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath    *)indexPath
    {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    NSString *myValue;

    //This is just some test array I created:
    myValue=[myArray objectAtIndex:indexPath.row];

    cell.textLabel.text=myValue;
    UIFont *myFont = [ UIFont fontWithName: @"Arial" size: 12.0 ];
    cell.textLabel.font  = myFont;

    return cell;
   }

By the way: the button must be linked up with as an IBAction and as a IBOutlet if you want to anchor the popover to it.

UIPopoverController *popoverController3 is declared in the H file directly after @interface between {}

'module' object has no attribute 'DataFrame'

I recieved a similar error:

AttributeError: module 'pandas' has no attribute 'DataFrame'

The cause of my error was that I ran pip install of pandas as root, and my user did not have permission to the directory.

My fix was to run:

sudo chmod -R 755 /usr/local/lib/python3.6/site-packages

What is a file with extension .a?

.a files are created with the ar utility, and they are libraries. To use it with gcc, collect all .a files in a lib/ folder and then link with -L lib/ and -l<name of specific library>.

Collection of all .a files into lib/ is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

Try this if you want to display one of duplicate rows based on RequestID and CreatedDate and show the latest HistoryStatus.

with t as (select row_number()over(partition by RequestID,CreatedDate order by RequestID) as rnum,* from tbltmp)
Select RequestID,CreatedDate,HistoryStatus from t a where  rnum in (SELECT Max(rnum) FROM t GROUP BY RequestID,CreatedDate having t.RequestID=a.RequestID)

or if you want to select one of duplicate rows considering CreatedDate only and show the latest HistoryStatus then try the query below.

with t as (select row_number()over(partition by CreatedDate order by RequestID) as rnum,* from tbltmp)
Select RequestID,CreatedDate,HistoryStatus from t  where  rnum = (SELECT Max(rnum) FROM t)

Or if you want to select one of duplicate rows considering Request ID only and show the latest HistoryStatus then use the query below

with t as (select row_number()over(partition by RequestID order by RequestID) as rnum,* from tbltmp)
Select RequestID,CreatedDate,HistoryStatus from t a where  rnum in (SELECT Max(rnum) FROM t GROUP BY RequestID,CreatedDate having t.RequestID=a.RequestID)

All the above queries I have written in sql server 2005.

Validating an XML against referenced XSD in C#

You need to create an XmlReaderSettings instance and pass that to your XmlReader when you create it. Then you can subscribe to the ValidationEventHandler in the settings to receive validation errors. Your code will end up looking like this:

using System.Xml;
using System.Xml.Schema;
using System.IO;

public class ValidXSD
{
    public static void Main()
    {

        // Set the validation settings.
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
        settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
        settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

        // Create the XmlReader object.
        XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);

        // Parse the file. 
        while (reader.Read()) ;

    }
    // Display any warnings or errors.
    private static void ValidationCallBack(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.WriteLine("\tWarning: Matching schema not found.  No validation occurred." + args.Message);
        else
            Console.WriteLine("\tValidation error: " + args.Message);

    }
}

MySQL update CASE WHEN/THEN/ELSE

Try this

UPDATE `table` SET `uid` = CASE
    WHEN id = 1 THEN 2952
    WHEN id = 2 THEN 4925
    WHEN id = 3 THEN 1592
    ELSE `uid`
    END
WHERE id  in (1,2,3)

Check if cookie exists else set cookie to Expire in 10 days

You need to read and write document.cookie

if (document.cookie.indexOf("visited=") >= 0) {
  // They've been here before.
  alert("hello again");
}
else {
  // set a new cookie
  expiry = new Date();
  expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes

  // Date()'s toGMTSting() method will format the date correctly for a cookie
  document.cookie = "visited=yes; expires=" + expiry.toGMTString();
  alert("this is your first time");
}

How to know if other threads have finished?

You should really prefer a solution that uses java.util.concurrent. Find and read Josh Bloch and/or Brian Goetz on the topic.

If you are not using java.util.concurrent.* and are taking responsibility for using Threads directly, then you should probably use join() to know when a thread is done. Here is a super simple Callback mechanism. First extend the Runnable interface to have a callback:

public interface CallbackRunnable extends Runnable {
    public void callback();
}

Then make an Executor that will execute your runnable and call you back when it is done.

public class CallbackExecutor implements Executor {

    @Override
    public void execute(final Runnable r) {
        final Thread runner = new Thread(r);
        runner.start();
        if ( r instanceof CallbackRunnable ) {
            // create a thread to perform the callback
            Thread callerbacker = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // block until the running thread is done
                        runner.join();
                        ((CallbackRunnable)r).callback();
                    }
                    catch ( InterruptedException e ) {
                        // someone doesn't want us running. ok, maybe we give up.
                    }
                }
            });
            callerbacker.start();
        }
    }

}

The other sort-of obvious thing to add to your CallbackRunnable interface is a means to handle any exceptions, so maybe put a public void uncaughtException(Throwable e); line in there and in your executor, install a Thread.UncaughtExceptionHandler to send you to that interface method.

But doing all that really starts to smell like java.util.concurrent.Callable. You should really look at using java.util.concurrent if your project permits it.

How to use Class<T> in Java?

You often want to use wildcards with Class. For instance, Class<? extends JComponent>, would allow you to specify that the class is some subclass of JComponent. If you've retrieved the Class instance from Class.forName, then you can use Class.asSubclass to do the cast before attempting to, say, construct an instance.

ToList().ForEach in Linq

employees.ToList().Foreach(u=> { u.SomeProperty = null; u.OtherProperty = null; });

Notice that I used semicolons after each set statement that is -->

u.SomeProperty = null;
u.OtherProperty = null;

I hope this will definitely solve your problem.

How can I split a string into segments of n characters?

Coming a little later to the discussion but here a variation that's a little faster than the substring + array push one.

// substring + array push + end precalc
var chunks = [];

for (var i = 0, e = 3, charsLength = str.length; i < charsLength; i += 3, e += 3) {
    chunks.push(str.substring(i, e));
}

Pre-calculating the end value as part of the for loop is faster than doing the inline math inside substring. I've tested it in both Firefox and Chrome and they both show speedup.

You can try it here

Adding sheets to end of workbook in Excel (normal method not working?)

mainWB.Sheets.Add(After:=Sheets(Sheets.Count)).Name = new_sheet_name 

should probably be

mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name 

What is a constant reference? (not a reference to a constant)

The clearest answer. Does “X& const x” make any sense?

No, it is nonsense

To find out what the above declaration means, read it right-to-left: “x is a const reference to a X”. But that is redundant — references are always const, in the sense that you can never reseat a reference to make it refer to a different object. Never. With or without the const.

In other words, “X& const x” is functionally equivalent to “X& x”. Since you’re gaining nothing by adding the const after the &, you shouldn’t add it: it will confuse people — the const will make some people think that the X is const, as if you had said “const X& x”.

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

If the python version is 3.X, it's okay.

I think your python version is 2.X, the super would work when adding this code

__metaclass__ = type

so the code is

__metaclass__ = type
class B:
    def meth(self, arg):
        print arg
class C(B):
    def meth(self, arg):
        super(C, self).meth(arg)
print C().meth(1)

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

I think I found the answer in my kernel source documentation: /usr/src/linux-2.6.37-rc3/Documentation/filesystems/proc.txt

1.7 TTY info in /proc/tty
-------------------------

Information about  the  available  and actually used tty's can be found in the
directory /proc/tty.You'll  find  entries  for drivers and line disciplines in
this directory, as shown in Table 1-11.


Table 1-11: Files in /proc/tty
..............................................................................
 File          Content                                        
 drivers       list of drivers and their usage                
 ldiscs        registered line disciplines                    
 driver/serial usage statistic and status of single tty lines 
..............................................................................

To see  which  tty's  are  currently in use, you can simply look into the file
/proc/tty/drivers:

  > cat /proc/tty/drivers 
  pty_slave            /dev/pts      136   0-255 pty:slave 
  pty_master           /dev/ptm      128   0-255 pty:master 
  pty_slave            /dev/ttyp       3   0-255 pty:slave 
  pty_master           /dev/pty        2   0-255 pty:master 
  serial               /dev/cua        5   64-67 serial:callout 
  serial               /dev/ttyS       4   64-67 serial 
  /dev/tty0            /dev/tty0       4       0 system:vtmaster 
  /dev/ptmx            /dev/ptmx       5       2 system 
  /dev/console         /dev/console    5       1 system:console 
  /dev/tty             /dev/tty        5       0 system:/dev/tty 
  unknown              /dev/tty        4    1-63 console 

Here is a link to this file: http://git.kernel.org/?p=linux/kernel/git/next/linux-next.git;a=blob_plain;f=Documentation/filesystems/proc.txt;hb=e8883f8057c0f7c9950fa9f20568f37bfa62f34a

how does unix handle full path name with space and arguments?

You can quote if you like, or you can escape the spaces with a preceding \, but most UNIX paths (Mac OS X aside) don't have spaces in them.

/Applications/Image\ Capture.app/Contents/MacOS/Image\ Capture

"/Applications/Image Capture.app/Contents/MacOS/Image Capture"

/Applications/"Image Capture.app"/Contents/MacOS/"Image Capture"

All refer to the same executable under Mac OS X.

I'm not sure what you mean about recognizing a path - if any of the above paths are passed as a parameter to a program the shell will put the entire string in one variable - you don't have to parse multiple arguments to get the entire path.

How does the "view" method work in PyTorch?

What is the meaning of parameter -1?

You can read -1 as dynamic number of parameters or "anything". Because of that there can be only one parameter -1 in view().

If you ask x.view(-1,1) this will output tensor shape [anything, 1] depending on the number of elements in x. For example:

import torch
x = torch.tensor([1, 2, 3, 4])
print(x,x.shape)
print("...")
print(x.view(-1,1), x.view(-1,1).shape)
print(x.view(1,-1), x.view(1,-1).shape)

Will output:

tensor([1, 2, 3, 4]) torch.Size([4])
...
tensor([[1],
        [2],
        [3],
        [4]]) torch.Size([4, 1])
tensor([[1, 2, 3, 4]]) torch.Size([1, 4])

.NET obfuscation tools/strategy

I have been using smartassembly. Basically, you pick a dll and it returns it obfuscated. It seems to work fine and I've had no problems so far. Very, very easy to use.

Escaping quotes and double quotes

Escaping parameters like that is usually source of frustration and feels a lot like a time wasted. I see you're on v2 so I would suggest using a technique that Joel "Jaykul" Bennet blogged about a while ago.

Long story short: you just wrap your string with @' ... '@ :

Start-Process \\server\toto.exe @'
-batch=B -param="sort1;parmtxt='Security ID=1234'"
'@

(Mind that I assumed which quotes are needed, and which things you were attempting to escape.) If you want to work with the output, you may want to add the -NoNewWindow switch.

BTW: this was so important issue that since v3 you can use --% to stop the PowerShell parser from doing anything with your parameters:

\\server\toto.exe --% -batch=b -param="sort1;paramtxt='Security ID=1234'"

... should work fine there (with the same assumption).

Is ini_set('max_execution_time', 0) a bad idea?

At the risk of irritating you;

You're asking the wrong question. You don't need a reason NOT to deviate from the defaults, but the other way around. You need a reason to do so. Timeouts are absolutely essential when running a web server and to disable that setting without a reason is inherently contrary to good practice, even if it's running on a web server that happens to have a timeout directive of its own.

Now, as for the real answer; probably it doesn't matter at all in this particular case, but it's bad practice to go by the setting of a separate system. What if the script is later run on a different server with a different timeout? If you can safely say that it will never happen, fine, but good practice is largely about accounting for seemingly unlikely events and not unnecessarily tying together the settings and functionality of completely different systems. The dismissal of such principles is responsible for a lot of pointless incompatibilities in the software world. Almost every time, they are unforeseen.

What if the web server later is set to run some other runtime environment which only inherits the timeout setting from the web server? Let's say for instance that you later need a 15-year-old CGI program written in C++ by someone who moved to a different continent, that has no idea of any timeout except the web server's. That might result in the timeout needing to be changed and because PHP is pointlessly relying on the web server's timeout instead of its own, that may cause problems for the PHP script. Or the other way around, that you need a lesser web server timeout for some reason, but PHP still needs to have it higher.

It's just not a good idea to tie the PHP functionality to the web server because the web server and PHP are responsible for different roles and should be kept as functionally separate as possible. When the PHP side needs more processing time, it should be a setting in PHP simply because it's relevant to PHP, not necessarily everything else on the web server.

In short, it's just unnecessarily conflating the matter when there is no need to.

Last but not least, 'stillstanding' is right; you should at least rather use set_time_limit() than ini_set().

Hope this wasn't too patronizing and irritating. Like I said, probably it's fine under your specific circumstances, but it's good practice to not assume your circumstances to be the One True Circumstance. That's all. :)

Detecting the character encoding of an HTTP POST request

the default encoding of a HTTP POST is ISO-8859-1.

else you have to look at the Content-Type header that will then look like

Content-Type: application/x-www-form-urlencoded ; charset=UTF-8

You can maybe declare your form with

<form enctype="application/x-www-form-urlencoded;charset=UTF-8">

or

<form accept-charset="UTF-8">

to force the encoding.

Some references :

http://www.htmlhelp.com/reference/html40/forms/form.html

http://www.w3schools.com/tags/tag_form.asp

Eclipse plugin for generating a class diagram

Assuming that you meant to state 'Class Diagram' instead of 'Project Hierarchy', I've used the following Eclipse plug-ins to generate Class Diagrams at various points in my professional career:

  • ObjectAid. My current preference.
  • EclipseUML from Omondo. Only commercial versions appear to be available right now. The class diagram in your question, is most likely generated by this plugin.

Obligatory links

The listed tools will not generate class diagrams from source code, or atleast when I used them quite a few years back. You can use them to handcraft class diagrams though.

  • UMLet. I used this several years back. Appears to be in use, going by the comments in the Eclipse marketplace.
  • Violet. This supports creation of other types of UML diagrams in addition to class diagrams.

Related questions on StackOverflow

  1. Is there a free Eclipse plugin that creates a UML diagram out of Java classes / packages?

Except for ObjectAid and a few other mentions, most of the Eclipse plug-ins mentioned in the listed questions may no longer be available, or would work only against older versions of Eclipse.

Windows batch: echo without new line

Using: echo | set /p= or <NUL set /p= will both work to suppress the newline.

However, this can be very dangerous when writing more advanced scripts when checking the ERRORLEVEL becomes important as setting set /p= without specifying a variable name will set the ERRORLEVEL to 1.

A better approach would be to just use a dummy variable name like so:
echo | set /p dummyName=Hello World

This will produce exactly what you want without any sneaky stuff going on in the background as I had to find out the hard way, but this only works with the piped version; <NUL set /p dummyName=Hello will still raise the ERRORLEVEL to 1.

Window vs Page vs UserControl for WPF navigation?

All depends on the app you're trying to build. Use Windows if you're building a dialog based app. Use Pages if you're building a navigation based app. UserControls will be useful regardless of the direction you go as you can use them in both Windows and Pages.

A good place to start exploring is here: http://windowsclient.net/learn

My Application Could not open ServletContext resource

Make sure your maven war plugin block in pom.xml includes all files (especially xml files) while building the war. But you don't need to include the .java files though.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-war-plugin</artifactId>
  <version>2.5</version>

  <configuration>
    <webResources>
      <resources>
        <directory>WebContent</directory>
        <includes>
          <include>**/*.*</include> <!--this line includes the xml files into the war, which will be found when it is exploded in server during deployment -->
        </includes>
        <excludes>
          <exclude>*.java</exclude>
        </excludes>
      </resources>
    </webResources>
    <webXml>WebContent/WEB-INF/web.xml</webXml>
  </configuration>
</plugin> 

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

In Certain situations, Setting the UICollectionViewFlowLayout in viewDidLoador ViewWillAppear may not effect on the collectionView.

Setting the UICollectionViewFlowLayout in viewDidAppear may cause see the changes of the cells sizes in runtime.

Another Solution, in Swift 3 :

extension YourViewController : UICollectionViewDelegateFlowLayout{

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let collectionViewWidth = collectionView.bounds.width
        return CGSize(width: collectionViewWidth/3, height: collectionViewWidth/3)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 20
    }
}

Export to csv in jQuery

Just try the following coding...very simple to generate CSV with the values of HTML Tables. No browser issues will come

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>        
        <script src="http://www.csvscript.com/dev/html5csv.js"></script>
<script>
$(document).ready(function() {

 $('table').each(function() {
    var $table = $(this);

    var $button = $("<button type='button'>");
    $button.text("Export to CSV");
    $button.insertAfter($table);

    $button.click(function() {     
         CSV.begin('table').download('Export.csv').go();
    });
  });  
})

</script>
    </head>
<body>
<div id='PrintDiv'>
<table style="width:100%">
  <tr>
    <td>Jill</td>
    <td>Smith</td>      
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>        
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>        
    <td>80</td>
  </tr>
</table>
</div>
</body>
</html>

Reading specific columns from a text file in python

First of all we open the file and as datafile then we apply .read() method reads the file contents and then we split the data which returns something like: ['5', '10', '6', '6', '20', '1', '7', '30', '4', '8', '40', '3', '9', '23', '1', '4', '13', '6'] and the we applied list slicing on this list to start from the element at index position 1 and skip next 3 elements untill it hits the end of the loop.

with open("sample.txt", "r") as datafile:
    print datafile.read().split()[1::3]

Output:

['10', '20', '30', '40', '23', '13']

How do I change the figure size for a seaborn plot?

You can set the context to be poster or manually set fig_size.

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

np.random.seed(0)
n, p = 40, 8
d = np.random.normal(0, 2, (n, p))
d += np.log(np.arange(1, p + 1)) * -5 + 10


# plot
sns.set_style('ticks')
fig, ax = plt.subplots()
# the size of A4 paper
fig.set_size_inches(11.7, 8.27)
sns.violinplot(data=d, inner="points", ax=ax)    
sns.despine()

fig.savefig('example.png')

enter image description here

How to edit a text file in my terminal

If you are still inside the vi editor, you might be in a different mode from the one you want. Hit ESC a couple of times (until it rings or flashes) and then "i" to enter INSERT mode or "a" to enter APPEND mode (they are the same, just start before or after current character).

If you are back at the command prompt, make sure you can locate the file, then navigate to that directory and perform the mentioned "vi helloWorld.txt". Once you are in the editor, you'll need to check the vi reference to know how to perform the editions you want (you may want to google "vi reference" or "vi cheat sheet").

Once the edition is done, hit ESC again, then type :wq to save your work or :q! to quit without saving.

For quick reference, here you have a text-based cheat sheet.

Java Program to test if a character is uppercase/lowercase/number/vowel

This is your homework, so I assume you NEED to use the loops and switch statments. That's O.K, but why are all your loops inner to the privious ones ?

Just take them out to the same "level" and your code is just fine! (part to the low/up mixup).

A tip: Pressing extra 'Enter' & 'Space' is free! (That's the first thing I did to your code, and the problem became very trivial)

Python send POST with header

If we want to add custom HTTP headers to a POST request, we must pass them through a dictionary to the headers parameter.

Here is an example with a non-empty body and headers:

import requests
import json

url = 'https://somedomain.com'
body = {'name': 'Maryja'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(body), headers=headers)

Source

The action or event has been blocked by Disabled Mode

I solved this with Access options.

Go to the Office Button --> Access Options --> Trust Center --> Trust Center Settings Button --> Message Bar

In the right hand pane I selected the radio button "Show the message bar in all applications when content has been blocked."

Closed Access, reopened the database and got the warning for blocked content again.

Only read selected columns

To read a specific set of columns from a dataset you, there are several other options:

1) With freadfrom the data.table-package:

You can specify the desired columns with the select parameter from fread from the data.table package. You can specify the columns with a vector of column names or column numbers.

For the example dataset:

library(data.table)
dat <- fread("data.txt", select = c("Year","Jan","Feb","Mar","Apr","May","Jun"))
dat <- fread("data.txt", select = c(1:7))

Alternatively, you can use the drop parameter to indicate which columns should not be read:

dat <- fread("data.txt", drop = c("Jul","Aug","Sep","Oct","Nov","Dec"))
dat <- fread("data.txt", drop = c(8:13))

All result in:

> data
  Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27  -2  -6 -10 -32

UPDATE: When you don't want fread to return a data.table, use the data.table = FALSE-parameter, e.g.: fread("data.txt", select = c(1:7), data.table = FALSE)

2) With read.csv.sql from the sqldf-package:

Another alternative is the read.csv.sql function from the sqldf package:

library(sqldf)
dat <- read.csv.sql("data.txt",
                    sql = "select Year,Jan,Feb,Mar,Apr,May,Jun from file",
                    sep = "\t")

3) With the read_*-functions from the readr-package:

library(readr)
dat <- read_table("data.txt",
                  col_types = cols_only(Year = 'i', Jan = 'i', Feb = 'i', Mar = 'i',
                                        Apr = 'i', May = 'i', Jun = 'i'))
dat <- read_table("data.txt",
                  col_types = list(Jul = col_skip(), Aug = col_skip(), Sep = col_skip(),
                                   Oct = col_skip(), Nov = col_skip(), Dec = col_skip()))
dat <- read_table("data.txt", col_types = 'iiiiiii______')

From the documentation an explanation for the used characters with col_types:

each character represents one column: c = character, i = integer, n = number, d = double, l = logical, D = date, T = date time, t = time, ? = guess, or _/- to skip the column

How to detect chrome and safari browser (webkit)

Many answers here. Here is my first consideration.

Without JavaScript, including the possibility Javascript is initially disabled by the user in his browser for security purposes, to be white listed by the user if the user trusts the site, DOM will not be usable because Javascript is off.

Programmatically, you are left with a backend server-side or frontend client-side consideration.

With the backend, you can use common denominator HTTP "User-Agent" request header and/or any possible proprietary HTTP request header issued by the browser to output browser specific HTML stuff.

With the client site, you may want to enforce Javascript to allow you to use DOM. If so, then you probably will want to first use the following in your HTML page:

<noscript>This site requires Javascript. Please turn on Javascript.</noscript>

While we are heading to a day with every web coder will be dependent on Javascript in some way (or not), today, to presume every user has javascript enabled would be design and product development QA mistake.

I've seen far too may sites who end up with a blank page or the site breaks down because it presumed every user has javascript enabled. No. For security purposes, they may have Javascript initially off and some browsers, like Chrome, will allow the user to white list the web site on a domain by domain basis. Edge is the only browser I am aware of where Microsoft made the decision to completely disable the user's ability to turn off Javascript. Edge doesn't offer a white listing concept hence it is one reason I don't personally use Edge.

Using the tag is a simple way to inform the user your site won't work without Javascript. Once the user turns it on and refreshes/reload the page, DOM is now available to use the techniques cited by the thread replies to detect chrome vs safari.

Ironically, I got here because I was updating by platform and google the same basic question; chrome vs sarafi. I didn't know Chrome creates a DOM object named "chrome" which is really all you need to detect "chrome" vs everything else.

var isChrome = typeof(chrome) === "object";

If true, you got Chrome, if false, you got some other browser.

Check to see if Safari create its own DOM object as well, if so, get the object name and do the same thing, for example:

var isSafari = (typeof(safari) === "object");

Hope these tips help.

Storing sex (gender) in database

I use char 'f', 'm' and 'u' because I surmise the gender from name, voice and conversation, and sometimes don't know the gender. The final determination is their opinion.

It really depends how well you know the person and whether your criteria is physical form or personal identity. A psychologist might need additional options - cross to female, cross to male, trans to female, trans to male, hermaphrodite and undecided. With 9 options, not clearly defined by a single character, I might go with Hugo's advice of tiny integer.

Simulator or Emulator? What is the difference?

Simple Explanation.

If you want to convert your PC (running Windows) into Mac, you can do either of these:

(1) You can simply install a Mac theme on your Windows. So, your PC feels more like Mac, but you can't actually run any Mac programs. (SIMULATION)

(or)

(2) You can program your PC to run like Mac (I'm not sure if this is possible :P ). Now you can even run Mac programs successfully and expect the same output as on Mac. (EMULATION)

In the first case, you can experience Mac, but you can't expect the same output as on Mac.
In the second case, you can expect the same output as on Mac, but still the fact remains that it is only a PC.

Java 32-bit vs 64-bit compatibility

Unless you have native code (machine code compiled for a specific arcitechture) your code will run equally well in a 32-bit and 64-bit JVM.

Note, however, that due to the larger adresses (32-bit is 4 bytes, 64-bit is 8 bytes) a 64-bit JVM will require more memory than a 32-bit JVM for the same task.

CSS3 background image transition

If you can use jQuery, you can try BgSwitcher plugin to switch the background-image with effects, it's very easy to use.

For example :

$('.bgSwitch').bgswitcher({
        images: ["style/img/bg0.jpg","style/img/bg1.jpg","style/img/bg2.jpg"],
        effect: "fade",
        interval: 10000
});

And add your own effect, see adding an effect types

Unable to cast object of type 'System.DBNull' to type 'System.String`

With a simple generic function you can make this very easy. Just do this:

return ConvertFromDBVal<string>(accountNumber);

using the function:

public static T ConvertFromDBVal<T>(object obj)
{
    if (obj == null || obj == DBNull.Value)
    {
        return default(T); // returns the default value for the type
    }
    else
    {
        return (T)obj;
    }
}

MVC Calling a view from a different controller

You can move you read.aspx view to Shared folder. It is standard way in such circumstances

Shell script current directory?

To print the current working Directory i.e. pwd just type command like:

echo "the PWD is : ${pwd}"

How to exclude a directory in find . command

TLDR: understand your root directories and tailor your search from there, using the -path <excluded_path> -prune -o option. Do not include a trailing / at the end of the excluded path.

Example:

find / -path /mnt -prune -o -name "*libname-server-2.a*" -print


To effectively use the find I believe that it is imperative to have a good understanding of your file system directory structure. On my home computer I have multi-TB hard drives, with about half of that content backed up using rsnapshot (i.e., rsync). Although backing up to to a physically independent (duplicate) drive, it is mounted under my system root (/) directory: /mnt/Backups/rsnapshot_backups/:

/mnt/Backups/
+-- rsnapshot_backups/
    +-- hourly.0/
    +-- hourly.1/
    +-- ...
    +-- daily.0/
    +-- daily.1/
    +-- ...
    +-- weekly.0/
    +-- weekly.1/
    +-- ...
    +-- monthly.0/
    +-- monthly.1/
    +-- ...

The /mnt/Backups/rsnapshot_backups/ directory currently occupies ~2.9 TB, with ~60M files and folders; simply traversing those contents takes time:

## As sudo (#), to avoid numerous "Permission denied" warnings:

time find /mnt/Backups/rsnapshot_backups | wc -l
60314138    ## 60.3M files, folders
34:07.30    ## 34 min

time du /mnt/Backups/rsnapshot_backups -d 0
3112240160  /mnt/Backups/rsnapshot_backups    ## 3.1 TB
33:51.88    ## 34 min

time rsnapshot du    ## << more accurate re: rsnapshot footprint
2.9T    /mnt/Backups/rsnapshot_backups/hourly.0/
4.1G    /mnt/Backups/rsnapshot_backups/hourly.1/
...
4.7G    /mnt/Backups/rsnapshot_backups/weekly.3/
2.9T    total    ## 2.9 TB, per sudo rsnapshot du (more accurate)
2:34:54          ## 2 hr 35 min

Thus, anytime I need to search for a file on my / (root) partition, I need to deal with (avoid if possible) traversing my backups partition.


EXAMPLES

Among the approached variously suggested in this thread (How to exclude a directory in find . command), I find that searches using the accepted answer are much faster -- with caveats.

Solution 1

Let's say I want to find the system file libname-server-2.a, but I do not want to search through my rsnapshot backups. To quickly find a system file, use the exclude path /mnt (i.e., use /mnt, not /mnt/, or /mnt/Backups, or ...):

## As sudo (#), to avoid numerous "Permission denied" warnings:

time find / -path /mnt -prune -o -name "*libname-server-2.a*" -print
/usr/lib/libname-server-2.a
real    0m8.644s              ## 8.6 sec  <<< NOTE!
user    0m1.669s
 sys    0m2.466s

## As regular user (victoria); I also use an alternate timing mechanism, as
## here I am using 2>/dev/null to suppress "Permission denied" warnings:

$ START="$(date +"%s")" && find 2>/dev/null / -path /mnt -prune -o \
    -name "*libname-server-2.a*" -print; END="$(date +"%s")"; \
    TIME="$((END - START))"; printf 'find command took %s sec\n' "$TIME"
/usr/lib/libname-server-2.a
find command took 3 sec     ## ~3 sec  <<< NOTE!

... finds that file in just a few seconds, while this take much longer (appearing to recurse through all of the "excluded" directories):

## As sudo (#), to avoid numerous "Permission denied" warnings:

time find / -path /mnt/ -prune -o -name "*libname-server-2.a*" -print
find: warning: -path /mnt/ will not match anything because it ends with /.
/usr/lib/libname-server-2.a
real    33m10.658s            ## 33 min 11 sec (~231-663x slower!)
user    1m43.142s
 sys    2m22.666s

## As regular user (victoria); I also use an alternate timing mechanism, as
## here I am using 2>/dev/null to suppress "Permission denied" warnings:

$ START="$(date +"%s")" && find 2>/dev/null / -path /mnt/ -prune -o \
    -name "*libname-server-2.a*" -print; END="$(date +"%s")"; \
    TIME="$((END - START))"; printf 'find command took %s sec\n' "$TIME"
/usr/lib/libname-server-2.a
find command took 1775 sec    ## 29.6 min

Solution 2

The other solution offered in this thread (SO#4210042) also performs poorly:

## As sudo (#), to avoid numerous "Permission denied" warnings:

time find / -name "*libname-server-2.a*" -not -path "/mnt"
/usr/lib/libname-server-2.a
real    33m37.911s            ## 33 min 38 sec (~235x slower)
user    1m45.134s
 sys    2m31.846s

time find / -name "*libname-server-2.a*" -not -path "/mnt/*"
/usr/lib/libname-server-2.a
real    33m11.208s            ## 33 min 11 sec
user    1m22.185s
 sys    2m29.962s

SUMMARY | CONCLUSIONS

Use the approach illustrated in "Solution 1"

find / -path /mnt -prune -o -name "*libname-server-2.a*" -print

i.e.

... -path <excluded_path> -prune -o ...

noting that whenever you add the trailing / to the excluded path, the find command then recursively enters (all those) /mnt/* directories -- which in my case, because of the /mnt/Backups/rsnapshot_backups/* subdirectories, additionally includes ~2.9 TB of files to search! By not appending a trailing / the search should complete almost immediately (within seconds).

"Solution 2" (... -not -path <exclude path> ...) likewise appears to recursively search through the excluded directories -- not returning excluded matches, but unnecessarily consuming that search time.


Searching within those rsnapshot backups:

To find a file in one of my hourly/daily/weekly/monthly rsnapshot backups):

$ START="$(date +"%s")" && find 2>/dev/null /mnt/Backups/rsnapshot_backups/daily.0 -name '*04t8ugijrlkj.jpg'; END="$(date +"%s")"; TIME="$((END - START))"; printf 'find command took %s sec\n' "$TIME"
/mnt/Backups/rsnapshot_backups/daily.0/snapshot_root/mnt/Vancouver/temp/04t8ugijrlkj.jpg
find command took 312 sec   ## 5.2 minutes: despite apparent rsnapshot size
                            ## (~4 GB), it is in fact searching through ~2.9 TB)

Excluding a nested directory:

Here, I want to exclude a nested directory, e.g. /mnt/Vancouver/projects/ie/claws/data/* when searching from /mnt/Vancouver/projects/:

$ time find . -iname '*test_file*'
./ie/claws/data/test_file
./ie/claws/test_file
0:01.97

$ time find . -path '*/data' -prune -o -iname '*test_file*' -print
./ie/claws/test_file
0:00.07

Aside: Adding -print at the end of the command suppresses the printout of the excluded directory:

$ find / -path /mnt -prune -o -name "*libname-server-2.a*"
/mnt
/usr/lib/libname-server-2.a

$ find / -path /mnt -prune -o -name "*libname-server-2.a*" -print
/usr/lib/libname-server-2.a

Classpath including JAR within a JAR

You do NOT want to use those "explode JAR contents" solutions. They definitely make it harder to see stuff (since everything is exploded at the same level). Furthermore, there could be naming conflicts (should not happen if people use proper packages, but you cannot always control this).

The feature that you want is one of the top 25 Sun RFEs: RFE 4648386, which Sun, in their infinite wisdom, has designated as being of low priority. We can only hope that Sun wakes up...

In the meanwhile, the best solution that I have come across (which I wish that Sun would copy in the JDK) is to use the custom class loader JarClassLoader.

Copy output of a JavaScript variable to the clipboard

function copyToClipboard(text) {
    var dummy = document.createElement("textarea");
    // to avoid breaking orgain page when copying more words
    // cant copy when adding below this code
    // dummy.style.display = 'none'
    document.body.appendChild(dummy);
    //Be careful if you use texarea. setAttribute('value', value), which works with "input" does not work with "textarea". – Eduard
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
copyToClipboard('hello world')
copyToClipboard('hello\nworld')

Combining (concatenating) date and time into a datetime

Solution (1): datetime arithmetic

Given @myDate, which can be anything that can be cast as a DATE, and @myTime, which can be anything that can be cast as a TIME, starting SQL Server 2014+ this works fine and does not involve string manipulation:

CAST(CAST(@myDate as DATE) AS DATETIME) + CAST(CAST(@myTime as TIME) as DATETIME)

You can verify with:

SELECT  GETDATE(), 
        CAST(CAST(GETDATE() as DATE) AS DATETIME) + CAST(CAST(GETDATE() as TIME) as DATETIME)

Solution (2): string manipulation

SELECT  GETDATE(), 
        CONVERT(DATETIME, CONVERT(CHAR(8), GETDATE(), 112) + ' ' + CONVERT(CHAR(8), GETDATE(), 108))

However, solution (1) is not only 2-3x faster than solution (2), it also preserves the microsecond part.

See SQL Fiddle for the solution (1) using date arithmetic vs solution (2) involving string manipulation

Setting Windows PATH for Postgres tools

I am using Windows 8 and the above solutions did not work out for me. I downgraded Postgres from 9.4 to 9.3. Man,it worked :)

jQuery AJAX Call to PHP Script with JSON Return

try to send content type header from server use this just before echoing

header('Content-Type: application/json');

C# Test if user has write access to a folder

Your code gets the DirectorySecurity for a given directory, and handles an exception (due to your not having access to the security info) correctly. However, in your sample you don't actually interrogate the returned object to see what access is allowed - and I think you need to add this in.

Update Jenkins from a war file

If you have installed Jenkins via apt-get, you should also update Jenkins via apt-get to avoid future problems. Updating should work via "apt-get update" and then "apt-get upgrade".

For details visit the following URL:

https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+on+Ubuntu

How to make the 'cut' command treat same sequental delimiters as one?

This Perl one-liner shows how closely Perl is related to awk:

perl -lane 'print $F[3]' text.txt

However, the @F autosplit array starts at index $F[0] while awk fields start with $1

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;

This is all you need to:

  1. Add the id column
  2. Populate it with a sequence from 1 to count(*).
  3. Set it as primary key / not null.

Credit is given to @resnyanskiy who gave this answer in a comment.

filter: progid:DXImageTransform.Microsoft.gradient is not working in ie7

In testing IE7/8/9 I was getting an ActiveX warning trying to use this code snippet:

filter:progid:DXImageTransform.Microsoft.gradient

After removing this the warning went away. I know this isn't an answer, but I thought it was worthwhile to note.

Access nested dictionary items via a list of keys?

Solved this with recursion:

def get(d,l):
    if len(l)==1: return d[l[0]]
    return get(d[l[0]],l[1:])

Using your example:

dataDict = {
    "a":{
        "r": 1,
        "s": 2,
        "t": 3
        },
    "b":{
        "u": 1,
        "v": {
            "x": 1,
            "y": 2,
            "z": 3
        },
        "w": 3
        }
}
maplist1 = ["a", "r"]
maplist2 = ["b", "v", "y"]
print(get(dataDict, maplist1)) # 1
print(get(dataDict, maplist2)) # 2

How to delete all files and folders in a directory?

private void ClearDirectory(string path)
{
    if (Directory.Exists(path))//if folder exists
    {
        Directory.Delete(path, true);//recursive delete (all subdirs, files)
    }
    Directory.CreateDirectory(path);//creates empty directory
}

Bad Request - Invalid Hostname IIS7

Make sure IIS is listening to your port.

In my case this was the issue. So I had to change my port to something else like 8083 and it solved this issue.

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

If the other answers didn't worked for you. Try this!

Sometimes all you need is to push again. It happen to me today due to slow internet connection(when you are downloading or using p2p).

Please see screenshot below:

enter image description here

How to add headers to OkHttp request interceptor?

Finally, I added the headers this way:

@Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();
        Request newRequest;

        newRequest = request.newBuilder()
                .addHeader(HeadersContract.HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION)
                .addHeader(HeadersContract.HEADER_X_CLIENT_ID, CLIENT_ID)
                .build();
        return chain.proceed(newRequest);
    }

How to pass parameters to maven build using pom.xml?

We can Supply parameter in different way after some search I found some useful

<plugin>
  <artifactId>${release.artifactId}</artifactId>
  <version>${release.version}-${release.svm.version}</version>...

...

Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .

While Running build we need supply value for those parameter as follows.

RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74

Here I am supplying

release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74

It worked for me. Thanks

Accessing a class' member variables in Python?

The answer, in a few words

In your example, itsProblem is a local variable.

Your must use self to set and get instance variables. You can set it in the __init__ method. Then your code would be:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

But if you want a true class variable, then use the class name directly:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)

But be careful with this one, as theExample.itsProblem is automatically set to be equal to Example.itsProblem, but is not the same variable at all and can be changed independently.

Some explanations

In Python, variables can be created dynamically. Therefore, you can do the following:

class Example(object):
    pass

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem 

prints

True

Therefore, that's exactly what you do with the previous examples.

Indeed, in Python we use self as this, but it's a bit more than that. self is the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it self or not.

Which means you can do:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

or:

class Example(object):
    def __init__(my_super_self):
        my_super_self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

It's exactly the same. The first argument of ANY object method is the current object, we only call it self as a convention. And you add just a variable to this object, the same way you would do it from outside.

Now, about the class variables.

When you do:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

You'll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?

Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.

As a conclusion, never use class variables to set default values to object variables. Use __init__ for that.

Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.

Replace characters from a column of a data frame R

chartr is also convenient for these types of substitutions:

chartr("_", "-", data1$c)
#  [1] "A-B" "A-B" "A-B" "A-B" "A-C" "A-C" "A-C" "A-C" "A-C" "A-C"

Thus, you can just do:

data1$c <- chartr("_", "-", data1$c)

Get loop count inside a Python FOR loop

Using zip function we can get both element and index.

countries = ['Pakistan','India','China','Russia','USA']

for index, element zip(range(0,countries),countries):

         print('Index : ',index)
         print(' Element : ', element,'\n')

output : Index : 0 Element : Pakistan ...

See also :

Python.org

SQL Server - SELECT FROM stored procedure

You can

  1. create a table variable to hold the result set from the stored proc and then
  2. insert the output of the stored proc into the table variable, and then
  3. use the table variable exactly as you would any other table...

... sql ....

Declare @T Table ([column definitions here])
Insert @T Exec storedProcname params 
Select * from @T Where ...

Response Buffer Limit Exceeded

Here is what a Microsoft support page says about this: https://support.microsoft.com/en-us/help/944886/error-message-when-you-use-the-response-binarywrite-method-in-iis-6-an.

But it’s easier in the GUI:

  • In Internet Information Services (IIS) Manager, click on ASP.
  • Change Behavior > Limits Properties > Response Buffering Limit from 4 MB to 64 MB.
  • Apply and restart.

Check if an element contains a class in JavaScript?

Element.matches()

element.matches(selectorString)

According to MDN Web Docs:

The Element.matches() method returns true if the element would be selected by the specified selector string; otherwise, returns false.

Therefore, you can use Element.matches() to determine if an element contains a class.

_x000D_
_x000D_
const element = document.querySelector('#example');

console.log(element.matches('.foo')); // true
_x000D_
<div id="example" class="foo bar"></div>
_x000D_
_x000D_
_x000D_

View Browser Compatibility

How can I write maven build to add resources to classpath?

By default maven does not include any files from "src/main/java".

You have two possible way to that.

  1. put all your resource files (different than java files) to "src/main/resources" - this is highly recommended

  2. Add to your pom (resource plugin):

?

 <resources>
       <resource>
           <directory>src/main/resources</directory>
        </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
  </resources>

iOS 8 UITableView separator inset 0 not working

simply put this two lines in cellForRowAtIndexPath method

  • if you want to all separator lines are start from zero [cell setSeparatorInset:UIEdgeInsetsZero]; [cell setLayoutMargins:UIEdgeInsetsZero];

if you want to Specific separator line are start from zero suppose here is last line is start from zero

if (indexPath.row == array.count-1) 
{
   [cell setSeparatorInset:UIEdgeInsetsZero];
   [cell setLayoutMargins:UIEdgeInsetsZero];
}
else
   tblView.separatorInset=UIEdgeInsetsMake(0, 10, 0, 0);

Pick any kind of file via an Intent in Android

The other answers are not incorrect. However, now there are more options for opening files. For example, if you want the app to have long term, permanent acess to a file, you can use ACTION_OPEN_DOCUMENT instead. Refer to the official documentation: Open files using storage access framework. Also refer to this answer.

IIS7: A process serving application pool 'YYYYY' suffered a fatal communication error with the Windows Process Activation Service

Debug Diagnostics Tool (DebugDiag) can be a lifesaver. It creates and analyze IIS crash dumps. I figured out my crash in minutes once I saw the call stack. https://support.microsoft.com/en-us/kb/919789

Javascript - removing undefined fields from an object

This one is easy to remember, but might be slow. Use jQuery to copy non-null properties to an empty object. No deep copy unless you add true as first argument.

myObj = $.extend({}, myObj);

How to resolve this JNI error when trying to run LWJGL "Hello World"?

I had same issue using different dependancy what helped me is to set scope to compile.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>compile</scope>
    </dependency>

Creating multiline strings in JavaScript

Also do note that, when extending string over multiple lines using forward backslash at end of each line, any extra characters (mostly spaces, tabs and comments added by mistake) after forward backslash will cause unexpected character error, which i took an hour to find out

var string = "line1\  // comment, space or tabs here raise error
line2";

How does one use the onerror attribute of an img element

very simple

  <img onload="loaded(this, 'success')" onerror="error(this, 
 'error')"  src="someurl"  alt="" />

 function loaded(_this, status){
   console.log(_this, status)
  // do your work in load
 }
 function error(_this, status){
  console.log(_this, status)
  // do your work in error
  }

How to attach a process in gdb

The first argument should be the path to the executable program. So

gdb progname 12271

Where does one get the "sys/socket.h" header/source file?

Since you've labeled the question C++, you might be interested in using boost::asio, ACE, or some other cross-platform socket library for C++ or for C. Some other cross-platform libraries may be found in the answers to C++ sockets library for cross-platform and Cross platform Networking API.

Assuming that using a third party cross-platform sockets library is not an option for you...

The header <sys/socket.h> is defined in IEEE Std. 1003.1 (POSIX), but sadly Windows is non-compliant with the POSIX standard. The MinGW compiler is a port of GCC for compiling Windows applications, and therefore does not include these POSIX system headers. If you install GCC using Cygwin, then it will include these system headers to emulate a POSIX environment on Windows. Be aware, however, that if you use Cygwin for sockets that a.) you will need to put the cygwin DLL in a place where your application can read it and b.) Cygwin headers and Windows headers don't interact very well (so if you plan on including windows.h, then you probably don't want to be including sys/socket.h).

My personal recommendation would be to download a copy of VirtualBox, download a copy of Ubuntu, install Ubuntu into VirtualBox, and then do your coding and testing on Ubuntu. Alternatively, I am told that Microsoft sells a "UNIX subsystem" and that it is pre-installed on certain higher-end editions of Windows, although I have no idea how compliant this system is (and, if it is compliant, with which edition of the UNIX standard it is compliant). Winsockets are also an option, although they can behave in subtly different ways than their POSIX counterparts, even though the signatures may be similar.

Find if a String is present in an array

If you can organize the values in the array in sorted order, then you can use Arrays.binarySearch(). Otherwise you'll have to write a loop and to a linear search. If you plan to have a large (more than a few dozen) strings in the array, consider using a Set instead.

Insertion Sort vs. Selection Sort

Basically insertion sort works by comparing two elements at a time and selection sort selects the minimum element from the whole array and sorts it.

Conceptually insertion sort keeps on sorting the sub list by comparing two elements till the whole array is sorted while the selection sort selects the minimum element and swaps it to the first position second minimum element to the second position and so on.

Insertion sort can be shown as :

    for(i=1;i<n;i++)
        for(j=i;j>0;j--)
            if(arr[j]<arr[j-1])
                temp=arr[j];
                arr[j]=arr[j-1];
                arr[j-1]=temp;

Selection sort can be shown as :

    for(i=0;i<n;i++)
        min=i;
        for(j=i+1;j<n;j++)
        if(arr[j]<arr[min])
        min=j;
        temp=arr[i];
        arr[i]=arr[min];
        arr[min]=temp;

How to import Maven dependency in Android Studio/IntelliJ?

Try itext. Add dependency to your build.gradle for latest as of this post

Note: special version for android, trailing "g":

dependencies {
    compile 'com.itextpdf:itextg:5.5.9'
}

Convert Month Number to Month Name Function in SQL

Use this statement to convert Month numeric value to Month name.

SELECT CONVERT(CHAR(3), DATENAME(MONTH, GETDATE()))

twitter bootstrap 3.0 typeahead ajax example

With bootstrap3-typeahead, I made it to work with the following code:

<input id="typeahead-input" type="text" data-provide="typeahead" />

<script type="text/javascript">
jQuery(document).ready(function() {
    $('#typeahead-input').typeahead({
        source: function (query, process) {
            return $.get('search?q=' + query, function (data) {
                return process(data.search_results);
            });
        }
    });
})
</script>

The backend provides search service under the search GET endpoint, receiving the query in the q parameter, and returns a JSON in the format { 'search_results': ['resultA', 'resultB', ... ] }. The elements of the search_resultsarray are displayed in the typeahead input.

How can I make my custom objects Parcelable?

Now you can use Parceler library to convert your any custom class in parcelable. Just annotate your POJO class with @Parcel. e.g.

    @Parcel
    public class Example {
    String name;
    int id;

    public Example() {}

    public Example(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getName() { return name; }

    public int getId() { return id; }
}

you can create an object of Example class and wrap through Parcels and send as a bundle through intent. e.g

Bundle bundle = new Bundle();
bundle.putParcelable("example", Parcels.wrap(example));

Now to get Custom Class object just use

Example example = Parcels.unwrap(getIntent().getParcelableExtra("example"));

jQuery - disable selected options

This will disable/enable the options when you select/remove them, respectively.

$("#theSelect").change(function(){          
    var value = $(this).val();
    if (value === '') return;
    var theDiv = $(".is" + value);

    var option = $("option[value='" + value + "']", this);
    option.attr("disabled","disabled");

    theDiv.slideDown().removeClass("hidden");
    theDiv.find('a').data("option",option);
});


$("div a.remove").click(function () {     
    $(this).parent().slideUp(function() { $(this).addClass("hidden"); });
    $(this).data("option").removeAttr('disabled');
});

Demo: http://jsfiddle.net/AaXkd/

What is the connection string for localdb for version 11

This is for others who would have struggled like me to get this working....I wasted more than half a day on a seemingly trivial thing...

If you want to use SQL Express 2012 LocalDB from VS2010 you must have this patch installed http://www.microsoft.com/en-us/download/details.aspx?id=27756

Just like mentioned in the comments above I too had Microsoft .NET Framework Version 4.0.30319 SP1Rel and since its mentioned everywhere that you need "Framework 4.0.2 or Above" I thought I am good to go...

However, when I explicitly downloaded that 4.0.2 patch and installed it I got it working....

Example on ToggleButton

Try this Toggle Buttons

test_activity.xml

<ToggleButton 
android:id="@+id/togglebutton" 
android:layout_width="100px" 
android:layout_height="50px" 
android:layout_centerVertical="true" 
android:layout_centerHorizontal="true"
android:onClick="toggleclick"/>

Test.java

public class Test extends Activity {

private ToggleButton togglebutton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
}

public void toggleclick(View v){
    if(togglebutton.isChecked())
        Toast.makeText(TestActivity.this, "ON", Toast.LENGTH_SHORT).show();
    else
        Toast.makeText(TestActivity.this, "OFF", Toast.LENGTH_SHORT).show();
    }
}

onclick or inline script isn't working in extension

Reason

This does not work, because Chrome forbids any kind of inline code in extensions via Content Security Policy.

Inline JavaScript will not be executed. This restriction bans both inline <script> blocks and inline event handlers (e.g. <button onclick="...">).

How to detect

If this is indeed the problem, Chrome would produce the following error in the console:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

To access a popup's JavaScript console (which is useful for debug in general), right-click your extension's button and select "Inspect popup" from the context menu.

More information on debugging a popup is available here.

How to fix

One needs to remove all inline JavaScript. There is a guide in Chrome documentation.

Suppose the original looks like:

<a onclick="handler()">Click this</a> <!-- Bad -->

One needs to remove the onclick attribute and give the element a unique id:

<a id="click-this">Click this</a> <!-- Fixed -->

And then attach the listener from a script (which must be in a .js file, suppose popup.js):

// Pure JS:
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("click-this").addEventListener("click", handler);
});

// The handler also must go in a .js file
function handler() {
  /* ... */
}

Note the wrapping in a DOMContentLoaded event. This ensures that the element exists at the time of execution. Now add the script tag, for instance in the <head> of the document:

<script src="popup.js"></script>

Alternative if you're using jQuery:

// jQuery
$(document).ready(function() {
  $("#click-this").click(handler);
});

Relaxing the policy

Q: The error mentions ways to allow inline code. I don't want to / can't change my code, how do I enable inline scripts?

A: Despite what the error says, you cannot enable inline script:

There is no mechanism for relaxing the restriction against executing inline JavaScript. In particular, setting a script policy that includes 'unsafe-inline' will have no effect.

Update: Since Chrome 46, it's possible to whitelist specific inline code blocks:

As of Chrome 46, inline scripts can be whitelisted by specifying the base64-encoded hash of the source code in the policy. This hash must be prefixed by the used hash algorithm (sha256, sha384 or sha512). See Hash usage for <script> elements for an example.

However, I do not readily see a reason to use this, and it will not enable inline attributes like onclick="code".

Weird PHP error: 'Can't use function return value in write context'

The problem is in the () you have to go []

if (isset($_POST('sms_code') == TRUE)

by

if (isset($_POST['sms_code'] == TRUE)

Adding image inside table cell in HTML

There are some syntax errors on your HTML.

First, the URL of the image needs to point to an address on the public Internet. The users viewing your page won't have your hard drive, so pointing to a file on your local hard drive cannot work. Replace C:\Pics with the actual URL of the image, not a path on development machine filesystem. If you want to be absolutely sure, use a different computer and paste the img tag src attribute value to the address bar of the browser. If it works there, then you're good. Do not that the path can be relative and still valid, but then it needs to be relative to the public URL of the web page it's embedded in.

Second, the <title> tag. You need to add this tag if you need a title on the browser, and you can't format it.

The third error, if about the <th> tag, you have to add this header inside a <tr> tag, because <th> needs a row (create by <tr>).

Another thing is, you don't need all colspan you did.

I tried to do a valid html as you need. Take a look:

<!DOCTYPE html> 
<html>
<head>
    <title>CAR APPLICATION</title>
</head>
<body>
    <center>
        <h1>CAR APPLICATION</h1>
    </center>

    <table border="5" bordercolor="red" align="center">
        <tr>
            <th colspan="3">SONAKSHI RAINA 10B ROLL No:-32</th> 
        </tr>
        <tr>
            <th>Name</th>
            <th>Origin</th>
            <th>Photo</th>
        </tr>
        <tr>
            <td>Bugatti Veyron Super Sport</td>
            <td>Molsheim, Alsace, France</td>
                    <!-- considering it is on the same folder that .html file -->
            <td><img src="H.gif" alt="" border=3 height=100 width=100></img></td>
        </tr>
        <tr>
            <td>SSC Ultimate Aero TT  TopSpeed</td>
            <td>United States</td>
            <td border=3 height=100 width=100>Photo1</td>
        </tr>
        <tr>
            <td>Koenigsegg CCX</td>
            <td>Ängelholm, Sweden</td>
            <td border=4 height=100 width=300>Photo1</td>
        </tr>
        <tr>
            <td>Saleen S7</td>
            <td>Irvine, California, United States</td>
            <td border=3 height=100 width=100>Photo1</td>
        </tr>
        <tr>
            <td> McLaren F1</td>
            <td>Surrey, England</td>
            <td border=3 height=100 width=100>Photo1</td>
        </tr>
        <tr>
            <td>Ferrari Enzo</td>
            <td>Maranello, Italy</td>
            <td border=3 height=100 width=100>Photo1</td>
        </tr>
        <tr>
            <td> Pagani Zonda F Clubsport</td>
            <td>Modena, Italy</td>
            <td border=3 height=100 width=100>Photo1</td>
        </tr>
    </table>
</body>
<html>

List of standard lengths for database fields

I pretty much always use a power of 2 unless there is a good reason not to, such as a customer facing interface where some other number has special meaning to the customer.

If you stick to powers of 2 it keeps you within a limited set of common sizes, which itself is a good thing, and it makes it easier to guess the size of unknown objects you may encounter. I see a fair number of other people doing this, and there is something aesthetically pleasing about it. It generally gives me a good feeling when I see this, it means the designer was thinking like an engineer or mathematician. Though I'd probably be concerned if only prime numbers were used. :)

jQuery Mobile - back button

You can use nonHistorySelectors option from jquery mobile where you do not want to track history. You can find the detailed documentation here http://jquerymobile.com/demos/1.0a4.1/#docs/api/globalconfig.html

What is the proper way to format a multi-line dict in Python?

From my experience with tutorials, and other things number 2 always seems preferred, but it's a personal preference choice more than anything else.

How to install ADB driver for any android device?

You don't really need to install or use any third party tools.

The drivers located in ...\Android\Sdk\extras\google\usb_driver work just fine.

Step 1: In Device Manager, Right click on the malfunctioning Android ADB Interface driver

Step 2: Select Update Driver Software

Step 3: Select Browse my computer for driver software

Step 4: Select Let me pick from a list of device drivers on my computer

Step 5: Select Have Disk

This window pops up:

enter image description here

Step 6: Copy the location of the Google USB Driver (...\Android\Sdk\extras\google\usb_driver) or browse to it.

Step 7: Click Ok

This window pops up:

enter image description here

Step 8: Select Android ADB Interface and click Next

The window below pops up with a warning:

enter image description here

That's it. You driver installation will start and in a few seconds, you should be able to see your device

How to validate an email address using a regular expression?

It’s easy in Perl 5.10 or newer:

/(?(DEFINE)
   (?<address>         (?&mailbox) | (?&group))
   (?<mailbox>         (?&name_addr) | (?&addr_spec))
   (?<name_addr>       (?&display_name)? (?&angle_addr))
   (?<angle_addr>      (?&CFWS)? < (?&addr_spec) > (?&CFWS)?)
   (?<group>           (?&display_name) : (?:(?&mailbox_list) | (?&CFWS))? ;
                                          (?&CFWS)?)
   (?<display_name>    (?&phrase))
   (?<mailbox_list>    (?&mailbox) (?: , (?&mailbox))*)

   (?<addr_spec>       (?&local_part) \@ (?&domain))
   (?<local_part>      (?&dot_atom) | (?&quoted_string))
   (?<domain>          (?&dot_atom) | (?&domain_literal))
   (?<domain_literal>  (?&CFWS)? \[ (?: (?&FWS)? (?&dcontent))* (?&FWS)?
                                 \] (?&CFWS)?)
   (?<dcontent>        (?&dtext) | (?&quoted_pair))
   (?<dtext>           (?&NO_WS_CTL) | [\x21-\x5a\x5e-\x7e])

   (?<atext>           (?&ALPHA) | (?&DIGIT) | [!#\$%&'*+-/=?^_`{|}~])
   (?<atom>            (?&CFWS)? (?&atext)+ (?&CFWS)?)
   (?<dot_atom>        (?&CFWS)? (?&dot_atom_text) (?&CFWS)?)
   (?<dot_atom_text>   (?&atext)+ (?: \. (?&atext)+)*)

   (?<text>            [\x01-\x09\x0b\x0c\x0e-\x7f])
   (?<quoted_pair>     \\ (?&text))

   (?<qtext>           (?&NO_WS_CTL) | [\x21\x23-\x5b\x5d-\x7e])
   (?<qcontent>        (?&qtext) | (?&quoted_pair))
   (?<quoted_string>   (?&CFWS)? (?&DQUOTE) (?:(?&FWS)? (?&qcontent))*
                        (?&FWS)? (?&DQUOTE) (?&CFWS)?)

   (?<word>            (?&atom) | (?&quoted_string))
   (?<phrase>          (?&word)+)

   # Folding white space
   (?<FWS>             (?: (?&WSP)* (?&CRLF))? (?&WSP)+)
   (?<ctext>           (?&NO_WS_CTL) | [\x21-\x27\x2a-\x5b\x5d-\x7e])
   (?<ccontent>        (?&ctext) | (?&quoted_pair) | (?&comment))
   (?<comment>         \( (?: (?&FWS)? (?&ccontent))* (?&FWS)? \) )
   (?<CFWS>            (?: (?&FWS)? (?&comment))*
                       (?: (?:(?&FWS)? (?&comment)) | (?&FWS)))

   # No whitespace control
   (?<NO_WS_CTL>       [\x01-\x08\x0b\x0c\x0e-\x1f\x7f])

   (?<ALPHA>           [A-Za-z])
   (?<DIGIT>           [0-9])
   (?<CRLF>            \x0d \x0a)
   (?<DQUOTE>          ")
   (?<WSP>             [\x20\x09])
 )

 (?&address)/x

Socket.IO handling disconnect event

Create a Map or a Set, and using "on connection" event set to it each connected socket, in reverse "once disconnect" event delete that socket from the Map we created earlier

import * as Server from 'socket.io';

const io = Server();
io.listen(3000);

const connections = new Set();

io.on('connection', function (s) {

  connections.add(s);

  s.once('disconnect', function () {
    connections.delete(s);
  });

});

How to write UPDATE SQL with Table alias in SQL Server 2008?

The syntax for using an alias in an update statement on SQL Server is as follows:

UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;

The alias should not be necessary here though.

Java 8 stream's .min() and .max(): why does this compile?

This works because Integer::min resolves to an implementation of the Comparator<Integer> interface.

The method reference of Integer::min resolves to Integer.min(int a, int b), resolved to IntBinaryOperator, and presumably autoboxing occurs somewhere making it a BinaryOperator<Integer>.

And the min() resp max() methods of the Stream<Integer> ask the Comparator<Integer> interface to be implemented.
Now this resolves to the single method Integer compareTo(Integer o1, Integer o2). Which is of type BinaryOperator<Integer>.

And thus the magic has happened as both methods are a BinaryOperator<Integer>.