Programs & Examples On #Ropemacs

Ropemacs is a plugin for performing python refactorings in emacs. It uses rope library and pymacs.

Detecting TCP Client Disconnect

"""
tcp_disconnect.py
Echo network data test program in python. This easily translates to C & Java.

A server program might want to confirm that a tcp client is still connected 
before it sends a data. That is, detect if its connected without reading from socket.
This will demonstrate how to detect a TCP client disconnect without reading data.

The method to do this:
1) select on socket as poll (no wait)
2) if no recv data waiting, then client still connected
3) if recv data waiting, the read one char using PEEK flag 
4) if PEEK data len=0, then client has disconnected, otherwise its connected.
Note, the peek flag will read data without removing it from tcp queue.

To see it in action: 0) run this program on one computer 1) from another computer, 
connect via telnet port 12345, 2) type a line of data 3) wait to see it echo, 
4) type another line, 5) disconnect quickly, 6) watch the program will detect the 
disconnect and exit.

John Masinter, 17-Dec-2008
"""

import socket
import time
import select

HOST = ''       # all local interfaces
PORT = 12345    # port to listen

# listen for new TCP connections
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
# accept new conneciton
conn, addr = s.accept()
print 'Connected by', addr
# loop reading/echoing, until client disconnects
try:
    conn.send("Send me data, and I will echo it back after a short delay.\n")
    while 1:
        data = conn.recv(1024)                          # recv all data queued
        if not data: break                              # client disconnected
        time.sleep(3)                                   # simulate time consuming work
        # below will detect if client disconnects during sleep
        r, w, e = select.select([conn], [], [], 0)      # more data waiting?
        print "select: r=%s w=%s e=%s" % (r,w,e)        # debug output to command line
        if r:                                           # yes, data avail to read.
            t = conn.recv(1024, socket.MSG_PEEK)        # read without remove from queue
            print "peek: len=%d, data=%s" % (len(t),t)  # debug output
            if len(t)==0:                               # length of data peeked 0?
                print "Client disconnected."            # client disconnected
                break                                   # quit program
        conn.send("-->"+data)                           # echo only if still connected
finally:
    conn.close()

How to wait in a batch script?

What about:

@echo off
set wait=%1
echo waiting %wait% s
echo wscript.sleep %wait%000 > wait.vbs
wscript.exe wait.vbs
del wait.vbs

How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?

Laravel 5.4

Global functions

@if (request()->is('/'))
    <p>Is homepage</p>
@endif

List of special characters for SQL LIKE clause

ANSI SQL92:

  • %
  • _
  • an ESCAPE character only if specified.

It is disappointing that many databases do not stick to the standard rules and add extra characters, or incorrectly enable ESCAPE with a default value of ‘\’ when it is missing. Like we don't already have enough trouble with ‘\’!

It's impossible to write DBMS-independent code here, because you don't know what characters you're going to have to escape, and the standard says you can't escape things that don't need to be escaped. (See section 8.5/General Rules/3.a.ii.)

Thank you SQL! gnnn

Replace an element into a specific position of a vector

vec1[i] = vec2[i]

will set the value of vec1[i] to the value of vec2[i]. Nothing is inserted. Your second approach is almost correct. Instead of +i+1 you need just +i

v1.insert(v1.begin()+i, v2[i])

How do I restart a program based on user input?

This line will unconditionally restart the running program from scratch:

os.execl(sys.executable, sys.executable, *sys.argv)

One of its advantage compared to the remaining suggestions so far is that the program itself will be read again.

This can be useful if, for example, you are modifying its code in another window.

get current date with 'yyyy-MM-dd' format in Angular 4

app.component.html

<div>
     <h5 style="color:#ffffff;">{{myDate | date:'fullDate'}}</h5>
</div>

app.component.ts

export class AppComponent implements OnInit {
myDate = Date.now();    //date 

How to create a self-signed certificate with OpenSSL

Am I missing something? Is this the correct way to build a self-signed certificate?

It's easy to create a self-signed certificate. You just use the openssl req command. It can be tricky to create one that can be consumed by the largest selection of clients, like browsers and command line tools.

It's difficult because the browsers have their own set of requirements, and they are more restrictive than the IETF. The requirements used by browsers are documented at the CA/Browser Forums (see references below). The restrictions arise in two key areas: (1) trust anchors, and (2) DNS names.

Modern browsers (like the warez we're using in 2014/2015) want a certificate that chains back to a trust anchor, and they want DNS names to be presented in particular ways in the certificate. And browsers are actively moving against self-signed server certificates.

Some browsers don't exactly make it easy to import a self-signed server certificate. In fact, you can't with some browsers, like Android's browser. So the complete solution is to become your own authority.

In the absence of becoming your own authority, you have to get the DNS names right to give the certificate the greatest chance of success. But I would encourage you to become your own authority. It's easy to become your own authority, and it will sidestep all the trust issues (who better to trust than yourself?).


This is probably not the site you are looking for!
The site's security certificate is not trusted!

This is because browsers use a predefined list of trust anchors to validate server certificates. A self-signed certificate does not chain back to a trusted anchor.

The best way to avoid this is:

  1. Create your own authority (i.e., become a CA)
  2. Create a certificate signing request (CSR) for the server
  3. Sign the server's CSR with your CA key
  4. Install the server certificate on the server
  5. Install the CA certificate on the client

Step 1 - Create your own authority just means to create a self-signed certificate with CA: true and proper key usage. That means the Subject and Issuer are the same entity, CA is set to true in Basic Constraints (it should also be marked as critical), key usage is keyCertSign and crlSign (if you are using CRLs), and the Subject Key Identifier (SKI) is the same as the Authority Key Identifier (AKI).

To become your own certificate authority, see *How do you sign a certificate signing request with your certification authority? on Stack Overflow. Then, import your CA into the Trust Store used by the browser.

Steps 2 - 4 are roughly what you do now for a public facing server when you enlist the services of a CA like Startcom or CAcert. Steps 1 and 5 allows you to avoid the third-party authority, and act as your own authority (who better to trust than yourself?).

The next best way to avoid the browser warning is to trust the server's certificate. But some browsers, like Android's default browser, do not let you do it. So it will never work on the platform.

The issue of browsers (and other similar user agents) not trusting self-signed certificates is going to be a big problem in the Internet of Things (IoT). For example, what is going to happen when you connect to your thermostat or refrigerator to program it? The answer is, nothing good as far as the user experience is concerned.

The W3C's WebAppSec Working Group is starting to look at the issue. See, for example, Proposal: Marking HTTP As Non-Secure.


How to create a self-signed certificate with OpenSSL

The commands below and the configuration file create a self-signed certificate (it also shows you how to create a signing request). They differ from other answers in one respect: the DNS names used for the self signed certificate are in the Subject Alternate Name (SAN), and not the Common Name (CN).

The DNS names are placed in the SAN through the configuration file with the line subjectAltName = @alternate_names (there's no way to do it through the command line). Then there's an alternate_names section in the configuration file (you should tune this to suit your taste):

[ alternate_names ]

DNS.1       = example.com
DNS.2       = www.example.com
DNS.3       = mail.example.com
DNS.4       = ftp.example.com

# Add these if you need them. But usually you don't want them or
#   need them in production. You may need them for development.
# DNS.5       = localhost
# DNS.6       = localhost.localdomain
# IP.1        = 127.0.0.1
# IP.2        = ::1

It's important to put DNS name in the SAN and not the CN, because both the IETF and the CA/Browser Forums specify the practice. They also specify that DNS names in the CN are deprecated (but not prohibited). If you put a DNS name in the CN, then it must be included in the SAN under the CA/B policies. So you can't avoid using the Subject Alternate Name.

If you don't do put DNS names in the SAN, then the certificate will fail to validate under a browser and other user agents which follow the CA/Browser Forum guidelines.

Related: browsers follow the CA/Browser Forum policies; and not the IETF policies. That's one of the reasons a certificate created with OpenSSL (which generally follows the IETF) sometimes does not validate under a browser (browsers follow the CA/B). They are different standards, they have different issuing policies and different validation requirements.


Create a self signed certificate (notice the addition of -x509 option):

openssl req -config example-com.conf -new -x509 -sha256 -newkey rsa:2048 -nodes \
    -keyout example-com.key.pem -days 365 -out example-com.cert.pem

Create a signing request (notice the lack of -x509 option):

openssl req -config example-com.conf -new -sha256 -newkey rsa:2048 -nodes \
    -keyout example-com.key.pem -days 365 -out example-com.req.pem

Print a self-signed certificate:

openssl x509 -in example-com.cert.pem -text -noout

Print a signing request:

openssl req -in example-com.req.pem -text -noout

Configuration file (passed via -config option)

[ req ]
default_bits        = 2048
default_keyfile     = server-key.pem
distinguished_name  = subject
req_extensions      = req_ext
x509_extensions     = x509_ext
string_mask         = utf8only

# The Subject DN can be formed using X501 or RFC 4514 (see RFC 4519 for a description).
#   Its sort of a mashup. For example, RFC 4514 does not provide emailAddress.
[ subject ]
countryName         = Country Name (2 letter code)
countryName_default     = US

stateOrProvinceName     = State or Province Name (full name)
stateOrProvinceName_default = NY

localityName            = Locality Name (eg, city)
localityName_default        = New York

organizationName         = Organization Name (eg, company)
organizationName_default    = Example, LLC

# Use a friendly name here because it's presented to the user. The server's DNS
#   names are placed in Subject Alternate Names. Plus, DNS names here is deprecated
#   by both IETF and CA/Browser Forums. If you place a DNS name here, then you
#   must include the DNS name in the SAN too (otherwise, Chrome and others that
#   strictly follow the CA/Browser Baseline Requirements will fail).
commonName          = Common Name (e.g. server FQDN or YOUR name)
commonName_default      = Example Company

emailAddress            = Email Address
emailAddress_default        = [email protected]

# Section x509_ext is used when generating a self-signed certificate. I.e., openssl req -x509 ...
[ x509_ext ]

subjectKeyIdentifier        = hash
authorityKeyIdentifier    = keyid,issuer

# You only need digitalSignature below. *If* you don't allow
#   RSA Key transport (i.e., you use ephemeral cipher suites), then
#   omit keyEncipherment because that's key transport.
basicConstraints        = CA:FALSE
keyUsage            = digitalSignature, keyEncipherment
subjectAltName          = @alternate_names
nsComment           = "OpenSSL Generated Certificate"

# RFC 5280, Section 4.2.1.12 makes EKU optional
#   CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused
#   In either case, you probably only need serverAuth.
# extendedKeyUsage    = serverAuth, clientAuth

# Section req_ext is used when generating a certificate signing request. I.e., openssl req ...
[ req_ext ]

subjectKeyIdentifier        = hash

basicConstraints        = CA:FALSE
keyUsage            = digitalSignature, keyEncipherment
subjectAltName          = @alternate_names
nsComment           = "OpenSSL Generated Certificate"

# RFC 5280, Section 4.2.1.12 makes EKU optional
#   CA/Browser Baseline Requirements, Appendix (B)(3)(G) makes me confused
#   In either case, you probably only need serverAuth.
# extendedKeyUsage    = serverAuth, clientAuth

[ alternate_names ]

DNS.1       = example.com
DNS.2       = www.example.com
DNS.3       = mail.example.com
DNS.4       = ftp.example.com

# Add these if you need them. But usually you don't want them or
#   need them in production. You may need them for development.
# DNS.5       = localhost
# DNS.6       = localhost.localdomain
# DNS.7       = 127.0.0.1

# IPv6 localhost
# DNS.8     = ::1

You may need to do the following for Chrome. Otherwise Chrome may complain a Common Name is invalid (ERR_CERT_COMMON_NAME_INVALID). I'm not sure what the relationship is between an IP address in the SAN and a CN in this instance.

# IPv4 localhost
# IP.1       = 127.0.0.1

# IPv6 localhost
# IP.2     = ::1

There are other rules concerning the handling of DNS names in X.509/PKIX certificates. Refer to these documents for the rules:

RFC 6797 and RFC 7469 are listed, because they are more restrictive than the other RFCs and CA/B documents. RFCs 6797 and 7469 do not allow an IP address, either.

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

For me I had to manually uninstall mysql

brew uninstall mysql
rm -rf /usr/local/var/mysql
brew install mysql

What are database normal forms and can you give examples?

Here's a quick, admittedly butchered response, but in a sentence:

1NF : Your table is organized as an unordered set of data, and there are no repeating columns.

2NF: You don't repeat data in one column of your table because of another column.

3NF: Every column in your table relates only to your table's key -- you wouldn't have a column in a table that describes another column in your table which isn't the key.

For more detail, see wikipedia...

Which is best data type for phone number in MySQL and what should Java type mapping for it be?

VARCHAR with probably 15-20 length would be sufficient and would be the best option for the database. Since you would probably require various hyphens and plus signs along with your phone numbers.

Float and double datatype in Java

According to the IEEE standards, float is a 32 bit representation of a real number while double is a 64 bit representation.

In Java programs we normally mostly see the use of double data type. It's just to avoid overflows as the range of numbers that can be accommodated using the double data type is more that the range when float is used.

Also when high precision is required, the use of double is encouraged. Few library methods that were implemented a long time ago still requires the use of float data type as a must (that is only because it was implemented using float, nothing else!).

But if you are certain that your program requires small numbers and an overflow won't occur with your use of float, then the use of float will largely improve your space complexity as floats require half the memory as required by double.

Disable output buffering

Yes, it is enabled by default. You can disable it by using the -u option on the command line when calling python.

Passing Multiple route params in Angular2

As detailed in this answer, mayur & user3869623's answer's are now relating to a deprecated router. You can now pass multiple parameters as follows:

To call router:

this.router.navigate(['/myUrlPath', "someId", "another ID"]);

In routes.ts:

{ path: 'myUrlpath/:id1/:id2', component: componentToGoTo},

Fuzzy matching using T-SQL

I would use SQL Server Full Text Indexing, which will allow you to do searches and return things that not only contain the word but also may have a misspelling.

Undo git update-index --assume-unchanged <file>

None of the solutions worked for me in Windows - it seems to use capital H rather than h for the file status and the grep command requires an extra caret as ^ also represents the start of line as well as negating the next character.

Windows solution

  1. Open Git Bash and change to the relevant top level directory.
  2. git ls-files -v | grep '^^H' to list all the uncached files
  3. git ls-files -v | grep '^^H' | cut -c 3- | tr '\012' '\000' | xargs -0 git update-index --no-skip-worktree to undo the files skipping of all files that was done via update-index --skip-worktree
  4. git ls-files -v | grep '^^H]' | cut -c 3- | tr '\012' '\000' | xargs -0 git update-index --no-assume-unchanged to undo the files skipping of all files that was done via update-index --assume-unchanged
  5. git ls-files -v | grep '^^H' to again list all the uncached files and check whether the above commands have worked - this should now not return anything

How to add soap header in java

I struggled to get this working. That's why I'll add a complete solution here:

My objective is to add this header to the SOAP envelope:

   <soapenv:Header>
      <urn:OTAuthentication>
         <urn:AuthenticationToken>TOKEN</urn:AuthenticationToken>
      </urn:OTAuthentication>
   </soapenv:Header>
  1. First create a SOAPHeaderHandler class.

    import java.util.Set;
    import java.util.TreeSet;
    
    import javax.xml.namespace.QName;
    import javax.xml.soap.SOAPElement;
    import javax.xml.soap.SOAPEnvelope;
    import javax.xml.soap.SOAPFactory;
    import javax.xml.soap.SOAPHeader;
    import javax.xml.ws.handler.MessageContext;
    import javax.xml.ws.handler.soap.SOAPHandler;
    import javax.xml.ws.handler.soap.SOAPMessageContext;
    
    public class SOAPHeaderHandler implements SOAPHandler<SOAPMessageContext> {
    
        private final String authenticatedToken;
    
        public SOAPHeaderHandler(String authenticatedToken) {
            this.authenticatedToken = authenticatedToken;
        }
    
        public boolean handleMessage(SOAPMessageContext context) {
            Boolean outboundProperty =
                    (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
            if (outboundProperty.booleanValue()) {
                try {
                    SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
                    SOAPFactory factory = SOAPFactory.newInstance();
                    String prefix = "urn";
                    String uri = "urn:api.ecm.opentext.com";
                    SOAPElement securityElem =
                            factory.createElement("OTAuthentication", prefix, uri);
                    SOAPElement tokenElem =
                            factory.createElement("AuthenticationToken", prefix, uri);
                    tokenElem.addTextNode(authenticatedToken);
                    securityElem.addChildElement(tokenElem);
                    SOAPHeader header = envelope.addHeader();
                    header.addChildElement(securityElem);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                // inbound
            }
            return true;
        }
    
        public Set<QName> getHeaders() {
            return new TreeSet();
        }
    
        public boolean handleFault(SOAPMessageContext context) {
            return false;
        }
    
        public void close(MessageContext context) {
            //
        }
    }
    
    1. Add the handler to the proxy. Note that according javax.xml.ws.Binding's documentation: "If the returned chain is modified a call to setHandlerChain is required to configure the binding instance with the new chain."

    Authentication_Service authentication_Service = new Authentication_Service();

    Authentication basicHttpBindingAuthentication = authentication_Service.getBasicHttpBindingAuthentication(); String authenticatedToken = "TOKEN"; List<Handler> handlerChain = ((BindingProvider)basicHttpBindingAuthentication).getBinding().getHandlerChain(); handlerChain.add(new SOAPHeaderHandler(authenticatedToken)); ((BindingProvider)basicHttpBindingAuthentication).getBinding().setHandlerChain(handlerChain);

Setting Inheritance and Propagation flags with set-acl and powershell

Just because you're in PowerShell don't forgot about good ol' exes. Sometimes they can provide the easiest solution e.g.:

icacls.exe $folder /grant 'domain\user:(OI)(CI)(M)'

Where is the web server root directory in WAMP?

If you installed WAMP to c:\wamp then I believe your webserver root directory would be c:\wamp\www, however this might vary depending on version.

Yes, this is where you would put your site files to access them through a browser.

How do I add 1 day to an NSDate?

Swift 4.0 (same as Swift 3.0 in this wonderful answer just making it clear for rookies like me)

let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)

How to Copy Text to Clip Board in Android?

 ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); 
 ClipData clip = ClipData.newPlainText(label, text);
 clipboard.setPrimaryClip(clip);

How do I change UIView Size?

I know that there is already a solution to this question, but I found an alternative to this issue and maybe it could help someone.

I was having trouble with setting the frame of my sub view because certain values were referring to its position within the main view. So if you don't want to update your frame by changing the whole frame via CGRect, you can simply change a value of the frame and then update it.

// keep reference to you frames
var questionView = questionFrame.frame
var answerView = answerFrame.frame

// update the values of the copy        
questionView.size.height = CGFloat(screenSize.height * 0.70)
answerView.size.height = CGFloat(screenSize.height * 0.30)

// set the frames to the new frames
questionFrame.frame = questionView
answerFrame.frame = answerView

How to add a fragment to a programmatically generated layout?

Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear). You can change number 3 with any other number or take a number from a spinner!

for (int i = 0; i < 3; i++) {
            LinearLayout linearDummy = new LinearLayout(getActivity());
            linearDummy.setOrientation(LinearLayout.VERTICAL);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {

                Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();

            } else {
                linearDummy.setId(View.generateViewId());
            }
            fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();

            xNumberLinear.addView(linearDummy);
        }

Creating and writing lines to a file

' Create The Object
Set FSO = CreateObject("Scripting.FileSystemObject")

' How To Write To A File
Set File = FSO.CreateTextFile("C:\foo\bar.txt",True)
File.Write "Example String"
File.Close

' How To Read From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Do Until File.AtEndOfStream
    Line = File.ReadLine
    WScript.Echo(Line)
Loop
File.Close

' Another Method For Reading From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Set Text = File.ReadAll
WScript.Echo(Text)
File.Close

Get image data url in JavaScript?

Coming long after, but none of the answers here are entirely correct.

When drawn on a canvas, the passed image is uncompressed + all pre-multiplied.
When exported, its uncompressed or recompressed with a different algorithm, and un-multiplied.

All browsers and devices will have different rounding errors happening in this process
(see Canvas fingerprinting).

So if one wants a base64 version of an image file, they have to request it again (most of the time it will come from cache) but this time as a Blob.

Then you can use a FileReader to read it either as an ArrayBuffer, or as a dataURL.

_x000D_
_x000D_
function toDataURL(url, callback){_x000D_
    var xhr = new XMLHttpRequest();_x000D_
    xhr.open('get', url);_x000D_
    xhr.responseType = 'blob';_x000D_
    xhr.onload = function(){_x000D_
      var fr = new FileReader();_x000D_
    _x000D_
      fr.onload = function(){_x000D_
        callback(this.result);_x000D_
      };_x000D_
    _x000D_
      fr.readAsDataURL(xhr.response); // async call_x000D_
    };_x000D_
    _x000D_
    xhr.send();_x000D_
}_x000D_
_x000D_
toDataURL(myImage.src, function(dataURL){_x000D_
  result.src = dataURL;_x000D_
_x000D_
  // now just to show that passing to a canvas doesn't hold the same results_x000D_
  var canvas = document.createElement('canvas');_x000D_
  canvas.width = myImage.naturalWidth;_x000D_
  canvas.height = myImage.naturalHeight;_x000D_
  canvas.getContext('2d').drawImage(myImage, 0,0);_x000D_
_x000D_
  console.log(canvas.toDataURL() === dataURL); // false - not same data_x000D_
  });
_x000D_
<img id="myImage" src="https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png" crossOrigin="anonymous">_x000D_
<img id="result">
_x000D_
_x000D_
_x000D_

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

Using the AWS Management Console

  • Go to "Volumes" and create a Snapshot of your instance's volume.
  • Go to "Snapshots" and select "Create Image from Snapshot".
  • Go to "AMIs" and select "Launch Instance" and choose your "Instance Type" etc.

How to insert a newline in front of a pattern?

In this case, I do not use sed. I use tr.

cat Somefile |tr ',' '\012' 

This takes the comma and replaces it with the carriage return.

No tests found with test runner 'JUnit 4'

My problem was using **

testng

** package org.testng.Assert;

You can replace it in libraries of the project (Maven) with JUnit and then need to refactor project.
OR add TestNG Eclipse plug-in

http://testng.org/doc/eclipse.html

Rename Excel Sheet with VBA Macro

The "no frills" options are as follows:

ActiveSheet.Name = "New Name"

and

Sheets("Sheet2").Name = "New Name"

You can also check out recording macros and seeing what code it gives you, it's a great way to start learning some of the more vanilla functions.

How to solve "java.io.IOException: error=12, Cannot allocate memory" calling Runtime#exec()?

What's the memory profile of your machine ? e.g. if you run top, how much free memory do you have ?

I suspect UnixProcess performs a fork() and it's simply not getting enough memory from the OS (if memory serves, it'll fork() to duplicate the process and then exec() to run the ls in the new memory process, and it's not getting as far as that)

EDIT: Re. your overcommit solution, it permits overcommitting of system memory, possibly allowing processes to allocate (but not use) more memory than is actually available. So I guess that the fork() duplicates the Java process memory as discussed in the comments below. Of course you don't use the memory since the 'ls' replaces the duplicate Java process.

WPF ListView turn off selection

Set the style of each ListViewItem to have Focusable set to false.

<ListView ItemsSource="{Binding Test}" >
    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="Focusable" Value="False"/>
        </Style>
    </ListView.ItemContainerStyle>
</ListView>

sorting and paging with gridview asp.net

Tarkus's answer works well. However, I would suggest replacing VIEWSTATE with SESSION.

The current page's VIEWSTATE only works while the current page posts back to itself and is gone once the user is redirected away to another page. SESSION persists the sort order on more than just the current page's post-back. It persists it across the entire duration of the session. This means that the user can surf around to other pages, and when he comes back to the given page, the sort order he last used still remains. This is usually more convenient.

There are other methods, too, such as persisting user profiles.

I recommend this article for a very good explanation of ViewState and how it works with a web page's life cycle: https://msdn.microsoft.com/en-us/library/ms972976.aspx

To understand the difference between VIEWSTATE, SESSION and other ways of persisting variables, I recommend this article: https://msdn.microsoft.com/en-us/library/75x4ha6s.aspx

Returning JSON from a PHP Script

If you query a database and need the result set in JSON format it can be done like this:

<?php

$db = mysqli_connect("localhost","root","","mylogs");
//MSG
$query = "SELECT * FROM logs LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
    $rows[] = $row;
}
//Return result to jTable
$qryResult = array();
$qryResult['logs'] = $rows;
echo json_encode($qryResult);

mysqli_close($db);

?>

For help in parsing the result using jQuery take a look at this tutorial.

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

Jacob Helwig mentions in his answer that:

It looks like rev-parse is being used without sufficient error checking before-hand

Commit 62f162f from Jeff King (peff) should improve the robustness of git rev-parse in Git 1.9/2.0 (Q1 2014) (in addition of commit 1418567):

For cases where we do not match (e.g., "doesnotexist..HEAD"), we would then want to try to treat the argument as a filename.
try_difference() gets this right, and always unmunges in this case.
However, try_parent_shorthand() never unmunges, leading to incorrect error messages, or even incorrect results:

$ git rev-parse foobar^@
foobar
fatal: ambiguous argument 'foobar': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

maven compilation failure

I had a similar problem, and never find anything on the web after excessive searching.

I reviewed the pom.xml file and in the dependencies I changed the scope of the <dependency> it: <scope>test</scope> to <scope>compile</scope> .

Previously I was using it only for tests but I change the project's structure and never knew I hve to change this.

test: This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.

compile: This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.

Here is a reference from Apache Maven Docs: https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope

URL encoding in Android

I'm going to add one suggestion here. You can do this which avoids having to get any external libraries.

Give this a try:

String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();

You can see that in this particular URL, I need to have those spaces encoded so that I can use it for a request.

This takes advantage of a couple features available to you in Android classes. First, the URL class can break a url into its proper components so there is no need for you to do any string search/replace work. Secondly, this approach takes advantage of the URI class feature of properly escaping components when you construct a URI via components rather than from a single string.

The beauty of this approach is that you can take any valid url string and have it work without needing any special knowledge of it yourself.

Android: Internet connectivity change listener

ConnectivityAction is deprecated in api 28+. Instead you can use registerDefaultNetworkCallback as long as you support api 24+.

In Kotlin:

val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager?.let {
    it.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {
            //take action when network connection is gained
        }
        override fun onLost(network: Network?) {
            //take action when network connection is lost
        }
    })
}

How to show and update echo on same line

You can try this.. My own version of it..

funcc() {
while true ; do 
for i in \| \/ \- \\ \| \/ \- \\; do 
  echo -n -e "\r$1  $i  "
sleep 0.5
done  
#echo -e "\r                                                                                      "
[ -f /tmp/print-stat ] && break 2
done
}

funcc "Checking Kubectl" & &>/dev/null
sleep 5
touch /tmp/print-stat
echo -e "\rPrint Success                  "

Make xargs execute the command once for each line of input

find path -type f | xargs -L1 command 

is all you need.

How to retrieve a user environment variable in CMake (Windows)

Getting variables into your CMake script

You can pass a variable on the line with the cmake invocation:

FOO=1 cmake

or by exporting a variable in BASH:

export FOO=1

Then you can pick it up in a cmake script using:

$ENV{FOO}

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

Here is what you do in Excel 2003:

  1. In your sheet of interest, go to Format -> Sheet -> Hide and hide your sheet.
  2. Go to Tools -> Protection -> Protect Workbook, make sure Structure is selected, and enter your password of choice.

Here is what you do in Excel 2007:

  1. In your sheet of interest, go to Home ribbon -> Format -> Hide & Unhide -> Hide Sheet and hide your sheet.
  2. Go to Review ribbon -> Protect Workbook, make sure Structure is selected, and enter your password of choice.

Once this is done, the sheet is hidden and cannot be unhidden without the password. Make sense?


If you really need to keep some calculations secret, try this: use Access (or another Excel workbook or some other DB of your choice) to calculate what you need calculated, and export only the "unclassified" results to your Excel workbook.

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

Instead of thinking of it as 'extracting', I like to think of it as 'isolating'. Once the desired bits are isolated, you can do what you will with them.

To isolate any set of bits, apply an AND mask.

If you want the last X bits of a value, there is a simple trick that can be used.

unsigned  mask;
mask = (1 << X) - 1;
lastXbits = value & mask;

If you want to isolate a run of X bits in the middle of 'value' starting at 'startBit' ...

unsigned  mask;
mask = ((1 << X) - 1) << startBit;
isolatedXbits = value & mask;

Hope this helps.

How to convert an Image to base64 string in java?

this did it for me. you can vary the options for the output format to Base64.Default whatsoever.

// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);

Change priorityQueue to max priorityqueue

The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time.

The Comparator should override the compare method.

int compare(T o1, T o2)

Default compare method returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

The Default PriorityQueue provided by Java is Min-Heap, If you want a max heap following is the code

public class Sample {
    public static void main(String[] args) {
        PriorityQueue<Integer> q = new PriorityQueue<Integer>(new Comparator<Integer>() {

            public int compare(Integer lhs, Integer rhs) {
                if(lhs<rhs) return +1;
                if(lhs>rhs) return -1;
                return 0;
            }
        });
        q.add(13);
        q.add(4);q.add(14);q.add(-4);q.add(1);
        while (!q.isEmpty()) {
            System.out.println(q.poll());
        }
    }

}

Reference :https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html#comparator()

What does the @ symbol before a variable name mean in C#?

The @ symbol allows you to use reserved word. For example:

int @class = 15;

The above works, when the below wouldn't:

int class = 15;

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

I got this issue when deploying to Azure using the Publish feature. Remember to clear files at destination.

Publish Settings -> File Publish Options drop down -> Check Remove additional files at destination

This solved my issue, in case people have to hunt around for this like I did. Everything was the same version in my project/solution, just not at the destination I was deploying to.

How to get only filenames within a directory using c#?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetNameOfFiles
{
    public class Program
    {
        static void Main(string[] args)
        {
           string[] fileArray = Directory.GetFiles(@"YOUR PATH");
           for (int i = 0; i < fileArray.Length; i++)
           {

               Console.WriteLine(fileArray[i]);
           }
            Console.ReadLine();
        }
    }
}

Directory index forbidden by Options directive

Insert this lines:

<Directory "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs">
        Options  +Indexes
</Directory>

In your C:\Program Files (x86)\Apache Software Foundation\Apache2.2\conf\extra\httpd-vhosts.conf file. I assume you are using Virtual Host for development.

And then, of course, just restart Apache.

Documentation

Object comparison in JavaScript

if you want to check for methods explicitly you can use the method.toSource() or method.toString() methods.

How to downgrade the installed version of 'pip' on windows?

well the only thing that will work is

python -m pip install pip==

you can and should run it under IDE terminal (mine was pycharm)

PHP Multiple Checkbox Array

<form method='post' id='userform' action='thisform.php'> <tr>
    <td>Trouble Type</td>
    <td>
    <input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Three'>3
    </td> </tr> </table> <input type='submit' class='buttons'> </form>

<?php 
if (isset($_POST['checkboxvar'])) 
{
    print_r($_POST['checkboxvar']); 
}
?>

You pass the form name as an array and then you can access all checked boxes using the var itself which would then be an array.

To echo checked options into your email you would then do this:

echo implode(',', $_POST['checkboxvar']); // change the comma to whatever separator you want

Please keep in mind you should always sanitize your input as needed.

For the record, official docs on this exist: http://php.net/manual/en/faq.html.php#faq.html.arrays

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?

Easy:

SELECT question_id, wm_concat(element_id) as elements
FROM   questions
GROUP BY question_id;

Pesonally tested on 10g ;-)

From http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

Let's start with the problems these tools want to solve:

My system package manager don't have the Python versions I wanted or I want to install multiple Python versions side by side, Python 3.9.0 and Python 3.9.1, Python 3.5.3, etc

Then use pyenv.

I want to install and run multiple applications with different, conflicting dependencies.

Then use virtualenv or venv. These are almost completely interchangeable, the difference being that virtualenv supports older python versions and has a few more minor unique features, while venv is in the standard library.

I'm developing an /application/ and need to manage my dependencies, and manage the dependency resolution of the dependencies of my project.

Then use pipenv or poetry.

I'm developing a /library/ or a /package/ and want to specify the dependencies that my library users need to install

Then use setuptools.

I used virtualenv, but I don't like virtualenv folders being scattered around various project folders. I want a centralised management of the environments and some simple project management

Then use virtualenvwrapper. Variant: pyenv-virtualenvwrapper if you also use pyenv.


Not recommended

  • pyvenv. This is deprecated, use venv or virtualenv instead. Not to be confused with pipenv or pyenv.

How should I cast in VB.NET?

At one time, I remember seeing the MSDN library state to use CStr() because it was faster. I do not know if this is true though.

How to extract numbers from a string in Python?

Using Regex below is the way

lines = "hello 12 hi 89"
import re
output = []
#repl_str = re.compile('\d+.?\d*')
repl_str = re.compile('^\d+$')
#t = r'\d+.?\d*'
line = lines.split()
for word in line:
        match = re.search(repl_str, word)
        if match:
            output.append(float(match.group()))
print (output)

with findall re.findall(r'\d+', "hello 12 hi 89")

['12', '89']

re.findall(r'\b\d+\b', "hello 12 hi 89 33F AC 777")

['12', '89', '777']

Convert an object to an XML string

    public static string Serialize(object dataToSerialize)
    {
        if(dataToSerialize==null) return null;

        using (StringWriter stringwriter = new System.IO.StringWriter())
        {
            var serializer = new XmlSerializer(dataToSerialize.GetType());
            serializer.Serialize(stringwriter, dataToSerialize);
            return stringwriter.ToString();
        }
    }

    public static T Deserialize<T>(string xmlText)
    {
        if(String.IsNullOrWhiteSpace(xmlText)) return default(T);

        using (StringReader stringReader = new System.IO.StringReader(xmlText))
        {
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stringReader);
        }
    }

Spring JPA selecting specific columns

With the newer Spring versions One can do as follows:

If not using native query this can done as below:

public interface ProjectMini {
    String getProjectId();
    String getProjectName();
}

public interface ProjectRepository extends JpaRepository<Project, String> { 
    @Query("SELECT p FROM Project p")
    List<ProjectMini> findAllProjectsMini();
}

Using native query the same can be done as below:

public interface ProjectRepository extends JpaRepository<Project, String> { 
    @Query(value = "SELECT projectId, projectName FROM project", nativeQuery = true)
    List<ProjectMini> findAllProjectsMini();
}

For detail check the docs

bootstrap datepicker setDate format dd/mm/yyyy

"As with bootstrap’s own plugins, datepicker provides a data-api that can be used to instantiate datepickers without the need for custom javascript..."

Boostrap DatePicker Documentation

Maybe you want to set format without DatePicker instance, for that, you have to add the property data-date-format="DateFormat" to main Div tag, for example:

<div class="input-group date" data-provide="datepicker" data-date-format="yyyy-mm-dd">
    <div class="input-group-addon">
        <span class="glyphicon glyphicon-th"></span>
    </div>

    <input type="text" name="YourName" id="YourId" class="YourClass">
</div>

In nodeJs is there a way to loop through an array without using array size?

What you probably want is for...of, a relatively new construct built for the express purpose of enumerating the values of iterable objects:

_x000D_
_x000D_
let myArray = ["a","b","c","d"];_x000D_
for (let item of myArray) {_x000D_
  console.log(item);_x000D_
}
_x000D_
_x000D_
_x000D_

... as distinct from for...in, which enumerates property names (presumably1 numeric indices in the case of arrays). Your loop displayed unexpected results because you didn't use the property names to get the corresponding values via bracket notation... but you could have:

_x000D_
_x000D_
let myArray = ["a","b","c","d"];_x000D_
for (let key in myArray) {_x000D_
  let value =  myArray[key]; // get the value by key_x000D_
  console.log("key: %o, value: %o", key, value);_x000D_
}
_x000D_
_x000D_
_x000D_

1 Unfortunately, someone may have added enumerable properties to the array or its prototype chain which are not numeric indices... or they may have assigned an index leaving unassigned indices in the interim range. The issues are explained pretty well here. The main takeaway is that it's best to loop explicitly from 0 to array.length - 1 rather than using for...in.

So, this is not (as I'd originally thought) an academic question, i.e.:

Without regard for practicality, is it possible to avoid length when iterating over an array?

According to your comment (emphasis mine):

[...] why do I need to calculate the size of an array whereas the interpreter can know it.

You have a misguided aversion to Array.length. It's not calculated on the fly; it's updated whenever the length of the array changes. You're not going to see performance gains by avoiding it (apart from caching the array length rather than accessing the property):

loop test

Now, even if you did get some marginal performance increase, I doubt it would be enough to justify the risk of dealing with the aforementioned issues.

Group list by values

len = max(key for (item, key) in list)
newlist = [[] for i in range(len+1)]
for item,key in list:
  newlist[key].append(item)

You can do it in a single list comprehension, perhaps more elegant but O(n**2):

[[item for (item,key) in list if key==i] for i in range(max(key for (item,key) in list)+1)]

Select distinct rows from datatable in Linq

Dim distinctValues As List(Of Double) = (From r In _
DirectCast(DataTable.AsEnumerable(),IEnumerable(Of DataRow)) Where (Not r.IsNull("ColName")) _
Select r.Field(Of Double)("ColName")).Distinct().ToList()

Marquee text in Android

android:ellipsize="marquee"

This only works when your TextView has the focus.

change <audio> src with javascript

Here is how I did it using React and CJSX (Coffee JSX) based on Vitim.us solution. Using componentWillReceiveProps I was able to detect every property changes. Then I just check whether the url has changed between the future props and the current one. And voilà.

@propTypes =
    element: React.PropTypes.shape({
         version: React.PropTypes.number
         params:
             React.PropTypes.shape(
                 url: React.PropTypes.string.isRequired
                 filename: React.PropTypes.string.isRequired
                 title: React.PropTypes.string.isRequired
                 ext: React.PropTypes.string.isRequired
             ).isRequired
     }).isRequired

componentWillReceiveProps: (nextProps) ->
    element = ReactDOM.findDOMNode(this)
    audio = element.querySelector('audio')
    source = audio.querySelector('source')

    # When the url changes, we refresh the component manually so it reloads the loaded file
    if nextProps.element.params?.filename? and
    nextProps.element.params.url isnt @props.element.params.url
        source.src = nextProps.element.params.url
        audio.load()

I had to do it this way, because even a change of state or a force redraw didn't work.

How to select last one week data from today's date

Yes, the syntax is accurate and it should be fine.

Here is the SQL Fiddle Demo I created for your particular case

create table sample2
(
    id int primary key,
    created_date date,
    data varchar(10)
  )

insert into sample2 values (1,'2012-01-01','testing');

And here is how to select the data

SELECT Created_Date
FROM sample2
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

Get total number of items on Json object?

That's an Object and you want to count the properties of it.

Object.keys(jsonArray).length

References:

Making text bold using attributed string in swift

I extended David West's great answer so that you can input a string and tell it all the substrings you would like to embolden:

func addBoldText(fullString: NSString, boldPartsOfString: Array<NSString>, font: UIFont!, boldFont: UIFont!) -> NSAttributedString {
    let nonBoldFontAttribute = [NSFontAttributeName:font!]
    let boldFontAttribute = [NSFontAttributeName:boldFont!]
    let boldString = NSMutableAttributedString(string: fullString as String, attributes:nonBoldFontAttribute)
    for i in 0 ..< boldPartsOfString.count {
        boldString.addAttributes(boldFontAttribute, range: fullString.rangeOfString(boldPartsOfString[i] as String))
    }
    return boldString
}

And then call it like this:

let normalFont = UIFont(name: "Dosis-Medium", size: 18)
let boldSearchFont = UIFont(name: "Dosis-Bold", size: 18)
self.UILabel.attributedText = addBoldText("Check again in 30 days to find more friends", boldPartsOfString: ["Check", "30 days", "find", "friends"], font: normalFont!, boldFont: boldSearchFont!)

This will embolden all the substrings you want bolded in your given string

CSS text-transform capitalize on all caps

If the data is coming from a database, as in my case, you can lower it before sending it to a select list/drop down list. Shame you can't do it in CSS.

"break;" out of "if" statement?

I think the question is a little bit fuzzy - for example, it can be interpreted as a question about best practices in programming loops with if inside. So, I'll try to answer this question with this particular interpretation.

If you have if inside a loop, then in most cases you'd like to know how the loop has ended - was it "broken" by the if or was it ended "naturally"? So, your sample code can be modified in this way:

bool intMaxFound = false;
for (size = 0; size < HAY_MAX; size++)
{
  // wait for hay until EOF
  printf("\nhaystack[%d] = ", size);
  int straw = GetInt();
  if (straw == INT_MAX)
     {intMaxFound = true; break;}

  // add hay to stack
  haystack[size] = straw;
}
if (intMaxFound)
{
  // ... broken
}
else
{
  // ... ended naturally
}

The problem with this code is that the if statement is buried inside the loop body, and it takes some effort to locate it and understand what it does. A more clear (even without the break statement) variant will be:

bool intMaxFound = false;
for (size = 0; size < HAY_MAX && !intMaxFound; size++)
{
  // wait for hay until EOF
  printf("\nhaystack[%d] = ", size);
  int straw = GetInt();
  if (straw == INT_MAX)
     {intMaxFound = true; continue;}

  // add hay to stack
  haystack[size] = straw;
}
if (intMaxFound)
{
  // ... broken
}
else
{
  // ... ended naturally
}

In this case you can clearly see (just looking at the loop "header") that this loop can end prematurely. If the loop body is a multi-page text, written by somebody else, then you'd thank its author for saving your time.

UPDATE:

Thanks to SO - it has just suggested the already answered question about crash of the AT&T phone network in 1990. It's about a risky decision of C creators to use a single reserved word break to exit from both loops and switch.

Anyway this interpretation doesn't follow from the sample code in the original question, so I'm leaving my answer as it is.

Image convert to Base64

It's useful to work with Deferred Object in this case, and return promise:

function readImage(inputElement) {
    var deferred = $.Deferred();

    var files = inputElement.get(0).files;
    if (files && files[0]) {
        var fr= new FileReader();
        fr.onload = function(e) {
            deferred.resolve(e.target.result);
        };
        fr.readAsDataURL( files[0] );
    } else {
        deferred.resolve(undefined);
    }

    return deferred.promise();
}

And above function could be used in this way:

var inputElement = $("input[name=file]");
readImage(inputElement).done(function(base64Data){
    alert(base64Data);
});

Or in your case:

$(input).on('change',function(){
  readImage($(this)).done(function(base64Data){ alert(base64Data); });
});

Resize on div element

Just try this func (it may work not only for divs):

function resized(elem, func = function(){}, args = []){
    elem = jQuery(elem);
    func = func.bind(elem);
    var h = -1, w = -1;
    setInterval(function(){
        if (elem.height() != h || elem.width() != w){
            h = elem.height();
            w = elem.width();
            func.apply(null, args);
        }
    }, 100);
}

You can use it like this

resized(/*element*/ '.advs-columns-main > div > div', /*callback*/ function(a){
    console.log(a);
    console.log(this); //for accessing the jQuery element you passed
}, /*callback arguments in array*/ ['I\'m the first arg named "a"!']);

UPDATE: You can also use more progressive watcher (it can work for any objects, not only DOM elements):

function changed(elem, propsToBeChanged, func = function(){}, args = [], interval = 100){
        func = func.bind(elem);
        var currentVal = {call: {}, std: {}};
        $.each(propsToBeChanged, (property, needCall)=>{
            needCall = needCall ? 'call' : 'std';
            currentVal[needCall][property] = new Boolean(); // is a minimal and unique value, its equivalent comparsion with each other will always return false
        });
        setInterval(function(){
            $.each(propsToBeChanged, (property, needCall)=>{
                try{
                    var currVal = needCall ? elem[property]() : elem[property];
                } catch (e){ // elem[property] is not a function anymore
                    var currVal = elem[property];
                    needCall = false;
                    propsToBeChanged[property] = false;
                }
                needCall = needCall ? 'call' : 'std';
                if (currVal !== currentVal[needCall][property]){
                    currentVal[needCall][property] = currVal;
                    func.apply(null, args);
                }
            });
        }, interval);
    }

Just try it:

var b = '2',
    a = {foo: 'bar', ext: ()=>{return b}};
changed(a, {
// prop name || do eval like a function?
    foo:        false,
    ext:        true
}, ()=>{console.log('changed')})

It will log 'changed' every time when you change b, a.foo or a.ext directly

How to set a default value for an existing column

The correct way to do this is as follows:

  1. Run the command:

    sp_help [table name] 
    
  2. Copy the name of the CONSTRAINT.

  3. Drop the DEFAULT CONSTRAINT:

    ALTER TABLE [table name] DROP [NAME OF CONSTRAINT] 
    
  4. Run the command below:

    ALTER TABLE [table name] ADD DEFAULT [DEFAULT VALUE] FOR [NAME OF COLUMN]
    

virtualenvwrapper and Python 3

If you already have python3 installed as well virtualenvwrapper the only thing you would need to do to use python3 with the virtual environment is creating an environment using:

which python3 #Output: /usr/bin/python3
mkvirtualenv --python=/usr/bin/python3 nameOfEnvironment

Or, (at least on OSX using brew):

mkvirtualenv --python=`which python3` nameOfEnvironment

Start using the environment and you'll see that as soon as you type python you'll start using python3

Unable to import path from django.urls

Python 2 doesn't support Django 2. On a Mac once you've installed Python 3 and Django 2 run the following command from shell to run your app while keeping path:

python3 manage.py runserver

Even if you have upgraded and are on a mac you will, by default, run Python 2 if you're entering the following command:

python manage.py runserver

The version of Django will then be wrong and you will see import errors for path

Padding or margin value in pixels as integer using jQuery

Shamelessly adopted from Quickredfox.

jQuersy.fn.cssNum = function(){
    return parseInt(jQuery.fn.css.apply(this, arguments), 10);
};

update

Changed to parseInt(val, 10) since it is faster than parseFloat.

http://jsperf.com/number-vs-plus-vs-toint-vs-tofloat/20

How to open in default browser in C#

After researching a lot I feel most of the given answer will not work with dotnet core. 1.System.Diagnostics.Process.Start("http://google.com"); -- Will not work with dotnet core

2.It will work but it will block the new window opening in case default browser is chrome

 myProcess.StartInfo.UseShellExecute = true; 
    myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
    myProcess.Start();

Below is the simplest and will work in all the scenarios.

Process.Start("explorer", url);

Find kth smallest element in a binary search tree in Optimum way

//add a java version without recursion

public static <T> void find(TreeNode<T> node, int num){
    Stack<TreeNode<T>> stack = new Stack<TreeNode<T>>();

    TreeNode<T> current = node;
    int tmp = num;

    while(stack.size() > 0 || current!=null){
        if(current!= null){
            stack.add(current);
            current = current.getLeft();
        }else{
            current = stack.pop();
            tmp--;

            if(tmp == 0){
                System.out.println(current.getValue());
                return;
            }

            current = current.getRight();
        }
    }
}

Rotating a two-dimensional array in Python

Rotating Counter Clockwise ( standard column to row pivot ) As List and Dict

rows = [
  ['A', 'B', 'C', 'D'],
  [1,2,3,4],
  [1,2,3],
  [1,2],
  [1],
]

pivot = []

for row in rows:
  for column, cell in enumerate(row):
    if len(pivot) == column: pivot.append([])
    pivot[column].append(cell)

print(rows)
print(pivot)
print(dict([(row[0], row[1:]) for row in pivot]))

Produces:

[['A', 'B', 'C', 'D'], [1, 2, 3, 4], [1, 2, 3], [1, 2], [1]]
[['A', 1, 1, 1, 1], ['B', 2, 2, 2], ['C', 3, 3], ['D', 4]]
{'A': [1, 1, 1, 1], 'B': [2, 2, 2], 'C': [3, 3], 'D': [4]}

Remove a cookie

You May Try this

if (isset($_COOKIE['remember_user'])) {
    unset($_COOKIE['remember_user']); 
    setcookie('remember_user', null, -1, '/'); 
    return true;
} else {
    return false;
}

How do I get the SharedPreferences from a PreferenceActivity in Android?

Declare these methods first..

public static void putPref(String key, String value, Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(key, value);
    editor.commit();
}

public static String getPref(String key, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(key, null);
}

Then call this when you want to put a pref:

putPref("myKey", "mystring", getApplicationContext());

call this when you want to get a pref:

getPref("myKey", getApplicationContext());

Or you can use this object https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo which simplifies everything even further

Example:

TinyDB tinydb = new TinyDB(context);

tinydb.putInt("clickCount", 2);
tinydb.putFloat("xPoint", 3.6f);
tinydb.putLong("userCount", 39832L);

tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true); 

tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);

npm install hangs

install nvm (Node Version Manager) and downgrade node version from 14 to 12 solved the issue in my case

Presto SQL - Converting a date string to date format

Converted DateID having date in Int format to date format: Presto Query

Select CAST(date_format(date_parse(cast(dateid as varchar(10)), '%Y%m%d'), '%Y/%m-%d') AS DATE)
from
     Table_Name
limit 10;

Git commit date

You can use the git show command.

To get the last commit date from git repository in a long(Unix epoch timestamp):

  • Command: git show -s --format=%ct
  • Result: 1605103148

Note: You can visit the git-show documentation to get a more detailed description of the options.

org.apache.jasper.JasperException: Unable to compile class for JSP:

I was facing the issue, i found that that older ecj library is present in Apache Tomcat directory 1)remove old jar from Apache Tomcat library 2)clean the project 3)build it. It started working as expected.

Regex for Mobile Number Validation

This regex is very short and sweet for working.

/^([+]\d{2})?\d{10}$/

Ex: +910123456789 or 0123456789

-> /^ and $/ is for starting and ending
-> The ? mark is used for conditional formatting where before question mark is available or not it will work
-> ([+]\d{2}) this indicates that the + sign with two digits '\d{2}' here you can place digit as per country
-> after the ? mark '\d{10}' this says that the digits must be 10 of length change as per your country mobile number length

This is how this regex for mobile number is working.
+ sign is used for world wide matching of number.

if you want to add the space between than you can use the

[ ]

here the square bracket represents the character sequence and a space is character for searching in regex.
for the space separated digit you can use this regex

/^([+]\d{2}[ ])?\d{10}$/

Ex: +91 0123456789

Thanks ask any question if you have.

How do I get the value of a registry key and ONLY the value using powershell

Well you need to be specific here. As far as I know, the key in a registry is a "folder" of properties. So did you mean get the value of a property? If so, try something like this:

(Get-ItemProperty HKLM:\Software\Microsoft\PowerShell\1\PowerShellEngine -Name PowerShellVersion).PowerShellVersion

First we get an object containing the property we need with Get-ItemProperty and then we get the value of for the property we need from that object. That will return the value of the property as a string. The example above gives you the PS version for "legacy"/compatibility-mdoe powershell (1.0 or 2.0).

How can I print the contents of an array horizontally?

Just loop through the array and write the items to the console using Write instead of WriteLine:

foreach(var item in array)
    Console.Write(item.ToString() + " ");

As long as your items don't have any line breaks, that will produce a single line.

...or, as Jon Skeet said, provide a little more context to your question.

Get content of a cell given the row and column numbers

It took me a while, but here's how I made it dynamic. It doesn't depend on a sorted table.

First I started with a column of state names (Column A) and a column of aircraft in each state (Column B). (Row 1 is a header row).

Finding the cell that contains the number of aircraft was:

=MATCH(MAX($B$2:$B$54),$B$2:$B$54,0)+MIN(ROW($B$2:$B$54))-1

I put that into a cell and then gave that cell a name, "StateRow" Then using the tips from above, I wound up with this:

=INDIRECT(ADDRESS(StateRow,1))

This returns the name of the state from the dynamic value in row "StateRow", column 1

Now, as the values in the count column change over time as more data is entered, I always know which state has the most aircraft.

Why do you need to put #!/bin/bash at the beginning of a script file?

It is called a shebang. It consists of a number sign and an exclamation point character (#!), followed by the full path to the interpreter such as /bin/bash. All scripts under UNIX and Linux execute using the interpreter specified on a first line.

mongodb service is not starting up

For ubunto , what made it happen and was real simple is to install mongodb package:

sudo apt-get install  mongodb

How can I debug what is causing a connection refused or a connection time out?

The problem

The problem is in the network layer. Here are the status codes explained:

  • Connection refused: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.

  • Connection timed out: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.

In context

That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.

Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.

It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.

Debugging this

As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.

To rule out network congestion as a problem you could use a tool like mtr or traceroute or even ping to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.

Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).

If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp is definetly recommended then.

Using Panel or PlaceHolder

The Placeholder does not render any tags for itself, so it is great for grouping content without the overhead of outer HTML tags.

The Panel does have outer HTML tags but does have some cool extra properties.

  • BackImageUrl: Gets/Sets the background image's URL for the panel

  • HorizontalAlign: Gets/Sets the
    horizontal alignment of the parent's contents

  • Wrap: Gets/Sets whether the
    panel's content wraps

There is a good article at startvbnet here.

What are 'get' and 'set' in Swift?

The getting and setting of variables within classes refers to either retrieving ("getting") or altering ("setting") their contents.

Consider a variable members of a class family. Naturally, this variable would need to be an integer, since a family can never consist of two point something people.

So you would probably go ahead by defining the members variable like this:

class family {
   var members:Int
}

This, however, will give people using this class the possibility to set the number of family members to something like 0 or 1. And since there is no such thing as a family of 1 or 0, this is quite unfortunate.

This is where the getters and setters come in. This way you can decide for yourself how variables can be altered and what values they can receive, as well as deciding what content they return.

Returning to our family class, let's make sure nobody can set the members value to anything less than 2:

class family {
  var _members:Int = 2
  var members:Int {
   get {
     return _members
   }
   set (newVal) {
     if newVal >= 2 {
       _members = newVal
     } else {
       println('error: cannot have family with less than 2 members')
     }
   }
  }
}

Now we can access the members variable as before, by typing instanceOfFamily.members, and thanks to the setter function, we can also set it's value as before, by typing, for example: instanceOfFamily.members = 3. What has changed, however, is the fact that we cannot set this variable to anything smaller than 2 anymore.

Note the introduction of the _members variable, which is the actual variable to store the value that we set through the members setter function. The original members has now become a computed property, meaning that it only acts as an interface to deal with our actual variable.

Calculating Pearson correlation and significance in Python

I have a very simple and easy to understand solution for this. For two arrays of equal length, Pearson coefficient can be easily computed as follows:

def manual_pearson(a,b):
"""
Accepts two arrays of equal length, and computes correlation coefficient. 
Numerator is the sum of product of (a - a_avg) and (b - b_avg), 
while denominator is the product of a_std and b_std multiplied by 
length of array. 
"""
  a_avg, b_avg = np.average(a), np.average(b)
  a_stdev, b_stdev = np.std(a), np.std(b)
  n = len(a)
  denominator = a_stdev * b_stdev * n
  numerator = np.sum(np.multiply(a-a_avg, b-b_avg))
  p_coef = numerator/denominator
  return p_coef

Bootstrap: Position of dropdown menu relative to navbar item

Boostrap has a class for that called navbar-right. So your code will look as follows:

<ul class="nav navbar-right">
    <li class="dropdown">
      <a class="dropdown-toggle" href="#" data-toggle="dropdown">Link</a>
      <ul class="dropdown-menu">
         <li>...</li>
      </ul>
    </li>
</ul>

How to use HTML to print header and footer on every printed page of a document?

If you can use javascipt, have the client handle laying out the content using javascript to place elements based on available space.

You could use the jquery columnizer plugin to dynamically lay out your content in fixed size blocks and position your headers and footers as part of the rendering routine. http://welcome.totheinter.net/columnizer-jquery-plugin/

See example 10 http://welcome.totheinter.net/autocolumn/sample10.html

The browser will still add its own headers or footers if enabled in the os. Consistent layout across platforms and browsers will likely require conditional css.

Convert text into number in MySQL query

A generic way to do :

SELECT * FROM your_table ORDER BY LENTH(your_column) ASC, your_column ASC

How to copy data from one HDFS to another HDFS?

Hadoop comes with a useful program called distcp for copying large amounts of data to and from Hadoop Filesystems in parallel. The canonical use case for distcp is for transferring data between two HDFS clusters. If the clusters are running identical versions of hadoop, then the hdfs scheme is appropriate to use.

$ hadoop distcp hdfs://namenode1/foo hdfs://namenode2/bar

The data in /foo directory of namenode1 will be copied to /bar directory of namenode2. If the /bar directory does not exist, it will create it. Also we can mention multiple source paths.

Similar to rsync command, distcp command by default will skip the files that already exist. We can also use -overwrite option to overwrite the existing files in destination directory. The option -update will only update the files that have changed.

$ hadoop distcp -update hdfs://namenode1/foo hdfs://namenode2/bar/foo

distcp can also be implemented as a MapReduce job where the work of copying is done by the maps that run in parallel across the cluster. There will be no reducers.

If trying to copy data between two HDFS clusters that are running different versions, the copy will process will fail, since the RPC systems are incompatible. In that case we need to use the read-only HTTP based HFTP filesystems to read from the source. Here the job has to run on destination cluster.

$ hadoop distcp hftp://namenode1:50070/foo hdfs://namenode2/bar

50070 is the default port number for namenode's embedded web server.

How to trim a string after a specific character in java

You can use:

result = result.split("\n")[0];

Setting Icon for wpf application (VS 08)

Note: (replace file.ico with your actual icon filename)

  1. Add the icon to the project with build action of "Resource".
  2. In the Project Properties, set the Application Icon to file.ico
  3. In the main Window XAML set: Icon=".\file.ico" on the Window

How to use HTTP GET in PowerShell?

In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:

$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"

Can a Windows batch file determine its own file name?

Using the following script, based on SLaks answer, I determined that the correct answer is:

echo The name of this file is: %~n0%~x0
echo The name of this file is: %~nx0

And here is my test script:

@echo off
echo %0
echo %~0
echo %n0
echo %x0
echo %~n0
echo %dp0
echo %~dp0
pause

What I find interesting is that %nx0 won't work, given that we know the '~' char usually is used to strip/trim quotes off of a variable.

How to control size of list-style-type disc in CSS?

In modern browsers you can use the ::marker CSS pseudo-element like this:

.farParentDiv ul li::marker {
  font-size: 0.8em;
}

For browser support, please refer to: Can I Use ::marker pseudo-element

Macro to Auto Fill Down to last adjacent cell

ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

User Authentication in ASP.NET Web API

I am amazed how I've not been able to find a clear example of how to authenticate an user right from the login screen down to using the Authorize attribute over my ApiController methods after several hours of Googling.

That's because you are getting confused about these two concepts:

  • Authentication is the mechanism whereby systems may securely identify their users. Authentication systems provide an answers to the questions:

    • Who is the user?
    • Is the user really who he/she represents himself to be?
  • Authorization is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system. For example, a database management system might be designed so as to provide certain specified individuals with the ability to retrieve information from a database but not the ability to change data stored in the datbase, while giving other individuals the ability to change data. Authorization systems provide answers to the questions:

    • Is user X authorized to access resource R?
    • Is user X authorized to perform operation P?
    • Is user X authorized to perform operation P on resource R?

The Authorize attribute in MVC is used to apply access rules, for example:

 [System.Web.Http.Authorize(Roles = "Admin, Super User")]
 public ActionResult AdministratorsOnly()
 {
     return View();
 }

The above rule will allow only users in the Admin and Super User roles to access the method

These rules can also be set in the web.config file, using the location element. Example:

  <location path="Home/AdministratorsOnly">
    <system.web>
      <authorization>
        <allow roles="Administrators"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

However, before those authorization rules are executed, you have to be authenticated to the current web site.

Even though these explain how to handle unauthorized requests, these do not demonstrate clearly something like a LoginController or something like that to ask for user credentials and validate them.

From here, we could split the problem in two:

  • Authenticate users when consuming the Web API services within the same Web application

    This would be the simplest approach, because you would rely on the Authentication in ASP.Net

    This is a simple example:

    Web.config

    <authentication mode="Forms">
      <forms
        protection="All"
        slidingExpiration="true"
        loginUrl="account/login"
        cookieless="UseCookies"
        enableCrossAppRedirects="false"
        name="cookieName"
      />
    </authentication>
    

    Users will be redirected to the account/login route, there you would render custom controls to ask for user credentials and then you would set the authentication cookie using:

        if (ModelState.IsValid)
        {
            if (Membership.ValidateUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }
    
        // If we got this far, something failed, redisplay form
        return View(model);
    
  • Cross - platform authentication

    This case would be when you are only exposing Web API services within the Web application therefore, you would have another client consuming the services, the client could be another Web application or any .Net application (Win Forms, WPF, console, Windows service, etc)

    For example assume that you will be consuming the Web API service from another web application on the same network domain (within an intranet), in this case you could rely on the Windows authentication provided by ASP.Net.

    <authentication mode="Windows" />
    

    If your services are exposed on the Internet, then you would need to pass the authenticated tokens to each Web API service.

    For more info, take a loot to the following articles:

How to run Node.js as a background process and never die?

Try this for a simple solution

cmd & exit

What linux shell command returns a part of a string?

In "pure" bash you have many tools for (sub)string manipulation, mainly, but not exclusively in parameter expansion :

${parameter//substring/replacement}
${parameter##remove_matching_prefix}
${parameter%%remove_matching_suffix}

Indexed substring expansion (special behaviours with negative offsets, and, in newer Bashes, negative lengths):

${parameter:offset}
${parameter:offset:length}
${parameter:offset:length}

And of course, the much useful expansions that operate on whether the parameter is null:

${parameter:+use this if param is NOT null}
${parameter:-use this if param is null}
${parameter:=use this and assign to param if param is null}
${parameter:?show this error if param is null}

They have more tweakable behaviours than those listed, and as I said, there are other ways to manipulate strings (a common one being $(command substitution) combined with sed or any other external filter). But, they are so easily found by typing man bash that I don't feel it merits to further extend this post.

Change class on mouseover in directive

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

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

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

with some styling:

.red {
  background-color: red;
}

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

See running example here: jsfiddle sample

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

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

If you're USING a date then I strongly advise that you use jodatime, http://joda-time.sourceforge.net/. Using System.currentTimeMillis() for fields that are dates sounds like a very bad idea because you'll end up with a lot of useless code.

Both date and calendar are seriously borked, and Calendar is definitely the worst performer of them all.

I'd advise you to use System.currentTimeMillis() when you are actually operating with milliseconds, for instance like this

 long start = System.currentTimeMillis();
    .... do something ...
 long elapsed = System.currentTimeMillis() -start;

Getting Raw XML From SOAPMessage in Java

If you need formatting the xml string to xml, try this:

String xmlStr = "your-xml-string";
Source xmlInput = new StreamSource(new StringReader(xmlStr));
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput,
        new StreamResult(new FileOutputStream("response.xml")));

Java time-based map/cache with expiring keys

Typically, a cache should keep objects around some time and shall expose of them some time later. What is a good time to hold an object depends on the use case. I wanted this thing to be simple, no threads or schedulers. This approach works for me. Unlike SoftReferences, objects are guaranteed to be available some minimum amount of time. However, the do not stay around in memory until the sun turns into a red giant.

As useage example think of a slowly responding system that shall be able to check if a request has been done quite recently, and in that case not to perform the requested action twice, even if a hectic user hits the button several times. But, if the same action is requested some time later, it shall be performed again.

class Cache<T> {
    long avg, count, created, max, min;
    Map<T, Long> map = new HashMap<T, Long>();

    /**
     * @param min   minimal time [ns] to hold an object
     * @param max   maximal time [ns] to hold an object
     */
    Cache(long min, long max) {
        created = System.nanoTime();
        this.min = min;
        this.max = max;
        avg = (min + max) / 2;
    }

    boolean add(T e) {
        boolean result = map.put(e, Long.valueOf(System.nanoTime())) != null;
        onAccess();
        return result;
    }

    boolean contains(Object o) {
        boolean result = map.containsKey(o);
        onAccess();
        return result;
    }

    private void onAccess() {
        count++;
        long now = System.nanoTime();
        for (Iterator<Entry<T, Long>> it = map.entrySet().iterator(); it.hasNext();) {
            long t = it.next().getValue();
            if (now > t + min && (now > t + max || now + (now - created) / count > t + avg)) {
                it.remove();
            }
        }
    }
}

Remove last specific character in a string c#

Try below

Something..TrimEnd(",".ToCharArray());

How do I convert a String to an InputStream in Java?

You could use a StringReader and convert the reader to an input stream using the solution in this other stackoverflow post.

How to target only IE (any version) within a stylesheet?

When using SASS I use the following 2 @media queries to target IE 6-10 & EDGE.

@media screen\9
    @import ie_styles
@media screen\0
    @import ie_styles

http://keithclark.co.uk/articles/moving-ie-specific-css-into-media-blocks/

Edit

I also target later versions of EDGE using @support queries (add as many as you need)

@supports (-ms-ime-align:auto)
    @import ie_styles
@supports (-ms-accelerator:auto)
    @import ie_styles

https://jeffclayton.wordpress.com/2015/04/07/css-hacks-for-windows-10-and-spartan-browser-preview/

How to replace NaN value with zero in a huge data frame?

In fact, in R, this operation is very easy:

If the matrix 'a' contains some NaN, you just need to use the following code to replace it by 0:

a <- matrix(c(1, NaN, 2, NaN), ncol=2, nrow=2)
a[is.nan(a)] <- 0
a

If the data frame 'b' contains some NaN, you just need to use the following code to replace it by 0:

#for a data.frame: 
b <- data.frame(c1=c(1, NaN, 2), c2=c(NaN, 2, 7))
b[is.na(b)] <- 0
b

Note the difference is.nan when it's a matrix vs. is.na when it's a data frame.

Doing

#...
b[is.nan(b)] <- 0
#...

yields: Error in is.nan(b) : default method not implemented for type 'list' because b is a data frame.

Note: Edited for small but confusing typos

Open web in new tab Selenium + Python

browser.execute_script('''window.open("http://bings.com","_blank");''')

Where browser is the webDriver

Does MySQL foreign_key_checks affect the entire database?

In case of using Mysql query browser, SET FOREIGN_KEY_CHECKS=0; does not have any impact in version 1.1.20. However, it works fine on Mysql query browser 1.2.17

How to draw interactive Polyline on route google maps v2 android

You should use options.addAll(allPoints); instead of options.add(point);

How can I check that JButton is pressed? If the isEnable() is not work?

The method you are trying to use checks if the button is active:

btnAdd.isEnabled()

When enabled, any component associated with this object is active and able to fire this object's actionPerformed method.

This method does not check if the button is pressed.

If i understand your question correctly, you want to disable your "Add" button after the user clicks "Check out".

Try disabling your button at start: btnAdd.setEnabled(false) or after the user presses "Check out"

Add jars to a Spark Job - spark-submit

Other configurable Spark option relating to jars and classpath, in case of yarn as deploy mode are as follows
From the spark documentation,

spark.yarn.jars

List of libraries containing Spark code to distribute to YARN containers. By default, Spark on YARN will use Spark jars installed locally, but the Spark jars can also be in a world-readable location on HDFS. This allows YARN to cache it on nodes so that it doesn't need to be distributed each time an application runs. To point to jars on HDFS, for example, set this configuration to hdfs:///some/path. Globs are allowed.

spark.yarn.archive

An archive containing needed Spark jars for distribution to the YARN cache. If set, this configuration replaces spark.yarn.jars and the archive is used in all the application's containers. The archive should contain jar files in its root directory. Like with the previous option, the archive can also be hosted on HDFS to speed up file distribution.

Users can configure this parameter to specify their jars, which inturn gets included in Spark driver's classpath.

Python: most idiomatic way to convert None to empty string?

I use max function:

max(None, '')  #Returns blank
max("Hello",'') #Returns Hello

Works like a charm ;) Just put your string in the first parameter of the function.

Using Apache POI how to read a specific excel column

import java.io.*;

import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.ss.usermodel.*;
import java.text.*;

public class XSLXReader {
    static DecimalFormat df = new DecimalFormat("#####0");

    public static void main(String[] args) {
        FileWriter fostream;
        PrintWriter out = null;
        String strOutputPath = "H:\\BLR_Team\\Kavitha\\Excel-to-xml\\";
        String strFilePrefix = "Master_5.2-B";

        try {
            InputStream inputStream = new FileInputStream(new File("H:\\BLR_Team\\Kavitha\\Excel-to-xml\\Stack-up 20L pure storage 11-0039-01 ISU_USA-A 1-30-17-Rev_exm.xls"));
            Workbook wb = WorkbookFactory.create(inputStream);
           // Sheet sheet = wb.getSheet(0);
            Sheet sheet =null;
            Integer noOfSheets= wb.getNumberOfSheets();

            for(int i=0;i<noOfSheets;i++){
                sheet = wb.getSheetAt(i);
                System.out.println("Sheet : "+i + " " + sheet.getSheetName());
                System.out.println("Sheet : "+i + " " + sheet.getFirstRowNum());
                System.out.println("Sheet : "+i + " " + sheet.getLastRowNum());

            //Column 29
            fostream = new FileWriter(strOutputPath + "\\" + strFilePrefix+i+ ".xml");
            out = new PrintWriter(new BufferedWriter(fostream));

            out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            out.println("<Bin-code>");

            boolean firstRow = true;
            for (Row row : sheet) {
                if (firstRow == true) {
                    firstRow = false;
                    continue;
                }
                out.println("\t<DCT>");
                out.println(formatElement("\t\t", "ID", formatCell(row.getCell(0))));
                out.println(formatElement("\t\t", "Table_name", formatCell(row.getCell(1))));
                out.println(formatElement("\t\t", "isProddaten", formatCell(row.getCell(2))));
                out.println(formatElement("\t\t", "isR3P01Data", formatCell(row.getCell(3))));

                out.println(formatElement("\t\t", "LayerNo", formatCell(row.getCell(29))));
                out.println("\t</DCT>");
            }
            CellReference ref = new CellReference("A13");
          Row r = sheet.getRow(ref.getRow());
          if (r != null) {
             Cell c = r.getCell(ref.getCol());
           System.out.println(c.getRichStringCellValue().getString());
          }

            for (Row row : sheet) {
                  for (Cell cell : row) {

                      CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());


                      switch (cell.getCellType()) {
                      case Cell.CELL_TYPE_STRING:
                          System.out.println(cell.getRichStringCellValue().getString());
                          break;
                      case Cell.CELL_TYPE_NUMERIC:
                          if (DateUtil.isCellDateFormatted(cell)) {
                              System.out.println(cell.getDateCellValue());
                          } else {
                              System.out.println(cell.getNumericCellValue());
                          }
                          break;
                      case Cell.CELL_TYPE_BOOLEAN:
                          System.out.println(cell.getBooleanCellValue());
                          break;
                      case Cell.CELL_TYPE_FORMULA:
                          System.out.println(cell.getCellFormula());
                          break;
                      case Cell.CELL_TYPE_BLANK:
                          System.out.println();
                          break;
                      default:
                          System.out.println();
                  }
                  }

            }
            out.write("</Bin-code>");
            out.flush();
            out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String formatCell(Cell cell)
    {
        if (cell == null) {
            return "";
        }
        switch(cell.getCellType()) {
            case Cell.CELL_TYPE_BLANK:
                return "";
            case Cell.CELL_TYPE_BOOLEAN:
                return Boolean.toString(cell.getBooleanCellValue());
            case Cell.CELL_TYPE_ERROR:
                return "*error*";
            case Cell.CELL_TYPE_NUMERIC:
                return XSLXReader.df.format(cell.getNumericCellValue());
            case Cell.CELL_TYPE_STRING:
                return cell.getStringCellValue();
            default:
                return "<unknown value>";
        }
    }

    private static String formatElement(String prefix, String tag, String value) {
        StringBuilder sb = new StringBuilder(prefix);
        sb.append("<");
        sb.append(tag);
        if (value != null && value.length() > 0) {
            sb.append(">");
            sb.append(value);
            sb.append("</");
            sb.append(tag);
            sb.append(">");
        } else {
            sb.append("/>");
        }
        return sb.toString();
    }
}

This code does 3 things:

  1. Excel to XML file generation. Eng. Name Dong Kim
  2. Prints the content of a particular cell : A13
  3. Also print the excel content into normal text format. Jars to be imported: poi-3.9.jar,poi-ooxml-3.9.jar,poi-ooxml-schemas-3.9.jar,xbea??n-2.3.0.jar,xmlbeans??-xmlpublic-2.4.0.jar??,dom4j-1.5.jar

Link to add to Google calendar

I've also been successful with this URL structure:

Base URL:

https://calendar.google.com/calendar/r/eventedit?

And let's say this is my event details:

Title: Event Title
Description: Example of some description. See more at https://stackoverflow.com/questions/10488831/link-to-add-to-google-calendar
Location: 123 Some Place
Date: February 22, 2020
Start Time: 10:00am
End Time: 11:30am
Timezone: America/New York (GMT -5)

I'd convert my details into these parameters (URL encoded):

text=Event%20Title
details=Example%20of%20some%20description.%20See%20more%20at%20https%3A%2F%2Fstackoverflow.com%2Fquestions%2F10488831%2Flink-to-add-to-google-calendar
location=123%20Some%20Place%2C%20City
dates=20200222T100000/20200222T113000
ctz=America%2FNew_York

Example link:

https://calendar.google.com/calendar/r/eventedit?text=Event%20Title&details=Example%20of%20some%20description.%20See%20more%20at%20https%3A%2F%2Fstackoverflow.com%2Fquestions%2F10488831%2Flink-to-add-to-google-calendar&location=123%20Some%20Place%2C%20City&dates=20200222T100000/20200222T113000&ctz=America%2FNew_York

Please note that since I've specified a timezone with the "ctz" parameter, I used the local times for the start and end dates. Alternatively, you can use UTC dates and exclude the timezone parameter, like this:

dates=20200222T150000Z/20200222T163000Z

Example link:

https://calendar.google.com/calendar/r/eventedit?text=Event%20Title&details=Example%20of%20some%20description.%20See%20more%20at%20https%3A%2F%2Fstackoverflow.com%2Fquestions%2F10488831%2Flink-to-add-to-google-calendar&location=123%20Some%20Place%2C%20City&dates=20200222T150000Z/20200222T163000Z

Difference between JE/JNE and JZ/JNZ

JE and JZ are just different names for exactly the same thing: a conditional jump when ZF (the "zero" flag) is equal to 1.

(Similarly, JNE and JNZ are just different names for a conditional jump when ZF is equal to 0.)

You could use them interchangeably, but you should use them depending on what you are doing:

  • JZ/JNZ are more appropriate when you are explicitly testing for something being equal to zero:

    dec  ecx
    jz   counter_is_now_zero
    
  • JE and JNE are more appropriate after a CMP instruction:

    cmp  edx, 42
    je   the_answer_is_42
    

    (A CMP instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1 when the operands are equal and ZF=0 when they're not.)

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.

Calling other function in the same controller?

To call a function inside a same controller in any laravel version follow as bellow

$role = $this->sendRequest('parameter');
// sendRequest is a public function

Multiple lines of text in UILabel

You can do that via the Storyboard too:

  1. Select the Label on the view controller
  2. In the Attribute Inspector, increase the value of the Line option (Press Alt+Cmd+4 to show Attributes Inspector)
  3. Double click the Label in the view controller and write or paste your text
  4. Resize the Label and/or increase the font size so that the whole text could be shown

How to set environment variables in PyCharm?

This is what you can do to source an .env (and .flaskenv) file in the pycharm flask/django console. It would also work for a normal python console of course.

  1. Do pip install python-dotenv in your environment (the same as being pointed to by pycharm).

  2. Go to: Settings > Build ,Execution, Deployment > Console > Flask/django Console

  3. In "starting script" include something like this near the top:

    from dotenv import load_dotenv load_dotenv(verbose=True)

The .env file can look like this: export KEY=VALUE

It doesn't matter if one includes export or not for dotenv to read it.

As an alternative you could also source the .env file in the activate shell script for the respective virtual environement.

jquery: get id from class selector

As of jQuery 1.6, you could (and some would say should) use .prop instead of .attr

$('.test').click(function(){
    alert($(this).prop('id'));
});

It is discussed further in this post: .prop() vs .attr()

Why is an OPTIONS request sent and can I disable it?

There is maybe a solution (but i didnt test it) : you could use CSP (Content Security Policy) to enable your remote domain and browsers will maybe skip the CORS OPTIONS request verification.

I if find some time, I will test that and update this post !

CSP : https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Content-Security-Policy

CSP Specification : https://www.w3.org/TR/CSP/

can't start MySql in Mac OS 10.6 Snow Leopard

Okay... Finally I could install it! Why? or what I did? well I am not sure. first I downloaded and installed the package (I installed all the files(3) from the disk image) but I couldn't start it. (nor from the preferences panel, nor from the termial)

second I removed it and installed through mac ports.

again, the same thing. could not start it.

Now I deleted it again, installed from the package. (i am not sure if it was the exact same package but I think it is) Only this time I got the package from another site(its a mirror).

the site:

http://www.mmisoftware.co.uk/weblog/2009/08/29/mac-os-x-10-6-snow-leopard-and-mysql/

and the link:

http://mirror.services.wisc.edu/mysql/Downloads/MySQL-5.1/mysql-5.1.37-osx10.5-x86.dmg

1.- install mysql-5-1.37-osx10.5-x86.pkg

2.- install MySQLStartupItem.pkg

3.- install MySQL.prefpanel

And this time is working fine (even the preferences panel!)

Nothing special, I don't know what happened the first two times.

But thank you all. Regards.

jquery background-color change on focus and blur

What you are trying to do can be simplified down to this.

_x000D_
_x000D_
$('input:text').bind('focus blur', function() {_x000D_
    $(this).toggleClass('red');_x000D_
});
_x000D_
input{_x000D_
    background:#FFFFEE;_x000D_
}_x000D_
.red{_x000D_
    background-color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<form>_x000D_
    <input class="calc_input" type="text" name="start_date" id="start_date" />_x000D_
    <input class="calc_input" type="text" name="end_date" id="end_date" />_x000D_
    <input class="calc_input" size="8" type="text" name="leap_year" id="leap_year" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

What is the difference between new/delete and malloc/free?

1.new syntex is simpler than malloc()

2.new/delete is a operator where malloc()/free() is a function.

3.new/delete execute faster than malloc()/free() because new assemly code directly pasted by the compiler.

4.we can change new/delete meaning in program with the help of operator overlading.

Refresh Part of Page (div)

Use Ajax for this.

Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.

Relevant function:

http://api.jquery.com/load/

e.g.

$('#thisdiv').load(document.URL +  ' #thisdiv');

Note, load automatically replaces content. Be sure to include a space before the id selector.

Force drop mysql bypassing foreign key constraint

You can use the following steps, its worked for me to drop table with constraint,solution already explained in the above comment, i just added screen shot for that -enter image description here

How to use mongoimport to import csv

mongoimport -d test -c test --type csv --file SampleCSVFile_119kb.csv --headerline

check collection data:-

_x000D_
_x000D_
var collections = db.getCollectionNames();_x000D_
_x000D_
for(var i = 0; i< collections.length; i++)_x000D_
{    _x000D_
   print('Collection: ' + collections[i]);_x000D_
   // print the name of each collection_x000D_
   _x000D_
   db.getCollection(collections[i]).find().forEach(printjson);_x000D_
   _x000D_
   //and then print the json of each of its elements_x000D_
}
_x000D_
_x000D_
_x000D_

Android eclipse DDMS - Can't access data/data/ on phone to pull files

If you NEED to do it on your phone, I use a terminal emulator and standard linux commands.

Example:

  1. su
  2. cd data
  3. cd com.yourappp
  4. ls or cd into cache/shared_prefs

http://www.appbrain.com/app/android-terminal-emulator/jackpal.androidterm

Valid characters of a hostname?

If you're registering a domain and the termination (ex .com) it is not IDN, as Aaron Hathaway said: Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, en.wikipedia.org is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.

The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters a through z (in a case-insensitive manner), the digits 0 through 9, and the hyphen -. The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.

Later, Spain with it's .es, .com.es, .org.es, .nom,es, .gob.es and .edu.es introduced IDN tlds, if your tld is one of .es or any other that supports it, any character can be used, but you can't combine alphabets like Latin, Greek or Cyril in one hostname, and that it respects the things that can't go at the start or at the end.

If you're using non-registered tlds, just for local networking, like with local DNS or with hosts files, you can treat them all as IDN.

Keep in mind some programs could not work well, especially old, outdated and unpopular ones.

How to add "active" class to Html.ActionLink in ASP.NET MVC

I have make combination of answers above and made my solution.

So..

First in razor block create one string variable which will contain name value of controller and action that is called by user.

    @{
        string controllerAction =  ViewContext.RouteData.Values["Controller"].ToString() + ViewContext.RouteData.Values["Action"].ToString(); 
    }

Then use combination of HTML and Razor code:

    <ul class="nav navbar-nav">
        <li class="@(controllerAction == "HomeIndex" ? "active" : "" )">@Html.ActionLink("Home", "Index", "Home")</li>
        <li class="@(controllerAction == "AboutIndex" ? "active" : "" )">@Html.ActionLink("About", "Index", "About")</li>
        <li class="@(controllerAction == "HomeContact" ? "active" : "" )">@Html.ActionLink("Contact", "Contact", "Home")</li>
    </ul>

I think, that this is good because you don't need to access "ViewContext.RouteData.Values" each time to get controller name and action name.

Is there an API to get bank transaction and bank balance?

Just a helpful hint, there is a company called Yodlee.com who provides this data. They do charge for the API. Companies like Mint.com use this API to gather bank and financial account data.

Also, checkout https://plaid.com/, they are a similar company Yodlee.com and provide both authentication API for several banks and REST-based transaction fetching endpoints.

jQuery remove selected option from this

 $('#some_select_box').click(function() {
     $(this).find('option:selected').remove();
 });

Using the find method.

How to make <label> and <input> appear on the same line on an HTML form?

Wrap the label and the input within a bootstraps div

<div class ="row">
  <div class="col-md-4">Name:</div>
  <div class="col-md-8"><input type="text"></div>
</div>

How to overlay images

Unless you use the <img> tag, which displays an image by itself, you will not be able to achieve this with pure CSS alone. You will also need TWO HTML elements as well - one for each picture. This is because the only way you can make an element display a picture via CSS is with the background-image property, and every element can have only one background image. Which two elements you choose and how you position them is up to you. There are many ways how you can position one HTML element above another.

Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

This is the disassembled code from .NET Reflector for Path.Combine method. Check IsPathRooted function. If the second path is rooted (starts with a DirectorySeparatorChar), return second path as it is.

public static string Combine(string path1, string path2)
{
    if ((path1 == null) || (path2 == null))
    {
        throw new ArgumentNullException((path1 == null) ? "path1" : "path2");
    }
    CheckInvalidPathChars(path1);
    CheckInvalidPathChars(path2);
    if (path2.Length == 0)
    {
        return path1;
    }
    if (path1.Length == 0)
    {
        return path2;
    }
    if (IsPathRooted(path2))
    {
        return path2;
    }
    char ch = path1[path1.Length - 1];
    if (((ch != DirectorySeparatorChar) &&
         (ch != AltDirectorySeparatorChar)) &&
         (ch != VolumeSeparatorChar))
    {
        return (path1 + DirectorySeparatorChar + path2);
    }
    return (path1 + path2);
}


public static bool IsPathRooted(string path)
{
    if (path != null)
    {
        CheckInvalidPathChars(path);
        int length = path.Length;
        if (
              (
                  (length >= 1) &&
                  (
                      (path[0] == DirectorySeparatorChar) ||
                      (path[0] == AltDirectorySeparatorChar)
                  )
              )

              ||

              ((length >= 2) &&
              (path[1] == VolumeSeparatorChar))
           )
        {
            return true;
        }
    }
    return false;
}

How to transfer some data to another Fragment?

            First Fragment Sending String To Next Fragment
            public class MainActivity extends AppCompatActivity {
                    private Button Add;
                    private EditText edt;
                    FragmentManager fragmentManager;
                    FragClass1 fragClass1;


                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                        Add= (Button) findViewById(R.id.BtnNext);
                        edt= (EditText) findViewById(R.id.editText);

                        Add.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                fragClass1=new FragClass1();
                                Bundle bundle=new Bundle();

                                fragmentManager=getSupportFragmentManager();
                                fragClass1.setArguments(bundle);
                                bundle.putString("hello",edt.getText().toString());
                                FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
                                fragmentTransaction.add(R.id.activity_main,fragClass1,"");
                                fragmentTransaction.addToBackStack(null);
                                fragmentTransaction.commit();

                            }
                        });
                    }
                }
         Next Fragment to fetch the string.
            public class FragClass1 extends Fragment {
                  EditText showFrag1;


                    @Nullable
                    @Override
                    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

                        View view=inflater.inflate(R.layout.lay_frag1,null);
                        showFrag1= (EditText) view.findViewById(R.id.edtText);
                        Bundle bundle=getArguments();
                        String a=getArguments().getString("hello");//Use This or The Below Commented Code
                        showFrag1.setText(a);
                        //showFrag1.setText(String.valueOf(bundle.getString("hello")));
                        return view;
                    }
                }
    I used Frame Layout easy to use.
    Don't Forget to Add Background color or else fragment will overlap.
This is for First Fragment.
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="@color/colorPrimary"
        tools:context="com.example.sumedh.fragmentpractice1.MainActivity">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:id="@+id/BtnNext"/>
    </FrameLayout>


Xml for Next Fragment.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
   android:background="@color/colorAccent"
    android:layout_height="match_parent">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edtText"/>

</LinearLayout>

Change the default base url for axios

Instead of

this.$axios.get('items')

use

this.$axios({ url: 'items', baseURL: 'http://new-url.com' })

If you don't pass method: 'XXX' then by default, it will send via get method.

Request Config: https://github.com/axios/axios#request-config

XML Parser for C

Two of the most widely used parsers are Expat and libxml.

If you are okay with using C++, there's Xerces-C++ too.

Set the layout weight of a TextView programmatically

TextView txtview = new TextView(v.getContext());
LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
txtview.setLayoutParams(params);

1f is denotes as weight=1; you can give 2f or 3f, views will move accoding to the space

How to add click event to a iframe with JQuery

There's no 'onclick' event for an iframe, but you can try to catch the click event of the document in the iframe:

document.getElementById("iframe_id").contentWindow.document.body.onclick = 
function() {
  alert("iframe clicked");
}

EDIT Though this doesn't solve your cross site problem, FYI jQuery has been updated to play well with iFrames:

$('#iframe_id').on('click', function(event) { });

Update 1/2015 The link to the iframe explanation has been removed as it's no longer available.

Note The code above will not work if the iframe is from different domain than the host page. You can still try to use hacks mentioned in comments.

jQuery date/time picker

My best experience with a datepicker is with the prototype-based AnyTime. I know that's not jQuery, but it may still be worth the compromise for you. I know absolutely no prototype, and it's still easy enough to work with.

One caveat I've found: it is not forward compatible on some browsers. That is, it did not work with a newer version of prototype on Chrome.

How to load my app from Eclipse to my Android phone instead of AVD

connect your device to system and set you device debug mode on when you run your application Android Virtual Device AVD will select device there you will see your connected device select your mobile device and thats all refer this link to set your device debugging mode on

http://developer.android.com/training/basics/firstapp/running-app.html device manager showing your device

Printing Python version in output

If you are using jupyter notebook Try:

!python --version

If you are using terminal Try:

 python --version

Navigation Drawer (Google+ vs. YouTube)

Just recently I forked a current Github project called "RibbonMenu" and edited it to fit my needs:

https://github.com/jaredsburrows/RibbonMenu

What's the Purpose

  • Ease of Access: Allow easy access to a menu that slides in and out
  • Ease of Implementation: Update the same screen using minimal amount of code
  • Independency: Does not require support libraries such as ActionBarSherlock
  • Customization: Easy to change colors and menus

What's New

  • Changed the sliding animation to match Facebook and Google+ apps
  • Added standard ActionBar (you can chose to use ActionBarSherlock)
  • Used menuitem to open the Menu
  • Added ability to update ListView on main Activity
  • Added 2 ListViews to the Menu, similiar to Facebook and Google+ apps
  • Added a AutoCompleteTextView and a Button as well to show examples of implemenation
  • Added method to allow users to hit the 'back button' to hide the menu when it is open
  • Allows users to interact with background(main ListView) and the menu at the same time unlike the Facebook and Google+ apps!

ActionBar with Menu out

ActionBar with Menu out

ActionBar with Menu out and search selected

ActionBar with Menu out and search selected

Can't connect to local MySQL server through socket '/tmp/mysql.sock

Check number of open files for the mysql process using lsof command.

Increase the open files limit and run again.

How to gzip all files in all sub-directories into one compressed file in bash

tar -zcvf compressFileName.tar.gz folderToCompress

everything in folderToCompress will go to compressFileName

Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName

Checking whether a string starts with XXXX

aString = "hello world"
aString.startswith("hello")

More info about startswith.

Call asynchronous method in constructor?

In order to use async within the constructor and ensure the data is available when you instantiate the class, you can use this simple pattern:

class FooClass : IFooAsync
{        
    FooClass 
    {
        this.FooAsync = InitFooTask();
    }

    public Task FooAsync { get; }

    private async Task InitFooTask()
    {
        await Task.Delay(5000);
    }
}

The interface:

public interface IFooAsync
{
    Task FooAsync { get; }
}

The usage:

FooClass foo = new FooClass();    
if (foo is IFooAsync)
    await foo.FooAsync;

Permissions for /var/www/html

log in as root user:

sudo su

password:

then go and do what you want to do in var/www

Error message "Linter pylint is not installed"

I would like to add my trials and my solution following rob3c's answer.

PS: My solution only concerns Windows users.

The problem:

I tried the following settings without success:

// settings.json
"python.linting.pylintPath": ${workspaceFolder}\\_tools\\python3\\Scripts\\pylint

and

"python.linting.pylintPath": ${workspaceFolder}\\_tools\\python3\\Scripts\\pylint.exe

I always had the following error message:

Linter 'pylint' is not installed. Please install it or select another linter".
Error: spawn c:\WS\myproject\_tools\python3\Scripts\pylint ENOENT

Even with a pylint file in my folder:

dir c:\WS\myproject\_tools\python3\Scripts\
...
05.07.2017  09:34 AM                52 pylint    # ! no pylint.exe !
...

As my toolchain is based on MSYS, the Pylint installed is without pylint.exe.

The content of _tools\python3\Scripts\pylint file:

#!python
from pylint import run_pylint
run_pylint()

The solution

My workaround was to create a batch file .vscode\pylint.bat with the following contents:

%PYTHON3_EXE% _prefix\python3\Scripts\pylint %*

(%PYTHON3_EXE% is an environment variable to the Python 3 interpreter C:\Python34\python.exe)

And to configure .vscode\settings.json as follows:

// settings.json
"python.linting.pylintPath": "${workspaceFolder}\\.vscode\\pylint.bat",

Result

Log from OUTPUT --> Python:

##########Linting Output - pylint##########

c:\WS\myproject> C:\Python34\python.exe _tools\python3\Scripts\pylint
--rcfile c:\WS\framework\pylintrc
--msg-template='{line},{column},{category},{msg_id}:{msg}'
--reports=n
--output-format=text
c:\WS\myproject\myScriptToLint.py
Using config file c:\WS\myproject\pylintrc

------------------------------------

Your code has been rated at 10.00/10

? Visual Studio Code uses the Pylint version from my toolchain!

How to pre-populate the sms body text via an html link

Bradorego's solution is what worked for me, but here is a more expanded answer.

A small consideration is that you need to encode the body using %20 instead of +. For PHP, this means using rawurlencode($body) instead of urlencode($body). Otherwise you'll see plus signs in the message on old versions of iOS, instead of spaces.

Here is a jQuery function which will refit your SMS links for iOS devices. Android/other devices should work normally and won't execute the code.

HTML:

<a href="sms:+15551231234?body=Hello%20World">SMS "Hello World" to 555-123-1234</a>

jQuery:

(function() {
  if ( !navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ) return;

  jQuery('a[href^="sms:"]').attr('href', function() {
    // Convert: sms:+000?body=example
    // To iOS:  sms:+000;body=example (semicolon, not question mark)
    return jQuery(this).attr('href').replace(/sms:(\+?([0-9]*))?\?/, 'sms:$1;');
  });
})();

Consider using a class like a.sms-link instead of a[href^="sms:"] if possible.

How can I get the current time in C#?

DateTime.Now is what you're searching for...

Get Root Directory Path of a PHP project

You could also use realpath.

realpath(".") returns your document root.

You can call realpath with your specific path. Note that it will NOT work if the target folder or file does not exist. In such case it will return false, which could be useful for testing if a file exists.

In my case I needed to specify a path for a new file to be written to disk, and the solution was to append the path relative to document root:

$filepath = realpath(".") . "/path/to/newfile.txt";

Hope this helps anyone.

LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?

U can also use :

var query =
    from t1 in myTABLE1List 
    join t2 in myTABLE1List
      on new { ColA=t1.ColumnA, ColB=t1.ColumnB } equals new { ColA=t2.ColumnA, ColB=t2.ColumnB }
    join t3 in myTABLE1List
      on new {ColC=t2.ColumnA, ColD=t2.ColumnB } equals new { ColC=t3.ColumnA, ColD=t3.ColumnB }

Boolean Field in Oracle

The best option is 0 and 1 (as numbers - another answer suggests 0 and 1 as CHAR for space-efficiency but that's a bit too twisted for me), using NOT NULL and a check constraint to limit contents to those values. (If you need the column to be nullable, then it's not a boolean you're dealing with but an enumeration with three values...)

Advantages of 0/1:

  • Language independent. 'Y' and 'N' would be fine if everyone used it. But they don't. In France they use 'O' and 'N' (I have seen this with my own eyes). I haven't programmed in Finland to see whether they use 'E' and 'K' there - no doubt they're smarter than that, but you can't be sure.
  • Congruent with practice in widely-used programming languages (C, C++, Perl, Javascript)
  • Plays better with the application layer e.g. Hibernate
  • Leads to more succinct SQL, for example, to find out how many bananas are ready to eat select sum(is_ripe) from bananas instead of select count(*) from bananas where is_ripe = 'Y' or even (yuk) select sum(case is_ripe when 'Y' then 1 else 0) from bananas

Advantages of 'Y'/'N':

  • Takes up less space than 0/1
  • It's what Oracle suggests, so might be what some people are more used to

Another poster suggested 'Y'/null for performance gains. If you've proven that you need the performance, then fair enough, but otherwise avoid since it makes querying less natural (some_column is null instead of some_column = 0) and in a left join you'll conflate falseness with nonexistent records.

Change Toolbar color in Appcompat 21

Hey if you want to apply Material theme for only android 5.0 then you can add this theme in it

<style name="AppHomeTheme" parent="@android:style/Theme.Material.Light">

        <!-- customize the color palette -->
        <item name="android:colorPrimary">@color/blue_dark_bg</item>
        <item name="android:colorPrimaryDark">@color/blue_status_bar</item>
        <item name="android:colorAccent">@color/blue_color_accent</item>
        <item name="android:textColor">@android:color/white</item>
        <item name="android:textColorPrimary">@android:color/white</item>
        <item name="android:actionMenuTextColor">@android:color/black</item>
    </style> 

Here below line is responsibly for text color of Actionbar of Material design.

<item name="android:textColorPrimary">@android:color/white</item>

git undo all uncommitted or unsaved changes

Another option to undo changes that weren't staged for commit is to run:

git restore <file>

To discard changes in the working directory.

Overlapping elements in CSS

You can try using the transform: translate property by passing the appropriate values inside the parenthesis using the inspect element in Google chrome.

You have to set translate property in such way that both the <div> overlap each other then You can use JavaScript to show and hide both the <div> according to your requirements

Get google map link with latitude/longitude

I've tried doing the request you need using an iframe to show the result for latitude, longitude, and zoom needed:

<iframe 
  width="300" 
  height="170" 
  frameborder="0" 
  scrolling="no" 
  marginheight="0" 
  marginwidth="0" 
  src="https://maps.google.com/maps?q='+YOUR_LAT+','+YOUR_LON+'&hl=es&z=14&amp;output=embed"
 >
 </iframe>
 <br />
 <small>
   <a 
    href="https://maps.google.com/maps?q='+data.lat+','+data.lon+'&hl=es;z=14&amp;output=embed" 
    style="color:#0000FF;text-align:left" 
    target="_blank"
   >
     See map bigger
   </a>
 </small>

How do I change the background color of a plot made with ggplot2

Here's a custom theme to make the ggplot2 background white and a bunch of other changes that's good for publications and posters. Just tack on +mytheme. If you want to add or change options by +theme after +mytheme, it will just replace those options from +mytheme.

library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())

mytheme = list(
    theme_classic()+
        theme(panel.background = element_blank(),strip.background = element_rect(colour=NA, fill=NA),panel.border = element_rect(fill = NA, color = "black"),
              legend.title = element_blank(),legend.position="bottom", strip.text = element_text(face="bold", size=9),
              axis.text=element_text(face="bold"),axis.title = element_text(face="bold"),plot.title = element_text(face = "bold", hjust = 0.5,size=13))
)

ggplot(data=data.frame(a=c(1,2,3), b=c(2,3,4)), aes(x=a, y=b)) + mytheme + geom_line()

custom ggplot theme

What is lazy loading in Hibernate?

"Lazy loading" means that an entity will be loaded only when you actually accesses the entity for the first time.

The pattern is like this:

public Entity getEntity() {
    if (entity == null) {
        entity = loadEntity();
    }
    return entity;
}

This saves the cost of preloading/prefilling all the entities in a large dataset beforehand while you after all actually don't need all of them.

In Hibernate, you can configure to lazily load a collection of child entities. The actual lazy loading is then done inside the methods of the PersistentSet which Hibernate uses "under the hoods" to assign the collection of entities as Set.

E.g.

public class Parent {
    private Set<Child> children;

    public Set<Child> getChildren() {
        return children;
    }
}

.

public void doSomething() {
    Set<Child> children = parent.getChildren(); // Still contains nothing.

    // Whenever you call one of the following (indirectly), 
    // Hibernate will start to actually load and fill the set.
    children.size();
    children.iterator();
}

Easy way to make a confirmation dialog in Angular?

UPDATE: Plunkr added

I was looking for a solution on all forums but found none, so found a solution with Old School Javascript Callback function. This is a really simple and clean way to create a confirmation dialog and set Callback functions for both YES and NO click events.
I have used Bootstrap CSS for Modal and An Alert Service with rxjs Subject.

alert.component.html

        <div *ngIf="message.type == 'confirm'"  class="modal-body">
            <div class="row">
                <div class="col-md-12">
                    <h3 class="text-center">{{message.text}}</h3>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                    <p class="text-center">
                        <a (click)="message.noFn()">
                            <button class="btn btn-pm">No</button>
                        </a>
                        <a (click)="message.siFn()">
                            <button  class="btn btn-sc" >Yes</button>
                        </a>
                    </p>
                </div>
            </div>
         </div>

alert.component.ts

export class AlertComponent {
    message: any;
    constructor(
      public router: Router, 
      private route: ActivatedRoute, 
      private alertService: AlertService,
   ) { }
   ngOnInit() {
    //this function waits for a message from alert service, it gets 
    //triggered when we call this from any other component
    this.alertService.getMessage().subscribe(message => {
        this.message = message;
    });
}

The most important part is here alert.service.ts

     import { Injectable } from '@angular/core'; 
     import { Router, NavigationStart } from '@angular/router'; 
     import { Observable } from 'rxjs'; 
     import { Subject } from 'rxjs/Subject';
     @Injectable() export class AlertService {
          private subject = new Subject<any>();
          constructor(){}
          confirm(message: string,siFn:()=>void,noFn:()=>void){
            this.setConfirmation(message,siFn,noFn);
          }
          setConfirmation(message: string,siFn:()=>void,noFn:()=>void) {
            let that = this;
            this.subject.next({ type: "confirm",
                        text: message,
                        siFn:
                        function(){
                            that.subject.next(); //this will close the modal
                            siFn();
                        },
                        noFn:function(){
                            that.subject.next();
                            noFn();
                        }
                     });

                 }

          getMessage(): Observable<any> {
             return this.subject.asObservable();
          }
       }

Call the function from any component

this.alertService.confirm("You sure Bro?",function(){
    //ACTION: Do this If user says YES
},function(){
    //ACTION: Do this if user says NO
})

Plunkr https://embed.plnkr.co/vWBT2nWmtsXff0MXMKdd/

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

I found the below stuff in ffmpeg Docs. Hope this helps! :)

Reference: http://ffmpeg.org/ffmpeg.html#toc-Generic-options

‘-report’ Dump full command line and console output to a file named program-YYYYMMDD-HHMMSS.log in the current directory. This file can be useful for bug reports. It also implies -loglevel verbose.

Note: setting the environment variable FFREPORT to any value has the same effect.

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

In the my.ini file in C:\xampp\mysql\bin, add the following line after the [mysqld] command under #Mysql Server:

skip-grant-tables

This should remove the error 1045.

git with development, staging and production branches

Actually what made this so confusing is that the Beanstalk people stand behind their very non-standard use of Staging (it comes before development in their diagram, and it's not a mistake!

https://twitter.com/Beanstalkapp/status/306129447885631488

How to check if a value is not null and not empty string in JS

Instead of using

if(data !== null && data !== ''  && data!==undefined) {

// do something
}

You can use below simple code

if(Boolean(value)){ 
// do something 
}
  • Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become false
  • Other values become true

Missing Authentication Token while accessing API Gateway?

I think you are directly trying to access API link, this won't work because API is secured using IAM role and you must provide AWS authentication i.e Access key and Secret key.

Use the Postman Chrome extension to test your API: http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-use-postman-to-call-api.html

APR based Apache Tomcat Native library was not found on the java.library.path?

I resolve this (On Eclipse IDE) by delete my old server and create the same again. This error is because you don't proper terminate Tomcat server and close Eclipse.

How do I set a checkbox in razor view?

The syntax in your last line is correct.

 @Html.CheckBoxFor(x => x.Test, new { @checked = "checked" })

That should definitely work. It is the correct syntax. If you have an existing model and AllowRating is set to true then MVC will add the checked attribute automatically. If AllowRating is set to false MVC won't add the attribute however if desired you can using the above syntax.

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

How to check if a service is running via batch file and start it, if it is not running?

Starting Service using Powershell script. You can link this to task scheduler and trigger it at intervals or as needed. Create this as a PS1 file i.e. file with extension PS1 and then let this file be triggered from task scheduler.

To start stop service

in task scheduler if you are using it on server use this in arguments

-noprofile -executionpolicy bypass -file "C:\Service Restart Scripts\StopService.PS1"

verify by running the same on cmd if it works it should work on task scheduler also

$Password = "Enter_Your_Password"
$UserAccount = "Enter_Your_AccountInfor"
$MachineName = "Enter_Your_Machine_Name"
$ServiceList = @("test.SocketService","test.WcfServices","testDesktopService","testService")
$PasswordSecure = $Password | ConvertTo-SecureString -AsPlainText -Force
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $UserAccount, $PasswordSecure 

$LogStartTime = Get-Date -Format "MM-dd-yyyy hh:mm:ss tt"
$FileDateTimeStamp = Get-Date -Format "MM-dd-yyyy_hh"
$LogFileName = "C:\Users\krakhil\Desktop\Powershell\Logs\StartService_$FileDateTimeStamp.txt" 


#code to start the service

"`n####################################################################" > $LogFileName
"####################################################################" >> $LogFileName
"######################  STARTING SERVICE  ##########################" >> $LogFileName

for($i=0;$i -le 3; $i++)
{
"`n`n" >> $LogFileName
$ServiceName = $ServiceList[$i]
"$LogStartTime => Service Name: $ServiceName" >> $LogFileName

Write-Output "`n####################################"
Write-Output "Starting Service - " $ServiceList[$i]

"$LogStartTime => Starting Service: $ServiceName" >> $LogFileName
Start-Service $ServiceList[$i]

$ServiceState = Get-Service | Where-Object {$_.Name -eq $ServiceList[$i]}

if($ServiceState.Status -eq "Running")
{
"$LogStartTime => Started Service Successfully: $ServiceName" >> $LogFileName
Write-Host "`n Service " $ServiceList[$i] " Started Successfully"
}
else
{
"$LogStartTime => Unable to Stop Service: $ServiceName" >> $LogFileName
Write-Output "`n Service didn't Start. Current State is - "
Write-Host $ServiceState.Status
}
}

#code to stop the service

"`n####################################################################" > $LogFileName
"####################################################################" >> $LogFileName
"######################  STOPPING SERVICE  ##########################" >> $LogFileName

for($i=0;$i -le 3; $i++)
{
"`n`n" >> $LogFileName
$ServiceName = $ServiceList[$i]
"$LogStartTime => Service Name: $ServiceName" >> $LogFileName

Write-Output "`n####################################"
Write-Output "Stopping Service - " $ServiceList[$i]

"$LogStartTime => Stopping Service: $ServiceName" >> $LogFileName
Stop-Service $ServiceList[$i]

$ServiceState = Get-Service | Where-Object {$_.Name -eq $ServiceList[$i]}

if($ServiceState.Status -eq "Stopped")
{
"$LogStartTime => Stopped Service Successfully: $ServiceName" >> $LogFileName
Write-Host "`n Service " $ServiceList[$i] " Stopped Successfully"
}
else
{
"$LogStartTime => Unable to Stop Service: $ServiceName" >> $LogFileName
Write-Output "`nService didn't Stop. Current State is - "
Write-Host $ServiceState.Status
}
}

How to filter an array/object by checking multiple values

You can use .filter() with boolean operators ie &&:

     var find = my_array.filter(function(result) {
       return result.param1 === "srting1" && result.param2 === 'string2';
     });
     
     return find[0];

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

  1. Find file:

    [XAMPP Installation Directory]\php\php.ini
    
  2. open php.ini.
  3. Find max_execution_time and increase the value of it as you required
  4. Restart XAMPP control panel

Saving a Numpy array as an image

You can use 'skimage' library in Python

Example:

from skimage.io import imsave
imsave('Path_to_your_folder/File_name.jpg',your_array)

Read MS Exchange email in C#

  1. The currently preferred (Exchange 2013 and 2016) API is EWS. It is purely HTTP based and can be accessed from any language, but there are .Net and Java specific libraries.

    You can use EWSEditor to play with the API.

  2. Extended MAPI. This is the native API used by Outlook. It ends up using the MSEMS Exchange MAPI provider, which can talk to Exchange using RPC (Exchange 2013 no longer supports it) or RPC-over-HTTP (Exchange 2007 or newer) or MAPI-over-HTTP (Exchange 2013 and newer).

    The API itself can only be accessed from unmanaged C++ or Delphi. You can also use Redemption (any language) - its RDO family of objects is an Extended MAPI wrapper. To use Extended MAPI, you need to install either Outlook or the standalone (Exchange) version of MAPI (on extended support, and it does not support Unicode PST and MSG files and cannot access Exchange 2016). Extended MAPI can be used in a service.

    You can play with the API using OutlookSpy or MFCMAPI.

  3. Outlook Object Model - not Exchange specific, but it allows access to all data available in Outlook on the machine where the code runs. Cannot be used in a service.

  4. Exchange Active Sync. Microsoft no longer invests any significant resources into this protocol.

  5. Outlook used to install CDO 1.21 library (it wraps Extended MAPI), but it had been deprecated by Microsoft and no longer receives any updates.

  6. There used to be a third-party .Net MAPI wrapper called MAPI33, but it is no longer being developed or supported.

  7. WebDAV - deprecated.

  8. Collaborative Data Objects for Exchange (CDOEX) - deprecated.

  9. Exchange OLE DB Provider (EXOLEDB) - deprecated.

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.

How to install Android Studio on Ubuntu?

Here's how I installed android studio on xubuntu.

1. Install JDK:

Go through following commands to install jdk

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer
sudo apt-get install oracle-java7-set-default

If you want to install other version of jdk than replace your version number with 7 in last two commands.

2. Download the latest android studio from official site: https://developer.android.com/studio/index.html

It is better to use latest version of android studio because I tried to install version 1.5.1 and it was not working. Then I installed version 2.1.1 and it run perfectly.

  1. Extract downloaded android studio file in whichever folder you want. Now go to extracted android studio-->bin directory and open terminal here. Now run following:

    ./studio.sh

And that's it. If you are facing any problem than comment below.

How to print a certain line of a file with PowerShell?

This will show the 10th line of myfile.txt:

get-content myfile.txt | select -first 1 -skip 9

both -first and -skip are optional parameters, and -context, or -last may be useful in similar situations.

How to clear exisiting dropdownlist items when its content changes?

Using ddl.Items.Clear() will clear the dropdownlist however you must be sure that your dropdownlist is not set to:

AppendDataBoundItems="True"

This option will cause the rebound data to be appended to the existing list which will NOT be cleared prior to binding.

SOLUTION

Add AppendDataBoundItems="False" to your dropdownlist.

Now when data is rebound it will automatically clear all existing data beforehand.

Protected Sub ddl1_SelectedIndexChanged(sender As Object, e As EventArgs)
    ddl2.DataSource = sql2
    ddl2.DataBind()
End Sub

NOTE: This may not be suitable in all situations as appenddatbound items can cause your dropdown to append its own data on each change of the list.


TOP TIP

Still want a default list item adding to your dropdown but need to rebind data?

Use AppendDataBoundItems="False" to prevent duplication data on postback and then directly after binding your dropdownlist insert a new default list item.

ddl.Items.Insert(0, New ListItem("Select ...", ""))

How to change app default theme to a different app theme?

Actually you should define your styles in res/values/styles.xml. I guess now you've got the following configuration:

<style name="AppBaseTheme" parent="android:Theme.Holo.Light"/>
<style name="AppTheme" parent="AppBaseTheme"/>

so if you want to use Theme.Black then change AppBaseTheme parent to android:Theme.Black or you could change app style directly in manifest file like this - android:theme="@android:style/Theme.Black". You must be lacking android namespace before style tag.

You can read more about styles and themes here.

Using ffmpeg to encode a high quality video

A couple of things:

  • You need to set the video bitrate. I have never used minrate and maxrate so I don't know how exactly they work, but by setting the bitrate using the -b switch, I am able to get high quality video. You need to come up with a bitrate that offers a good tradeoff between compression and video quality. You may have to experiment with this because it all depends on the frame size, frame rate and the amount of motion in the content of your video. Keep in mind that DVD tends to be around 4-5 Mbit/s on average for 720x480, so I usually start from there and decide whether I need more or less and then just experiment. For example, you could add -b 5000k to the command line to get more or less DVD video bitrate.

  • You need to specify a video codec. If you don't, ffmpeg will default to MPEG-1 which is quite old and does not provide near the amount of compression as MPEG-4 or H.264. If your ffmpeg version is built with libx264 support, you can specify -vcodec libx264 as part of the command line. Otherwise -vcodec mpeg4 will also do a better job than MPEG-1, but not as well as x264.

  • There are a lot of other advanced options that will help you squeeze out the best quality at the lowest bitrates. Take a look here for some examples.

Test if string begins with a string?

The best methods are already given but why not look at a couple of other methods for fun? Warning: these are more expensive methods but do serve in other circumstances.

The expensive regex method and the css attribute selector with starts with ^ operator

Option Explicit

Public Sub test()

    Debug.Print StartWithSubString("ab", "abc,d")

End Sub

Regex:

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft VBScript Regular Expressions
    Dim re As VBScript_RegExp_55.RegExp
    Set re = New VBScript_RegExp_55.RegExp

    re.Pattern = "^" & substring

    StartWithSubString = re.test(testString)

End Function

Css attribute selector with starts with operator

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft HTML Object Library
    Dim html As MSHTML.HTMLDocument
    Set html = New MSHTML.HTMLDocument

    html.body.innerHTML = "<div test=""" & testString & """></div>"

    StartWithSubString = html.querySelectorAll("[test^=" & substring & "]").Length > 0

End Function

Principal Component Analysis (PCA) in Python

For the sake def plot_pca(data): will work, it is necessary to replace the lines

data_resc, data_orig = PCA(data)
ax1.plot(data_resc[:, 0], data_resc[:, 1], '.', mfc=clr1, mec=clr1)

with lines

newData, data_resc, data_orig = PCA(data)
ax1.plot(newData[:, 0], newData[:, 1], '.', mfc=clr1, mec=clr1)

Calculate average in java

for 1. the number of integers read in, you can just use length property of array like :

int count = args.length

which gives you no of elements in an array. And 2. to calculate average value : you are doing in correct way.

Start a fragment via Intent within a Fragment

You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.

So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via intent filters.

How to detect a remote side socket close?

The method Socket.Available will immediately throw a SocketException if the remote system has disconnected/closed the connection.