Programs & Examples On #Extendscript

Extendscript is a scripting language based on ECMAScript for scripting Adobe products (Adobe Photoshop, Illustrator etc).

jquery Ajax call - data parameters are not being passed to MVC Controller action

I tried:

<input id="btnTest" type="button" value="button" />

<script type="text/javascript">
    $(document).ready( function() {
      $('#btnTest').click( function() {
        $.ajax({
          type: "POST", 
          url: "/Login/Test",
          data: { ListID: '1', ItemName: 'test' },
          dataType: "json",
          success: function(response) { alert(response); },
          error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
        });
      });
    });
</script>

and C#:

[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
    return Content(ListID + " " + ItemName);
}

It worked. Remove contentType and set data without double quotes.

Update a column in MySQL

If you want to update data you should use UPDATE command instead of INSERT

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

TypeError: '<=' not supported between instances of 'str' and 'int'

When you use the input function it automatically turns it into a string. You need to go:

vote = int(input('Enter the name of the player you wish to vote for'))

which turns the input into a int type value

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

I have a case where I am transforming a legacy DB2 z/os database timestamp (formatted as: "yyyy-MM-dd'T'HH:mm:ss.SSSZ") into a SqlServer 2016 datetime2 (formatted as: "yyyy-MM-dd HH:mm:ss.SSS) field that is handled by our Spring/Hibernate Entity Manager instance (in this case, the OldRevision Table). In the Class, I define the date as the java.util type, and write the setter and getter in the normal way. Then, When handling the data, the code I have handling the data related to this question looks like this:

OldRevision revision = new OldRevision();
String oldRevisionDateString= oldRevisionData.getString("originalRevisionDate", "");
Date oldDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
oldDateFormat.parse(oldRevisionDateString);
SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
newDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
Date finalFormattedDate= newDateFormat.parse(newDateFormat.format(oldDateFormat));
revision.setOriginalRevisionDate(finalFormattedDate);
em.persist(revision);

A simpler way to do the same case is:

SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
newDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
revision.setOriginalRevisionDate(
        newDateFormat.parse(newDateFormat.format(
                new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ")
                        .parse(rs.getString("originalRevisionDate", "")))));

SQL Server command line backup statement

Combine Remove Old Backup files with above script then this can perform backup by a scheduler, keep last 10 backup files

echo off
:: set folder to save backup files ex. BACKUPPATH=c:\backup
set BACKUPPATH=<<back up folder here>>

:: set Sql Server location ex. set SERVERNAME=localhost\SQLEXPRESS
set SERVERNAME=<<sql host here>>

:: set Database name to backup
set DATABASENAME=<<db name here>>

:: filename format Name-Date (eg MyDatabase-2009-5-19_1700.bak)
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)

set DATESTAMP=%mydate%_%mytime%
set BACKUPFILENAME=%BACKUPPATH%\%DATABASENAME%-%DATESTAMP%.bak
echo.

sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.

:: In this case, we are choosing to keep the most recent 10 files
:: Also, the files we are looking for have a 'bak' extension
for /f "skip=10 delims=" %%F in ('dir %BACKUPPATH%\*.bak /s/b/o-d/a-d') do del "%%F"

What is a stored procedure?

A stored procedure is nothing but a group of SQL statements compiled into a single execution plan.

  1. Create once time and call it n number of times
  2. It reduces the network traffic

Example: creating a stored procedure

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE GetEmployee
      @EmployeeID int = 0
AS
BEGIN
      SET NOCOUNT ON;

      SELECT FirstName, LastName, BirthDate, City, Country
      FROM Employees 
      WHERE EmployeeID = @EmployeeID
END
GO

Alter or modify a stored procedure:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE GetEmployee
      @EmployeeID int = 0
AS
BEGIN
    SET NOCOUNT ON;

    SELECT FirstName, LastName, BirthDate, City, Country
    FROM Employees 
    WHERE EmployeeID = @EmployeeID
END
GO

Drop or delete a stored procedure:

DROP PROCEDURE GetEmployee

How would I access variables from one class to another?

Just create the variables in a class. And then inherit from that class to access its variables. But before accessing them, the parent class has to be called to initiate the variables.

class a:
    def func1(self):
        a.var1 = "Stack "

class b:
    def func2(self):
        b.var2 = "Overflow"

class c(a,b):
    def func3(self):
        c.var3 = a.var1 + b.var2
        print(c.var3)

a().func1()
b().func2()
c().func3()

Why doesn't Java support unsigned ints?

I think Java is fine as it is, adding unsigned would complicate it without much gain. Even with the simplified integer model, most Java programmers don't know how the basic numeric types behave - just read the book Java Puzzlers to see what misconceptions you might hold.

As for practical advice:

  • If your values are somewhat arbitrary size and don't fit into int, use long. If they don't fit into long use BigInteger.

  • Use the smaller types only for arrays when you need to save space.

  • If you need exactly 64/32/16/8 bits, use long/int/short/byte and stop worrying about the sign bit, except for division, comparison, right shift, and casting.

See also this answer about "porting a random number generator from C to Java".

How to hide action bar before activity is created, and then show it again?

Android studio provide in build template for full screen, if you use Android studio you can follow below step to implement full screen activity.

First Step to Create new Activity

Select select Full screen Activity

Done. Android studio did your job, now you can check code for full screen.

How can I disable selected attribute from select2() dropdown Jquery?

In selec2 site you can see options. There is "disabled" option for api. You can use like :

$('#foo').select2({
    disabled: true
});

What is the difference between Trap and Interrupt?

A Trap can be identified as a transfer of control, which is initiated by the programmer. The term Trap is used interchangeably with the term Exception (which is an automatically occurring software interrupt). But some may argue that a trap is simply a special subroutine call. So they fall in to the category of software-invoked interrupts. For example, in 80×86 machines, a programmer can use the int instruction to initiate a trap. Because a trap is always unconditional the control will always be transferred to the subroutine associated with the trap. The exact instruction, which invokes the routine for handling the trap is easily identified because an explicit instruction is used to specify a trap.

What does it mean if a Python object is "subscriptable" or not?

It basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.

Python script to convert from UTF-8 to ASCII

import codecs

 ...

fichier = codecs.open(filePath, "r", encoding="utf-8")

 ...

fichierTemp = codecs.open("tempASCII", "w", encoding="ascii", errors="ignore")
fichierTemp.write(contentOfFile)

 ...

C++ int float casting

You need to use cast. I see the other answers, and they will really work, but as the tag is C++ I'd suggest you to use static_cast:

float m = static_cast< float >( a.y - b.y ) / static_cast< float >( a.x - b.x );

Maven and Spring Boot - non resolvable parent pom - repo.spring.io (Unknown host)

In the pom.xml (after loading effective pom.xml in eclipse), you may see it "http://repo.maven.apache.org/maven2" under central repository instead of "https://repo.maven.apache.org/maven2". Fix it

How to install Anaconda on RaspBerry Pi 3 Model B

If you're interested in generalizing to different architectures, you could also run the command above and substitute uname -m in with backticks like so:

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-`uname -m`.sh

Java - No enclosing instance of type Foo is accessible

static class Thing will make your program work.

As it is, you've got Thing as an inner class, which (by definition) is associated with a particular instance of Hello (even if it never uses or refers to it), which means it's an error to say new Thing(); without having a particular Hello instance in scope.

If you declare it as a static class instead, then it's a "nested" class, which doesn't need a particular Hello instance.

How to do fade-in and fade-out with JavaScript and CSS

Ok, I've worked it out

element.style.opacity = parseFloat(element.style.opacity) + 0.1;

Should be used instead of

element.style.opacity += 0.1;

Same with

element.style.opacity = parseFloat(element.style.opacity) - 0.1;

Instead of

element.style.opacity -= 0.1;

Because opacity value is stored as string, not as float. I'm still not sure though why the addition has worked.

const vs constexpr on variables

I believe there is a difference. Let's rename them so that we can talk about them more easily:

const     double PI1 = 3.141592653589793;
constexpr double PI2 = 3.141592653589793;

Both PI1 and PI2 are constant, meaning you can not modify them. However only PI2 is a compile-time constant. It shall be initialized at compile time. PI1 may be initialized at compile time or run time. Furthermore, only PI2 can be used in a context that requires a compile-time constant. For example:

constexpr double PI3 = PI1;  // error

but:

constexpr double PI3 = PI2;  // ok

and:

static_assert(PI1 == 3.141592653589793, "");  // error

but:

static_assert(PI2 == 3.141592653589793, "");  // ok

As to which you should use? Use whichever meets your needs. Do you want to ensure that you have a compile time constant that can be used in contexts where a compile-time constant is required? Do you want to be able to initialize it with a computation done at run time? Etc.

How to check if a String contains any of some strings

List<string> includedWords = new List<string>() { "a", "b", "c" };
bool string_contains_words = includedWords.Exists(o => s.Contains(o));

Keras, how do I predict after I trained a model?

I trained a neural network in Keras to perform non linear regression on some data. This is some part of my code for testing on new data using previously saved model configuration and weights.

fname = r"C:\Users\tauseef\Desktop\keras\tutorials\BestWeights.hdf5"
modelConfig = joblib.load('modelConfig.pkl')
recreatedModel = Sequential.from_config(modelConfig)
recreatedModel.load_weights(fname)
unseenTestData = np.genfromtxt(r"C:\Users\tauseef\Desktop\keras\arrayOf100Rows257Columns.txt",delimiter=" ")
X_test = unseenTestData
standard_scalerX = StandardScaler()
standard_scalerX.fit(X_test)
X_test_std = standard_scalerX.transform(X_test)
X_test_std = X_test_std.astype('float32')
unseenData_predictions = recreatedModel.predict(X_test_std)

Reset IntelliJ UI to Default

All above answers are correct, but you loose configuration settings.

But if your IDE's only themes or fonts are changed or some UI related issues and you want to restore to default theme, then just delete

${user.home}/.IntelliJIdea13/config/options/options.xml

file while IDE is not running, then after next restart IDE's theme will gets reset to default.

Stored procedure or function expects parameter which is not supplied

In my case I received this exception even when all parameter values were correctly supplied but the type of command was not specified :

cmd.CommandType = System.Data.CommandType.StoredProcedure;

This is obviously not the case in the question above, but exception description is not very clear in this case, so I decided to specify that.

Get URL of ASP.Net Page in code-behind

Do you want the server name? Or the host name?

Request.Url.Host ala Stephen

Dns.GetHostName - Server name

Request.Url will have access to most everything you'll need to know about the page being requested.

get launchable activity name of package from adb

Here is another way to find out apps package name and launcher activity.

Step1: Start "adb logcat" in command prompt.

Step2: Open the app (either in emulator or real device) enter image description here

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

What worked for me was just typing the command passive and ftp went into passive mode from active mode.

How do you sign a Certificate Signing Request with your Certification Authority?

1. Using the x509 module
openssl x509 ...
...

2 Using the ca module
openssl ca ...
...

You are missing the prelude to those commands.

This is a two-step process. First you set up your CA, and then you sign an end entity certificate (a.k.a server or user). Both of the two commands elide the two steps into one. And both assume you have a an OpenSSL configuration file already setup for both CAs and Server (end entity) certificates.


First, create a basic configuration file:

$ touch openssl-ca.cnf

Then, add the following to it:

HOME            = .
RANDFILE        = $ENV::HOME/.rnd

####################################################################
[ ca ]
default_ca    = CA_default      # The default ca section

[ CA_default ]

default_days     = 1000         # How long to certify for
default_crl_days = 30           # How long before next CRL
default_md       = sha256       # Use public key default MD
preserve         = no           # Keep passed DN ordering

x509_extensions = ca_extensions # The extensions to add to the cert

email_in_dn     = no            # Don't concat the email in the DN
copy_extensions = copy          # Required to copy SANs from CSR to cert

####################################################################
[ req ]
default_bits       = 4096
default_keyfile    = cakey.pem
distinguished_name = ca_distinguished_name
x509_extensions    = ca_extensions
string_mask        = utf8only

####################################################################
[ ca_distinguished_name ]
countryName         = Country Name (2 letter code)
countryName_default = US

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

localityName                = Locality Name (eg, city)
localityName_default        = Baltimore

organizationName            = Organization Name (eg, company)
organizationName_default    = Test CA, Limited

organizationalUnitName         = Organizational Unit (eg, division)
organizationalUnitName_default = Server Research Department

commonName         = Common Name (e.g. server FQDN or YOUR name)
commonName_default = Test CA

emailAddress         = Email Address
emailAddress_default = [email protected]

####################################################################
[ ca_extensions ]

subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyid:always, issuer
basicConstraints       = critical, CA:true
keyUsage               = keyCertSign, cRLSign

The fields above are taken from a more complex openssl.cnf (you can find it in /usr/lib/openssl.cnf), but I think they are the essentials for creating the CA certificate and private key.

Tweak the fields above to suit your taste. The defaults save you the time from entering the same information while experimenting with configuration file and command options.

I omitted the CRL-relevant stuff, but your CA operations should have them. See openssl.cnf and the related crl_ext section.

Then, execute the following. The -nodes omits the password or passphrase so you can examine the certificate. It's a really bad idea to omit the password or passphrase.

$ openssl req -x509 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM

After the command executes, cacert.pem will be your certificate for CA operations, and cakey.pem will be the private key. Recall the private key does not have a password or passphrase.

You can dump the certificate with the following.

$ openssl x509 -in cacert.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 11485830970703032316 (0x9f65de69ceef2ffc)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, CN=Test CA/[email protected]
        Validity
            Not Before: Jan 24 14:24:11 2014 GMT
            Not After : Feb 23 14:24:11 2014 GMT
        Subject: C=US, ST=MD, L=Baltimore, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (4096 bit)
                Modulus:
                    00:b1:7f:29:be:78:02:b8:56:54:2d:2c:ec:ff:6d:
                    ...
                    39:f9:1e:52:cb:8e:bf:8b:9e:a6:93:e1:22:09:8b:
                    59:05:9f
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                4A:9A:F3:10:9E:D7:CF:54:79:DE:46:75:7A:B0:D0:C1:0F:CF:C1:8A
            X509v3 Authority Key Identifier:
                keyid:4A:9A:F3:10:9E:D7:CF:54:79:DE:46:75:7A:B0:D0:C1:0F:CF:C1:8A

            X509v3 Basic Constraints: critical
                CA:TRUE
            X509v3 Key Usage:
                Certificate Sign, CRL Sign
    Signature Algorithm: sha256WithRSAEncryption
         4a:6f:1f:ac:fd:fb:1e:a4:6d:08:eb:f5:af:f6:1e:48:a5:c7:
         ...
         cd:c6:ac:30:f9:15:83:41:c1:d1:20:fa:85:e7:4f:35:8f:b5:
         38:ff:fd:55:68:2c:3e:37

And test its purpose with the following (don't worry about the Any Purpose: Yes; see "critical,CA:FALSE" but "Any Purpose CA : Yes").

$ openssl x509 -purpose -in cacert.pem -inform PEM
Certificate purposes:
SSL client : No
SSL client CA : Yes
SSL server : No
SSL server CA : Yes
Netscape SSL server : No
Netscape SSL server CA : Yes
S/MIME signing : No
S/MIME signing CA : Yes
S/MIME encryption : No
S/MIME encryption CA : Yes
CRL signing : Yes
CRL signing CA : Yes
Any Purpose : Yes
Any Purpose CA : Yes
OCSP helper : Yes
OCSP helper CA : Yes
Time Stamp signing : No
Time Stamp signing CA : Yes
-----BEGIN CERTIFICATE-----
MIIFpTCCA42gAwIBAgIJAJ9l3mnO7y/8MA0GCSqGSIb3DQEBCwUAMGExCzAJBgNV
...
aQUtFrV4hpmJUaQZ7ySr/RjCb4KYkQpTkOtKJOU1Ic3GrDD5FYNBwdEg+oXnTzWP
tTj//VVoLD43
-----END CERTIFICATE-----

For part two, I'm going to create another configuration file that's easily digestible. First, touch the openssl-server.cnf (you can make one of these for user certificates also).

$ touch openssl-server.cnf

Then open it, and add the following.

HOME            = .
RANDFILE        = $ENV::HOME/.rnd

####################################################################
[ req ]
default_bits       = 2048
default_keyfile    = serverkey.pem
distinguished_name = server_distinguished_name
req_extensions     = server_req_extensions
string_mask        = utf8only

####################################################################
[ server_distinguished_name ]
countryName         = Country Name (2 letter code)
countryName_default = US

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

localityName         = Locality Name (eg, city)
localityName_default = Baltimore

organizationName            = Organization Name (eg, company)
organizationName_default    = Test Server, Limited

commonName           = Common Name (e.g. server FQDN or YOUR name)
commonName_default   = Test Server

emailAddress         = Email Address
emailAddress_default = [email protected]

####################################################################
[ server_req_extensions ]

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

####################################################################
[ alternate_names ]

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

If you are developing and need to use your workstation as a server, then 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

Then, create the server certificate request. Be sure to omit -x509*. Adding -x509 will create a certificate, and not a request.

$ openssl req -config openssl-server.cnf -newkey rsa:2048 -sha256 -nodes -out servercert.csr -outform PEM

After this command executes, you will have a request in servercert.csr and a private key in serverkey.pem.

And you can inspect it again.

$ openssl req -text -noout -verify -in servercert.csr
Certificate:
    verify OK
    Certificate Request:
        Version: 0 (0x0)
        Subject: C=US, ST=MD, L=Baltimore, CN=Test Server/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:ce:3d:58:7f:a0:59:92:aa:7c:a0:82:dc:c9:6d:
                    ...
                    f9:5e:0c:ba:84:eb:27:0d:d9:e7:22:5d:fe:e5:51:
                    86:e1
                Exponent: 65537 (0x10001)
        Attributes:
        Requested Extensions:
            X509v3 Subject Key Identifier:
                1F:09:EF:79:9A:73:36:C1:80:52:60:2D:03:53:C7:B6:BD:63:3B:61
            X509v3 Basic Constraints:
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Key Encipherment
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
            Netscape Comment:
                OpenSSL Generated Certificate
    Signature Algorithm: sha256WithRSAEncryption
         6d:e8:d3:85:b3:88:d4:1a:80:9e:67:0d:37:46:db:4d:9a:81:
         ...
         76:6a:22:0a:41:45:1f:e2:d6:e4:8f:a1:ca:de:e5:69:98:88:
         a9:63:d0:a7

Next, you have to sign it with your CA.


You are almost ready to sign the server's certificate by your CA. The CA's openssl-ca.cnf needs two more sections before issuing the command.

First, open openssl-ca.cnf and add the following two sections.

####################################################################
[ signing_policy ]
countryName            = optional
stateOrProvinceName    = optional
localityName           = optional
organizationName       = optional
organizationalUnitName = optional
commonName             = supplied
emailAddress           = optional

####################################################################
[ signing_req ]
subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyid,issuer
basicConstraints       = CA:FALSE
keyUsage               = digitalSignature, keyEncipherment

Second, add the following to the [ CA_default ] section of openssl-ca.cnf. I left them out earlier, because they can complicate things (they were unused at the time). Now you'll see how they are used, so hopefully they will make sense.

base_dir      = .
certificate   = $base_dir/cacert.pem   # The CA certifcate
private_key   = $base_dir/cakey.pem    # The CA private key
new_certs_dir = $base_dir              # Location for new certs after signing
database      = $base_dir/index.txt    # Database index file
serial        = $base_dir/serial.txt   # The current serial number

unique_subject = no  # Set to 'no' to allow creation of
                     # several certificates with same subject.

Third, touch index.txt and serial.txt:

$ touch index.txt
$ echo '01' > serial.txt

Then, perform the following:

$ openssl ca -config openssl-ca.cnf -policy signing_policy -extensions signing_req -out servercert.pem -infiles servercert.csr

You should see similar to the following:

Using configuration from openssl-ca.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'US'
stateOrProvinceName   :ASN.1 12:'MD'
localityName          :ASN.1 12:'Baltimore'
commonName            :ASN.1 12:'Test CA'
emailAddress          :IA5STRING:'[email protected]'
Certificate is to be certified until Oct 20 16:12:39 2016 GMT (1000 days)
Sign the certificate? [y/n]:Y

1 out of 1 certificate requests certified, commit? [y/n]Y
Write out database with 1 new entries
Data Base Updated

After the command executes, you will have a freshly minted server certificate in servercert.pem. The private key was created earlier and is available in serverkey.pem.

Finally, you can inspect your freshly minted certificate with the following:

$ openssl x509 -in servercert.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9 (0x9)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, CN=Test CA/[email protected]
        Validity
            Not Before: Jan 24 19:07:36 2014 GMT
            Not After : Oct 20 19:07:36 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, CN=Test Server
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:ce:3d:58:7f:a0:59:92:aa:7c:a0:82:dc:c9:6d:
                    ...
                    f9:5e:0c:ba:84:eb:27:0d:d9:e7:22:5d:fe:e5:51:
                    86:e1
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                1F:09:EF:79:9A:73:36:C1:80:52:60:2D:03:53:C7:B6:BD:63:3B:61
            X509v3 Authority Key Identifier:
                keyid:42:15:F2:CA:9C:B1:BB:F5:4C:2C:66:27:DA:6D:2E:5F:BA:0F:C5:9E

            X509v3 Basic Constraints:
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Key Encipherment
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
            Netscape Comment:
                OpenSSL Generated Certificate
    Signature Algorithm: sha256WithRSAEncryption
         b1:40:f6:34:f4:38:c8:57:d4:b6:08:f7:e2:71:12:6b:0e:4a:
         ...
         45:71:06:a9:86:b6:0f:6d:8d:e1:c5:97:8d:fd:59:43:e9:3c:
         56:a5:eb:c8:7e:9f:6b:7a

Earlier, you added the following to CA_default: copy_extensions = copy. This copies extension provided by the person making the request.

If you omit copy_extensions = copy, then your server certificate will lack the Subject Alternate Names (SANs) like www.example.com and mail.example.com.

If you use copy_extensions = copy, but don't look over the request, then the requester might be able to trick you into signing something like a subordinate root (rather than a server or user certificate). Which means he/she will be able to mint certificates that chain back to your trusted root. Be sure to verify the request with openssl req -verify before signing.


If you omit unique_subject or set it to yes, then you will only be allowed to create one certificate under the subject's distinguished name.

unique_subject = yes            # Set to 'no' to allow creation of
                                # several ctificates with same subject.

Trying to create a second certificate while experimenting will result in the following when signing your server's certificate with the CA's private key:

Sign the certificate? [y/n]:Y
failed to update database
TXT_DB error number 2

So unique_subject = no is perfect for testing.


If you want to ensure the Organizational Name is consistent between self-signed CAs, Subordinate CA and End-Entity certificates, then add the following to your CA configuration files:

[ policy_match ]
organizationName = match

If you want to allow the Organizational Name to change, then use:

[ policy_match ]
organizationName = supplied

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. RFC's 6797 and 7469 do not allow an IP address, either.

Uncompress tar.gz file

gunzip <filename>

then

tar -xvf <tar-file-name>

How do I escape a string inside JavaScript code inside an onClick handler?

Another interesting solution might be to do this:

<a href="#" itemid="<%itemid%>" itemname="<%itemname%>" onclick="SelectSurveyItem(this.itemid, this.itemname); return false;">Select</a>

Then you can use a standard HTML-encoding on both the variables, without having to worry about the extra complication of the javascript quoting.

Yes, this does create HTML that is strictly invalid. However, it is a valid technique, and all modern browsers support it.

If it was my, I'd probably go with my first suggestion, and ensure the values are HTML-encoded and have single-quotes escaped.

git replacing LF with CRLF

Most of tools in Windows accepts only LF in text files. For example you can control the behaviour for Visual Studio in a file named '.editorconfig' with following example content (part):

 indent_style = space
 indent_size = 2
 end_of_line = lf    <<====
 charset = utf-8

Only the original Windows-Notepad does not work with LF but there are some more proper simple editor tools available!

Hence You should use LF in text files in Windows too. This is my message, stronlgy recommended! There is no reason to use CRLF in windows!

(The same discussion is using \ in include paths in C/++, it is bullshit, use #include <pathTo/myheader.h> with slash!, It is the C/++ standard and all microsoft compilers support it).

Hence the proper setting for git is

git config core.autocrlf false

My message: Forget such old thinking programs as dos2unix and unix2dos. Clarify in your team that LF is proper to use under Windows.

How do I add slashes to a string in Javascript?

A string can be escaped comprehensively and compactly using JSON.stringify. It is part of JavaScript as of ECMAScript 5 and supported by major newer browser versions.

str = JSON.stringify(String(str));
str = str.substring(1, str.length-1);

Using this approach, also special chars as the null byte, unicode characters and line breaks \r and \n are escaped properly in a relatively compact statement.

mssql convert varchar to float

DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE 0 END AS YOUR_QUERY_ANSWERED

above will return values

however below query wont work

DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE **@INPUT_1** END AS YOUR_QUERY_ANSWERED

as @INPUT_1 actually has varchar in it.

So your output column must have a varchar in it.

How to convert / cast long to String?

String longString = new String(""+long);

or

String longString = new Long(datelong).toString();

What's the yield keyword in JavaScript?

Before you learn about yield you need to know about generators. Generators are created using the function* syntax. Generator functions do not execute code but instead returns a type of iterator called a generator. When a value is given using the next method, the generator function keeps executing until it comes across a yield keyword. Using yield gives you back an object containing two values, one is value and the other is done (boolean). The value can be an array, object etc.

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

It turns out that you can create 32-bit ODBC connections using C:\Windows\SysWOW64\odbcad32.exe. My solution was to create the 32-bit ODBC connection as a System DSN. This still didn't allow me to connect to it since .NET couldn't look it up. After significant and fruitless searching to find how to get the OdbcConnection class to look for the DSN in the right place, I stumbled upon a web site that suggested modifying the registry to solve a different problem.

I ended up creating the ODBC connection directly under HKLM\Software\ODBC. I looked in the SysWOW6432 key to find the parameters that were set up using the 32-bit version of the ODBC administration tool and recreated this in the standard location. I didn't add an entry for the driver, however, as that was not installed by the standard installer for the app either.

After creating the entry (by hand), I fired up my windows service and everything was happy.

Getting execute permission to xp_cmdshell

To expand on what has been provided for automatically exporting data as csv to a network share via SQL Server Agent.

(1) Enable the xp_cmdshell procedure:

-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO

-- Enable the xp_cmdshell procedure
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
GO

(2) Create a login 'Domain\TestUser' (windows user) for the non-sysadmin user that has public access to the master database. Done through user mapping

(3) Give log on as batch job: Navigate to Local Security Policy -> Local Policies -> User Rights Assignment. Add user to "Log on as a batch job"

(4) Give read/write permissions to network folder for domain\user

(5) Grant EXEC permission on the xp_cmdshell stored procedure:

GRANT EXECUTE ON xp_cmdshell TO [Domain\TestUser]

(6) Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account

EXEC sp_xp_cmdshell_proxy_account 'Domain\TestUser', 'password_for_domain_user'

(7) If the sp_xp_cmdshell_proxy_account command doesn't work, manually create it

create credential ##xp_cmdshell_proxy_account## with identity = 'Domain\DomainUser', secret = 'password'

(8) Enable SQL Server Agent. Open SQL Server Configuration Manager, navigate to SQL Server Services, enable SQL Server Agent.

(9) Create automated job. Open SSMS, select SQL Server Agent, then right-click jobs and click "New Job".

(10) Select "Owner" as your created user. Select "Steps", make "type" = T-SQL. Fill out command field similar to below. Set delimiter as ','

EXEC master..xp_cmdshell 'SQLCMD -q "select * from master" -o file.csv -s "," 

(11) Fill out schedules accordingly.

How to create folder with PHP code?

Purely basic folder creation

<?php mkdir("testing"); ?> <= this, actually creates a folder called "testing".



Basic file creation

<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>

Use the a or a+ switch to add/append to file.



EDIT:

This version will create a file and folder at the same time and show it on screen after.

<?php

// change the name below for the folder you want
$dir = "new_folder_name";

$file_to_write = 'test.txt';
$content_to_write = "The content";

if( is_dir($dir) === false )
{
    mkdir($dir);
}

$file = fopen($dir . '/' . $file_to_write,"w");

// a different way to write content into
// fwrite($file,"Hello World.");

fwrite($file, $content_to_write);

// closes the file
fclose($file);

// this will show the created file from the created folder on screen
include $dir . '/' . $file_to_write;

?>

Remove all spaces from a string in SQL Server

Reference taken from this blog:

First, Create sample table and data:

CREATE TABLE tbl_RemoveExtraSpaces
(
     Rno INT
     ,Name VARCHAR(100)
)
GO

INSERT INTO tbl_RemoveExtraSpaces VALUES (1,'I    am     Anvesh   Patel')
INSERT INTO tbl_RemoveExtraSpaces VALUES (2,'Database   Research and     Development  ')
INSERT INTO tbl_RemoveExtraSpaces VALUES (3,'Database    Administrator     ')
INSERT INTO tbl_RemoveExtraSpaces VALUES (4,'Learning    BIGDATA    and       NOSQL ')
GO

Script to SELECT string without Extra Spaces:

SELECT
     [Rno]
    ,[Name] AS StringWithSpace
    ,LTRIM(RTRIM(REPLACE(REPLACE(REPLACE([Name],CHAR(32),'()'),')(',''),'()',CHAR(32)))) AS StringWithoutSpace
FROM tbl_RemoveExtraSpaces

Result:

Rno         StringWithSpace                                 StringWithoutSpace
----------- -----------------------------------------  ---------------------------------------------
1           I    am     Anvesh   Patel                      I am Anvesh Patel
2           Database   Research and     Development         Database Research and Development
3           Database    Administrator                       Database Administrator
4           Learning    BIGDATA    and       NOSQL          Learning BIGDATA and NOSQL

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

This error is encountered when the primary key of a table is updated but it is referenced by a foreign key from another table and the update specific is set to No action. The No action is the default option.

If this is your case and No action is set on the update operation you can change the foreign-key definition to Cascade.

Right click your foreign key and select Modify. In the Foreign key relationships dialog under the INSERT and UPDATE specifics set the UPDATE rule on Cascade:

enter image description here

You can also set the rule using T-SQL:

ALTER TABLE YourTable
DROP Constraint Your_FK
GO

ALTER TABLE YourTable
ADD CONSTRAINT [New_FK_Constraint]
FOREIGN KEY (YourColumn) REFERENCES ReferencedTable(YourColumn)
ON DELETE CASCADE ON UPDATE CASCADE
GO 

Hope this helps

Generating an MD5 checksum of a file

change the file_path to your file

import hashlib
def getMd5(file_path):
    m = hashlib.md5()
    with open(file_path,'rb') as f:
        line = f.read()
        m.update(line)
    md5code = m.hexdigest()
    return md5code

GetFiles with multiple extensions

I'm not sure if that is possible. The MSDN GetFiles reference says a search pattern, not a list of search patterns.

I might be inclined to fetch each list separately and "foreach" them into a final list.

Regular expression to extract numbers from a string

^\s*(\w+)\s*\(\s*(\d+)\D+(\d+)\D+\)\s*$

should work. After the match, backreference 1 will contain the month, backreference 2 will contain the first number and backreference 3 the second number.

Explanation:

^     # start of string
\s*   # optional whitespace
(\w+) # one or more alphanumeric characters, capture the match
\s*   # optional whitespace
\(    # a (
\s*   # optional whitespace
(\d+) # a number, capture the match
\D+   # one or more non-digits
(\d+) # a number, capture the match
\D+   # one or more non-digits
\)    # a )
\s*   # optional whitespace
$     # end of string

Git for beginners: The definitive practical guide

How to install Git

On Windows:

Install msysgit

There are several downloads:

  • Git: Use this unless you specifically need one of the other options below.
  • PortableGit: Use this if you want to run Git on a PC without installing on that PC (e.g. running Git from a USB drive)
  • msysGit: Use this if you want to develop Git itself. If you just want to use Git for your source code, but don't want to edit Git's source code, you don't need this.

This also installs a Cygwin bash shell, so you can use the git in a nicer shell (than cmd.exe), and also includes git-gui (accessible via git gui command, or the Start > All Programs > Git menu)

Mac OS X

Use the git-osx-installer, or you can also install from source

Via a package manager

Install git using your native package manager. For example, on Debian (or Ubuntu):

apt-get install git-core

Or on Mac OS X, via MacPorts:

sudo port install git-core+bash_completion+doc

…or fink:

fink install git

…or Homebrew:

brew install git

On Red Hat based distributions, such as Fedora:

yum install git

In Cygwin the Git package can be found under the "devel" section

From source (Mac OS X/Linux/BSD/etc.)

In Mac OS X, if you have the Developer Tools installed, you can compile Git from source very easily. Download the latest version of Git as a .tar.bz or .tar.gz from http://git-scm.com/, and extract it (double click in Finder)

On Linux/BSD/etc. it should be much the same. For example, in Debian (and Ubuntu), you need to install the build-essential package via apt.

Then in a Terminal, cd to where you extracted the files (Running cd ~/Downloads/git*/ should work), and then run..

./configure && make && sudo make install

This will install Git into the default place (/usr/local - so git will be in /usr/local/bin/git)

It will prompt you to enter your password (for sudo), this is so it can write to the /usr/local/ directory, which can only be accessed by the "root" user so sudo is required!

If you with to install it somewhere separate (so Git's files aren't mixed in with other tools), use --prefix with the configure command:

./configure --prefix=/usr/local/gitpath
make
sudo make install

This will install the git binary into /usr/local/bin/gitpath/bin/git - so you don't have to type that every time you, you should add into your $PATH by adding the following line into your ~/.profile:

export PATH="${PATH}:/usr/local/bin/gitpath/bin/"

If you do not have sudo access, you can use --prefix=/Users/myusername/bin and install into your home directory. Remember to add ~/bin/ to $PATH

The script x-git-update-to-latest-version automates a lot of this:

This script updates my local clone of the git repo (localy at ~/work/track/git), and then configures, installs (at /usr/local/git-git describe) and updates the /usr/local/git symlink.

This way, I can have /usr/local/git/bin in my PATH and I'm always using the latest version.

The latest version of this script also installs the man pages. You need to tweak your MANPATH to include the /usr/local/git/share/man directory.

How can I format bytes a cell in Excel as KB, MB, GB etc?

Paste this next to your values(bytes) and this will automatically change it to whatever your size of value is.

=IF(G10>=1099511627776,CONCATENATE(ROUND((G10/1024/1024/1024/1024),1)," TB"),IF(G10>=1073741824,CONCATENATE(ROUND((G10/1024/1024/1024),1)," GB"),IF(G10>=1048576,CONCATENATE(ROUND((G10/1024/1024),1)," MB"),IF(G10>=1024,CONCATENATE(ROUND((G10/1024),1)," KB"),IF(G10>=1,CONCATENATE((G10)," BYTES"),0)))))

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

How can I sort a dictionary by key?

A timing comparison of the two methods in 2.7 shows them to be virtually identical:

>>> setup_string = "a = sorted(dict({2:3, 1:89, 4:5, 3:0}).items())"
>>> timeit.timeit(stmt="[(k, val) for k, val in a]", setup=setup_string, number=10000)
0.003599141953657181

>>> setup_string = "from collections import OrderedDict\n"
>>> setup_string += "a = OrderedDict({1:89, 2:3, 3:0, 4:5})\n"
>>> setup_string += "b = a.items()"
>>> timeit.timeit(stmt="[(k, val) for k, val in b]", setup=setup_string, number=10000)
0.003581275490432745 

Aggregate / summarize multiple variables per group (e.g. sum, mean)

Interestingly, base R aggregate's data.frame method is not showcased here, above the formula interface is used, so for completeness:

aggregate(
  x = df1[c("x1", "x2")],
  by = df1[c("year", "month")],
  FUN = sum, na.rm = TRUE
)

More generic use of aggregate's data.frame method:

Since we are providing a

  • data.frame as x and
  • a list (data.frame is also a list) as by, this is very useful if we need to use it in a dynamic manner, e.g. using other columns to be aggregated and to aggregate by is very simple
  • also with custom-made aggregation functions

For example like so:

colsToAggregate <- c("x1")
aggregateBy <- c("year", "month")
dummyaggfun <- function(v, na.rm = TRUE) {
  c(sum = sum(v, na.rm = na.rm), mean = mean(v, na.rm = na.rm))
}

aggregate(df1[colsToAggregate], by = df1[aggregateBy], FUN = dummyaggfun)

'console' is undefined error for Internet Explorer

You can use console.log(...) directly in Firefox but not in IEs. In IEs you have to use window.console.

Loop Through Each HTML Table Column and Get the Data using jQuery

My first post...

I tried this: change 'tr' for 'td' and you will get all HTMLRowElements into an Array, and using textContent will change from Object into String

var dataArray = [];
var data = table.find('td'); //Get All HTML td elements

// Save important data into new Array
for (var i = 0; i <= data.size() - 1; i = i + 4)
{
  dataArray.push(data[i].textContent, data[i + 1].textContent, data[i + 2].textContent);
}

How to draw a graph in LaTeX?

Aside from the (excellent) suggestion to use TikZ, you could use gastex. I used this before TikZ was available and it did its job too.

Error related to only_full_group_by when executing a query in MySql

Use ANY_VALUE() to refer to the nonaggregated column.

SELECT name,           address , MAX(age) FROM t GROUP BY name; -- fails
SELECT name, ANY_VALUE(address), MAX(age) FROM t GROUP BY name; -- works

From MySQL 5.7 docs:

You can achieve the same effect without disabling ONLY_FULL_GROUP_BY by using ANY_VALUE() to refer to the nonaggregated column.

...

This query might be invalid with ONLY_FULL_GROUP_BY enabled because the nonaggregated address column in the select list is not named in the GROUP BY clause:

SELECT name, address, MAX(age) FROM t GROUP BY name;

...

If you know that, for a given data set, each name value in fact uniquely determines the address value, address is effectively functionally dependent on name. To tell MySQL to accept the query, you can use the ANY_VALUE() function:

SELECT name, ANY_VALUE(address), MAX(age) FROM t GROUP BY name;

ActionBarActivity is deprecated

Since the version 22.1.0, the class ActionBarActivity is deprecated. You should use AppCompatActivity.

Read here and here for more information.

How to use JavaScript with Selenium WebDriver Java

You need to run this command in the top-level directory of a Selenium SVN repository checkout.

how to access the command line for xampp on windows

Thank you guys for this answers. But I think the accepted answer needs more clarity, As i found difficulty in getting the solution.

  1. We may set the environment variable as mentioned in the answer by w0rldart .

    In this case(after seting envmnt var) we may run the phpFile by opening start >> CMD and typing commands like,

    php.exe <path to file location>

    or

    php <path to file location>

    example:

    php.exe C:\xampp\htdocs\test.php
    
  2. you can open Start >> CMD as administrator and write like

    <path to php.exe in xampp's php folder> <path to file location>

    example:

    C:\xampp\php\php.exe C:\xampp\htdocs\test.php
    

    or

    C:\xampp\php\php C:\xampp\htdocs\test.php
    

Hopes this will help somebody.

Curl to return http status code along with the response

the verbose mode will tell you everything

curl -v http://localhost

Disabling Chrome cache for website development

enter image description here

Clearing the cache is too annoying when you need to clear the cache 30 times an hour.. so I installed a Chrome Extension called Classic Cache Killer that clears the cache on every page load.

Chrome Store Link (free) (Now without malware!)

Now my mock json, javascript, css, html and data refreshes every time on every page load.

I never have to worry if I need to clear my cache.

There are about 20 cache cleaners for Chrome I found, but this one seemed lightweight and zero effort. In an update, Cache Killer can now stay "always on".

Note: I do not know the plugin author in any way. I just found it useful.

How can I enable the MySQLi extension in PHP 7?

sudo phpenmod mysqli
sudo service apache2 restart

  • phpenmod moduleName enables a module to PHP 7 (restart Apache after that sudo service apache2 restart)
  • phpdismod moduleName disables a module to PHP 7 (restart Apache after that sudo service apache2 restart)
  • php -m lists the loaded modules

Add image in pdf using jspdf

No need to add any extra base64 library. Simple 5 line solution -

var img = new Image();
img.src = path.resolve('sample.jpg');

var doc = new jsPDF('p', 'mm', 'a3');  // optional parameters
doc.addImage(img, 'JPEG', 1, 2);
doc.save("new.pdf");

What does the 'L' in front a string mean in C++?

It means the text is stored as wchar_t characters rather than plain old char characters.

(I originally said it meant unicode. I was wrong about that. But it can be used for unicode.)

Jquery Validate custom error message location

JQUERY FORM VALIDATION CUSTOM ERROR MESSAGE

Demo & example

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $("#registration").validate({_x000D_
    // Specify validation rules_x000D_
    rules: {_x000D_
      firstname: "required",_x000D_
      lastname: "required",_x000D_
      email: {_x000D_
        required: true,_x000D_
        email: true_x000D_
      },      _x000D_
      phone: {_x000D_
        required: true,_x000D_
        digits: true,_x000D_
        minlength: 10,_x000D_
        maxlength: 10,_x000D_
      },_x000D_
      password: {_x000D_
        required: true,_x000D_
        minlength: 5,_x000D_
      }_x000D_
    },_x000D_
    messages: {_x000D_
      firstname: {_x000D_
      required: "Please enter first name",_x000D_
     },      _x000D_
     lastname: {_x000D_
      required: "Please enter last name",_x000D_
     },     _x000D_
     phone: {_x000D_
      required: "Please enter phone number",_x000D_
      digits: "Please enter valid phone number",_x000D_
      minlength: "Phone number field accept only 10 digits",_x000D_
      maxlength: "Phone number field accept only 10 digits",_x000D_
     },     _x000D_
     email: {_x000D_
      required: "Please enter email address",_x000D_
      email: "Please enter a valid email address.",_x000D_
     },_x000D_
    },_x000D_
  _x000D_
  });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>jQuery Form Validation Using validator()</title>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> _x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>_x000D_
<style>_x000D_
  .error{_x000D_
    color: red;_x000D_
  }_x000D_
  label,_x000D_
  input,_x000D_
  button {_x000D_
    border: 0;_x000D_
    margin-bottom: 3px;_x000D_
    display: block;_x000D_
    width: 100%;_x000D_
  }_x000D_
 .common_box_body {_x000D_
    padding: 15px;_x000D_
    border: 12px solid #28BAA2;_x000D_
    border-color: #28BAA2;_x000D_
    border-radius: 15px;_x000D_
    margin-top: 10px;_x000D_
    background: #d4edda;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div class="common_box_body test">_x000D_
  <h2>Registration</h2>_x000D_
  <form action="#" name="registration" id="registration">_x000D_
 _x000D_
    <label for="firstname">First Name</label>_x000D_
    <input type="text" name="firstname" id="firstname" placeholder="John"><br>_x000D_
 _x000D_
    <label for="lastname">Last Name</label>_x000D_
    <input type="text" name="lastname" id="lastname" placeholder="Doe"><br>_x000D_
 _x000D_
    <label for="phone">Phone</label>_x000D_
    <input type="text" name="phone" id="phone" placeholder="8889988899"><br>  _x000D_
 _x000D_
    <label for="email">Email</label>_x000D_
    <input type="email" name="email" id="email" placeholder="[email protected]"><br>_x000D_
 _x000D_
    <label for="password">Password</label>_x000D_
    <input type="password" name="password" id="password" placeholder=""><br>_x000D_
 _x000D_
    <input name="submit" type="submit" id="submit" class="submit" value="Submit">_x000D_
  </form>_x000D_
</div>_x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

MySQL Trigger - Storing a SELECT in a variable

You can declare local variables in MySQL triggers, with the DECLARE syntax.

Here's an example:

DROP TABLE IF EXISTS foo;
CREATE TABLE FOO (
  i SERIAL PRIMARY KEY
);

DELIMITER //
DROP TRIGGER IF EXISTS bar //

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = NEW.i;
  SET @a = x; -- set user variable outside trigger
END//

DELIMITER ;

SET @a = 0;

SELECT @a; -- returns 0

INSERT INTO foo () VALUES ();

SELECT @a; -- returns 1, the value it got during the trigger

When you assign a value to a variable, you must ensure that the query returns only a single value, not a set of rows or a set of columns. For instance, if your query returns a single value in practice, it's okay but as soon as it returns more than one row, you get "ERROR 1242: Subquery returns more than 1 row".

You can use LIMIT or MAX() to make sure that the local variable is set to a single value.

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = (SELECT age FROM users WHERE name = 'Bill'); 
  -- ERROR 1242 if more than one row with 'Bill'
END//

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = (SELECT MAX(age) FROM users WHERE name = 'Bill');
  -- OK even when more than one row with 'Bill'
END//

Substring in excel

In Excel, the substring function is called MID function, and indexOf is called FIND for case-sensitive location and SEARCH function for non-case-sensitive location. For the first portion of your text parsing the LEFT function may also be useful.

See all the text functions here: Text Functions (reference).

Full worksheet function reference lists available at:

    Excel functions (by category)
    Excel functions (alphabetical)

JavaScript: Global variables after Ajax requests

It seems that your problem is simply a concurrency issue. The post function takes a callback argument to tell you when the post has been finished. You cannot make the alert in global scope like this and expect that the post has already been finished. You have to move it to the callback function.

How to overload functions in javascript?

I like to add sub functions within a parent function to achieve the ability to differentiate between argument groups for the same functionality.

var doSomething = function() {
    var foo;
    var bar;
};

doSomething.withArgSet1 = function(arg0, arg1) {
    var obj = new doSomething();
    // do something the first way
    return obj;
};

doSomething.withArgSet2 = function(arg2, arg3) {
    var obj = new doSomething();
    // do something the second way
    return obj;
};

Ruby convert Object to Hash

class Gift
  def initialize
    @name = "book"
    @price = 15.95
  end
end

gift = Gift.new
hash = {}
gift.instance_variables.each {|var| hash[var.to_s.delete("@")] = gift.instance_variable_get(var) }
p hash # => {"name"=>"book", "price"=>15.95}

Alternatively with each_with_object:

gift = Gift.new
hash = gift.instance_variables.each_with_object({}) { |var, hash| hash[var.to_s.delete("@")] = gift.instance_variable_get(var) }
p hash # => {"name"=>"book", "price"=>15.95}

How can I pretty-print JSON using node.js?

what about this?

console.table(object)

sample

Get startup type of Windows service using PowerShell

If you update to PowerShell 5 you can query all of the services on the machine and display Name and StartType and sort it by StartType for easy viewing:

Get-Service |Select-Object -Property Name,StartType |Sort-Object -Property StartType

Android OnClickListener - identify a button

The best way is by switch-ing between v.getId(). Having separate anonymous OnClickListener for each Button is taking up more memory. Casting View to Button is unnecessary. Using if-else when switch is possible is slower and harder to read. In Android's source you can often notice comparing the references by if-else:

if (b1 == v) {
 // ...
} else if (b2 == v) {

I don't know exactly why they chose this way, but it works too.

How can I make one python file run another?

You'd treat one of the files as a python module and make the other one import it (just as you import standard python modules). The latter can then refer to objects (including classes and functions) defined in the imported module. The module can also run whatever initialization code it needs. See http://docs.python.org/tutorial/modules.html

Efficiently finding the last line in a text file

lines = file.readlines()
fileHandle.close()
last_line = lines[-1]

How to check a string starts with numeric number?

This should work:

String s = "123foo";
Character.isDigit(s.charAt(0));

Accessing Google Account Id /username via Android

There is a sample from google, which lists the existing google accounts and generates an access token upon selection , you can send that access token to server to retrieve the related details from it to identify the user.

You can also get the email id from access token , for that you need to modify the SCOPE

Please go through My Post

An "and" operator for an "if" statement in Bash

What you have should work, unless ${STATUS} is empty. It would probably be better to do:

if ! [ "${STATUS}" -eq 200 ] 2> /dev/null && [ "${STRING}" != "${VALUE}" ]; then

or

if [ "${STATUS}" != 200 ] && [ "${STRING}" != "${VALUE}" ]; then

It's hard to say, since you haven't shown us exactly what is going wrong with your script.

Personal opinion: never use [[. It suppresses important error messages and is not portable to different shells.

Java - using System.getProperty("user.dir") to get the home directory

way of getting home directory of current user is

String currentUsersHomeDir = System.getProperty("user.home");

and to append path separator

String otherFolder = currentUsersHomeDir + File.separator + "other";

File.separator

The system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar.

Test if registry value exists

I would go with the function Get-RegistryValue. In fact it gets requested values (so that it can be used not only for testing). As far as registry values cannot be null, we can use null result as a sign of a missing value. The pure test function Test-RegistryValue is also provided.

# This function just gets $true or $false
function Test-RegistryValue($path, $name)
{
    $key = Get-Item -LiteralPath $path -ErrorAction SilentlyContinue
    $key -and $null -ne $key.GetValue($name, $null)
}

# Gets the specified registry value or $null if it is missing
function Get-RegistryValue($path, $name)
{
    $key = Get-Item -LiteralPath $path -ErrorAction SilentlyContinue
    if ($key) {
        $key.GetValue($name, $null)
    }
}

# Test existing value
Test-RegistryValue HKCU:\Console FontFamily
$val = Get-RegistryValue HKCU:\Console FontFamily
if ($val -eq $null) { 'missing value' } else { $val }

# Test missing value
Test-RegistryValue HKCU:\Console missing
$val = Get-RegistryValue HKCU:\Console missing
if ($val -eq $null) { 'missing value' } else { $val }

OUTPUT:

True
54
False
missing value

php foreach with multidimensional array

You can use array_walk_recursive:

array_walk_recursive($array, function ($item, $key) {
    echo "$key holds $item\n";
});

C++ program converts fahrenheit to celsius

Fahrenheit to celsius would be (Fahrenheit - 32) * 5 / 9

Check if a div exists with jquery

If you are simply checking for the existence of an ID, there is no need to go into jQuery, you could simply:

if(document.getElementById("yourid") !== null)
{
}

getElementById returns null if it can't be found.

Reference.

If however you plan to use the jQuery object later i'd suggest:

$(document).ready(function() {
    var $myDiv = $('#DivID');

    if ( $myDiv.length){
        //you can now reuse  $myDiv here, without having to select it again.
    }


});

A selector always returns a jQuery object, so there shouldn't be a need to check against null (I'd be interested if there is an edge case where you need to check for null - but I don't think there is).

If the selector doesn't find anything then length === 0 which is "falsy" (when converted to bool its false). So if it finds something then it should be "truthy" - so you don't need to check for > 0. Just for it's "truthyness"

Get Cell Value from a DataTable in C#

You probably need to reference it from the Rowsrather than as a cell:

var cellValue = dt.Rows[i][j];

Returning Promises from Vuex actions

Actions

ADD_PRODUCT : (context,product) => {
  return Axios.post(uri, product).then((response) => {
    if (response.status === 'success') {  
      context.commit('SET_PRODUCT',response.data.data)
    }
    return response.data
  });
});

Component

this.$store.dispatch('ADD_PRODUCT',data).then((res) => {
  if (res.status === 'success') {
    // write your success actions here....
  } else {
     // write your error actions here...
  }
})

Get SELECT's value and text in jQuery

$("#yourdropdownid option:selected").text(); // selected option text
$("#yourdropdownid").val(); // selected option value

Count all occurrences of a string in lots of files with grep

Another oneliner using basic command line functions handling multiple occurences per line.

 cat * |sed s/string/\\\nstring\ /g |grep string |wc -l

How to make a smooth image rotation in Android?

As hanry has mentioned above putting liner iterpolator is fine. But if rotation is inside a set you must put android:shareInterpolator="false" to make it smooth.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
**android:shareInterpolator="false"**
>
<rotate
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="300"
    android:fillAfter="true"
    android:repeatCount="10"
    android:repeatMode="restart"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%" />
<scale xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="3000"
    android:fillAfter="true"
    android:pivotX="50%"
    android:pivotY="50%"
    android:fromXScale="1.0"
    android:fromYScale="1.0"
    android:toXScale="0"
    android:toYScale="0" />
</set>

If Sharedinterpolator being not false, the above code gives glitches.

Java : How to determine the correct charset encoding of a stream

For ISO8859_1 files, there is not an easy way to distinguish them from ASCII. For Unicode files however one can generally detect this based on the first few bytes of the file.

UTF-8 and UTF-16 files include a Byte Order Mark (BOM) at the very beginning of the file. The BOM is a zero-width non-breaking space.

Unfortunately, for historical reasons, Java does not detect this automatically. Programs like Notepad will check the BOM and use the appropriate encoding. Using unix or Cygwin, you can check the BOM with the file command. For example:

$ file sample2.sql 
sample2.sql: Unicode text, UTF-16, big-endian

For Java, I suggest you check out this code, which will detect the common file formats and select the correct encoding: How to read a file and automatically specify the correct encoding

How to fix 'android.os.NetworkOnMainThreadException'?

Android Jetpack introduced WorkManager,which fixes the problem of background service restriction in Oreo and use of Alarm Manager below Lolipop and JobScheduler above Lolipop.

Please use WorkManager to run tasks on background thread and it's continue to run even after user closes the app.

Android get current Locale, not default

As per official documentation ConfigurationCompat is deprecated in support libraries

You can consider using

LocaleListCompat.getDefault()[0].toLanguageTag() 0th position will be user preferred locale

To get Default locale at 0th position would be LocaleListCompat.getAdjustedDefault()

If REST applications are supposed to be stateless, how do you manage sessions?

REST is very abstract. It helps to have some good, simple, real-world examples.

Take for example all major social media apps -- Tumblr, Instagram, Facebook, and Twitter. They all have a forever-scrolling view where the farther you scroll down, the more content you see, further and further back in time. However, we've all experienced that moment where you lose where you were scrolled to, and the app resets you back to the top. Like if you quit the app, then when you reopen it, you're back at the top again.

The reason why, is because the server did not store your session state. Sadly, your scroll position was just stored in RAM on the client.

Fortunately you don't have to log back in when you reconnect, but that's only because your client-side also stored login certificate has not expired. Delete and reinstall the app, and you're going to have to log back in, because the server did not associate your IP address with your session.

You don't have a login session on the server, because they abide by REST.


Now the above examples don't involve a web browser at all, but on the back end, the apps are communicating via HTTPS with their host servers. My point is that REST does not have to involve cookies and browsers etc. There are various means of storing client-side session state.

But lets talk about web browsers for a second, because that brings up another major advantage of REST that nobody here is talking about.

If the server tried to store session state, how is it supposed to identify each individual client?

It could not use their IP address, because many people could be using that same address on a shared router. So how, then?

It can't use MAC address for many reasons, not the least of which because you can be logged into multiple different Facebook accounts simultaneously on different browsers plus the app. One browser can easily pretend to be another one, and MAC addresses are just as easy to spoof.

If the server has to store some client-side state to identify you, it has to store it in RAM longer than just the time it takes to process your requests, or else it has to cache that data. Servers have limited amounts of RAM and cache, not to mention processor speed. Server-side state adds to all three, exponentially. Plus if the server is going to store any state about your sessions then it has to store it separately for each browser and app you're currently logged in with, and also for each different device you use.


So... I hope that you see now why REST is so important for scalability. I hope you can start to see why server-side session state is to server scalability what welded-on anvils are to car acceleration.


Where people get confused is by thinking that "state" refers to, like, information stored in a database. No, it refers to any information that needs to be in the RAM of the server when you're using it.

Java Regex Replace with Capturing Group

Java 9 offers a Matcher.replaceAll() that accepts a replacement function:

resultString = regexMatcher.replaceAll(
        m -> String.valueOf(Integer.parseInt(m.group()) * 3));

How to open the Chrome Developer Tools in a new window?

You have to click and hold until the other icon shows up, then slide the mouse down to the icon.

'NOT LIKE' in an SQL query

You need to specify the column in both expressions.

SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'

How to verify if $_GET exists?

   if (isset($_GET["id"])){
        //do stuff
    }

C++ - how to find the length of an integer

If you can use C libraries then one method would be to use sprintf, e.g.

#include <cstdio>

char s[32];

int len = sprintf(s, "%d", i);

How can I do factory reset using adb in android?

Try :

adb shell
recovery --wipe_data

And here is the list of arguments :

* The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

In My case there was space in the path that was failing the script.If you are using variables like $PROJECT_DIR or $TARGET_BUILD_DIR then replace them "$PROJECT_DIR" or "$TARGET_BUILD_DIR" respectively.After adding quotes my script ran successfully.

How do I restrict an input to only accept numbers?

Here is a pretty good solution to makes only allow enter number to the input:

<input type="text" ng-model="myText" name="inputName" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>

Generating Fibonacci Sequence

You Could Try This Fibonacci Solution Here

var a = 0;
console.log(a);
var b = 1;
console.log(b);
var c;
for (i = 0; i < 3; i++) {
  c = a + b;
  console.log(c);
  a = b + c;
  console.log(a);
  b = c + a;
  console.log(b);
}

How to check if a database exists in SQL Server?

From a Microsoft's script:

DECLARE @dbname nvarchar(128)
SET @dbname = N'Senna'

IF (EXISTS (SELECT name 
FROM master.dbo.sysdatabases 
WHERE ('[' + name + ']' = @dbname 
OR name = @dbname)))

-- code mine :)
PRINT 'db exists'

Binding Button click to a method

Here is the VB.Net rendition of Rachel's answer above.

Obviously the XAML binding is the same...

<Button Command="{Binding Path=SaveCommand}" />

Your Custom Class would look like this...

''' <summary>
''' Retrieves an new or existing RelayCommand.
''' </summary>
''' <returns>[RelayCommand]</returns>
Public ReadOnly Property SaveCommand() As ICommand
    Get
        If _saveCommand Is Nothing Then
            _saveCommand = New RelayCommand(Function(param) SaveObject(), Function(param) CanSave())
        End If
        Return _saveCommand
    End Get
End Property
Private _saveCommand As ICommand

''' <summary>
''' Returns Boolean flag indicating if command can be executed.
''' </summary>
''' <returns>[Boolean]</returns>
Private Function CanSave() As Boolean
    ' Verify command can be executed here.
    Return True
End Function

''' <summary>
''' Code to be run when the command is executed.
''' </summary>
''' <remarks>Converted to a Function in VB.net to avoid the "Expression does not produce a value" error.</remarks>
''' <returns>[Nothing]</returns>
Private Function SaveObject()
    ' Save command execution logic.
   Return Nothing
End Function

And finally the RelayCommand class is as follows...

Public Class RelayCommand : Implements ICommand

ReadOnly _execute As Action(Of Object)
ReadOnly _canExecute As Predicate(Of Object)
Private Event ICommand_CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged

''' <summary>
''' Creates a new command that can always execute.
''' </summary>
''' <param name="execute">The execution logic.</param>
Public Sub New(execute As Action(Of Object))
    Me.New(execute, Nothing)
End Sub

''' <summary>
''' Creates a new command.
''' </summary>
''' <param name="execute">The execution logic.</param>
''' <param name="canExecute">The execution status logic.</param>
Public Sub New(execute As Action(Of Object), canExecute As Predicate(Of Object))
    If execute Is Nothing Then
        Throw New ArgumentNullException("execute")
    End If
    _execute = execute
    _canExecute = canExecute
End Sub

<DebuggerStepThrough>
Public Function CanExecute(parameters As Object) As Boolean Implements ICommand.CanExecute
    Return If(_canExecute Is Nothing, True, _canExecute(parameters))
End Function

Public Custom Event CanExecuteChanged As EventHandler
    AddHandler(ByVal value As EventHandler)
        AddHandler CommandManager.RequerySuggested, value
    End AddHandler
    RemoveHandler(ByVal value As EventHandler)
        RemoveHandler CommandManager.RequerySuggested, value
    End RemoveHandler
    RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
        If (_canExecute IsNot Nothing) Then
            _canExecute.Invoke(sender)
        End If
    End RaiseEvent
End Event

Public Sub Execute(parameters As Object) Implements ICommand.Execute
    _execute(parameters)
End Sub

End Class

Hope that helps any VB.Net developers!

How to create a drop-down list?

In Kotlin you can do as:

First, put this code in your layout

   <Spinner
            android:id="@+id/spinner"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"/>

Then you can do in onCreate() in Activity as ->

   val spinner = findViewById<Spinner>(R.id.spinner)
    val items = arrayOf("500g", "1kg", "2kg")
    val adapter = ArrayAdapter<String>(
        this,
        android.R.layout.simple_spinner_dropdown_item,
        items
    )
    spinner.setAdapter(adapter)

You can get listener from dropdown as:

 spinner.onItemSelectedListener = object : OnItemSelectedListener {
        override fun onItemSelected(
            arg0: AdapterView<*>?,
            arg1: View?,
            arg2: Int,
            arg3: Long
        ) {
            // Do what you want
            val items = spinner.selectedItem.toString()
            
        }

        override fun onNothingSelected(arg0: AdapterView<*>?) {}
    }

How to scan a folder in Java?

You can also use the FileFilter interface to filter out what you want. It is best used when you create an anonymous class that implements it:

import java.io.File;
import java.io.FileFilter;

public class ListFiles {
    public File[] findDirectories(File root) { 
        return root.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory();
            }});
    }

    public File[] findFiles(File root) {
        return root.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isFile();
            }});
    }
}

EditText underline below text property

It's actually fairly easy to set the underline color of an EditText programmatically (just one line of code).

To set the color:

editText.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);

To remove the color:

editText.getBackground().clearColorFilter();

Note: when the EditText has focus on, the color you set won't take effect, instead, it has a focus color.

API Reference:

Drawable#setColorFilter

Drawable#clearColorFilter

How to update PATH variable permanently from Windows command line?

In a corporate network, where the user has only limited access and uses portable apps, there are these command line tricks:

  1. Query the user env variables: reg query "HKEY_CURRENT_USER\Environment". Use "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" for LOCAL_MACHINE.
  2. Add new user env variable: reg add "HKEY_CURRENT_USER\Environment" /v shared_dir /d "c:\shared" /t REG_SZ. Use REG_EXPAND_SZ for paths containing other %% variables.
  3. Delete existing env variable: reg delete "HKEY_CURRENT_USER\Environment" /v shared_dir.

Prevent form submission on Enter key press

A react js solution

 handleChange: function(e) {
    if (e.key == 'Enter') {
      console.log('test');
    }


 <div>
    <Input type="text"
       ref = "input"
       placeholder="hiya"
       onKeyPress={this.handleChange}
    />
 </div>

Angular + Material - How to refresh a data source (mat-table)

Since you are using MatPaginator, you just need to do any change to paginator, this triggers data reload.

Simple trick:

this.paginator._changePageSize(this.paginator.pageSize); 

This updates the page size to the current page size, so basically nothing changes, except the private _emitPageEvent() function is called too, triggeing table reload.

Format ints into string of hex

Example with some beautifying, similar to the sep option available in python 3.8

def prettyhex(nums, sep=''):
    return sep.join(f'{a:02x}' for a in nums)

numbers = [0, 1, 2, 3, 127, 200, 255]
print(prettyhex(numbers,'-'))

output

00-01-02-03-7f-c8-ff

Syntax for if/else condition in SCSS mixin

You can assign default parameter values inline when you first create the mixin:

@mixin clearfix($width: 'auto') {

  @if $width == 'auto' {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

HTML table: keep the same width for columns

give this style to td: width: 1%;

How do I see the current encoding of a file in Sublime Text?

For my part, and without any plug-in, simply saving the file either from the File menu or with keyboards shortcuts

CTRL + S (Windows, Linux) or CMD + S (Mac OS)

briefly displays the current encoding - between parentheses - in the status bar, at the bottom of the editor's window. This suggestion works in Sublime Text 2 and 3.

Note that the displayed encoding to the right in the status bar of Sublime Text 3, may display the wrong encoding of the file if you have attempted to save the file with an encoding that can't represent all the characters in your file. In this case you would have seen an informational dialog and Sublime telling you it's falling back to UTF-8. This may not be the case, so be careful.

jQuery validation: change default error message

Another possible solution is to loop over the fields, adding the same error message to each field.

$('.required').each(function(index) {
  $(this).rules("add", {
    messages: {
      required: "Custom error message."
   }
  });
});

Simple way to create matrix of random numbers

#this is a function for a square matrix so on the while loop rows does not have to be less than cols.
#you can make your own condition. But if you want your a square matrix, use this code.

import random

import numpy as np

def random_matrix(R, cols):

        matrix = []

        rows =  0

        while  rows < cols:

            N = random.sample(R, cols)

            matrix.append(N)

            rows = rows + 1

    return np.array(matrix)

print(random_matrix(range(10), 5))
#make sure you understand the function random.sample

"The operation is not valid for the state of the transaction" error and transaction scope

After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:

public void MyAddUpdateMethod()
{
    using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
    {
        using(SQLServer Sql = new SQLServer(this.m_connstring))
        {
            //do my first add update statement            
        }

        //removed the method call from the first sql server using statement
        bool DoesRecordExist = this.SelectStatementCall(id)
    }
}

public bool SelectStatementCall(System.Guid id)
{
    using(SQLServer Sql = new SQLServer(this.m_connstring))
    {
        //create parameters
    }
}

UICollectionView auto scroll to cell at IndexPath

I totally agree with the above answer. The only thing is that for me the solution was set the code in viewDidAppear

viewDidAppear 
{
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:YES];
}

When I used the viewWillAppear the scrolling didn't work.

Google Map API v3 — set bounds and center

My suggestion for google maps api v3 would be(don't think it can be done more effeciently):

gmap : {
    fitBounds: function(bounds, mapId)
    {
        //incoming: bounds - bounds object/array; mapid - map id if it was initialized in global variable before "var maps = [];"
        if (bounds==null) return false;
        maps[mapId].fitBounds(bounds);
    }
}

In the result u will fit all points in bounds in your map window.

Example works perfectly and u freely can check it here www.zemelapis.lt

How to make an autocomplete TextBox in ASP.NET?

Try this: .aspx page

<td>  
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"OnTextChanged="TextBox1_TextChanged"></asp:TextBox>  
<asp:AutoCompleteExtender ServiceMethod="GetCompletionList" MinimumPrefixLength="1"  
   CompletionInterval="10" EnableCaching="false" CompletionSetCount="1" TargetControlID="TextBox1"  
   ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">  
      </asp:AutoCompleteExtender>  

Now To auto populate from database :

public static List<string> GetCompletionList(string prefixText, int count)  
    {  
        return AutoFillProducts(prefixText);  

    }  

    private static List<string> AutoFillProducts(string prefixText)  
    {  
        using (SqlConnection con = new SqlConnection())  
        {  
            con.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;  
            using (SqlCommand com = new SqlCommand())  
            {  
                com.CommandText = "select ProductName from ProdcutMaster where " + "ProductName like @Search + '%'";  
                com.Parameters.AddWithValue("@Search", prefixText);  
                com.Connection = con;  
                con.Open();  
                List<string> countryNames = new List<string>();  
                using (SqlDataReader sdr = com.ExecuteReader())  
                {  
                    while (sdr.Read())  
                    {  
                        countryNames.Add(sdr["ProductName"].ToString());  
                    }  
                }  
                con.Close();  
                return countryNames;  
            }  
        }  
    }  

Now:create a stored Procedure that fetches the Product details depending on the selected product from the Auto Complete Text Box.

Create Procedure GetProductDet  
(  
@ProductName varchar(50)    
)  
as  
begin  
Select BrandName,warranty,Price from ProdcutMaster where ProductName=@ProductName  
End   

Create a function name to get product details ::

private void GetProductMasterDet(string ProductName)  
    {  
        connection();  
        com = new SqlCommand("GetProductDet", con);  
        com.CommandType = CommandType.StoredProcedure;  
        com.Parameters.AddWithValue("@ProductName", ProductName);  
        SqlDataAdapter da = new SqlDataAdapter(com);  
        DataSet ds=new DataSet();  
        da.Fill(ds);  
        DataTable dt = ds.Tables[0];  
        con.Close();  
        //Binding TextBox From dataTable  
        txtbrandName.Text =dt.Rows[0]["BrandName"].ToString();  
        txtwarranty.Text = dt.Rows[0]["warranty"].ToString();  
        txtPrice.Text = dt.Rows[0]["Price"].ToString();   
    }

Auto post back should be true

<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>

Now, Just call this function

protected void TextBox1_TextChanged(object sender, EventArgs e)  
  {  
      //calling method and Passing Values  
      GetProductMasterDet(TextBox1.Text);  
  } 

How to check if spark dataframe is empty?

For Spark 2.1.0, my suggestion would be to use head(n: Int) or take(n: Int) with isEmpty, whichever one has the clearest intent to you.

df.head(1).isEmpty
df.take(1).isEmpty

with Python equivalent:

len(df.head(1)) == 0  # or bool(df.head(1))
len(df.take(1)) == 0  # or bool(df.take(1))

Using df.first() and df.head() will both return the java.util.NoSuchElementException if the DataFrame is empty. first() calls head() directly, which calls head(1).head.

def first(): T = head()
def head(): T = head(1).head

head(1) returns an Array, so taking head on that Array causes the java.util.NoSuchElementException when the DataFrame is empty.

def head(n: Int): Array[T] = withAction("head", limit(n).queryExecution)(collectFromPlan)

So instead of calling head(), use head(1) directly to get the array and then you can use isEmpty.

take(n) is also equivalent to head(n)...

def take(n: Int): Array[T] = head(n)

And limit(1).collect() is equivalent to head(1) (notice limit(n).queryExecution in the head(n: Int) method), so the following are all equivalent, at least from what I can tell, and you won't have to catch a java.util.NoSuchElementException exception when the DataFrame is empty.

df.head(1).isEmpty
df.take(1).isEmpty
df.limit(1).collect().isEmpty

I know this is an older question so hopefully it will help someone using a newer version of Spark.

How to remove \n from a list element?

Using list comprehension:

myList = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']

[(el.strip()) for el in myList]

differences in application/json and application/x-www-form-urlencoded

The first case is telling the web server that you are posting JSON data as in:

{ Name : 'John Smith', Age: 23}

The second option is telling the web server that you will be encoding the parameters in the URL as in:

Name=John+Smith&Age=23

How do I put a variable inside a string?

In general, you can create strings using:

stringExample = "someString " + str(someNumber)
print(stringExample)
plot.savefig(stringExample)

Regular expression to search multiple strings (Textpad)

To get the lines that contain the texts 8768, 9875 or 2353, use:

^.*(8768|9875|2353).*$

What it means:

^                      from the beginning of the line
.*                     get any character except \n (0 or more times)
(8768|9875|2353)       if the line contains the string '8768' OR '9875' OR '2353'
.*                     and get any character except \n (0 or more times)
$                      until the end of the line

If you do want the literal * char, you'd have to escape it:

^.*(\*8768|\*9875|\*2353).*$

When to use If-else if-else over switch statements and vice versa

This depends very much on the specific case. Preferably, I think one should use the switch over the if-else if there are many nested if-elses.

The question is how much is many?

Yesterday I was asking myself the same question:

public enum ProgramType {
    NEW, OLD
}

if (progType == OLD) {
    // ...
} else if (progType == NEW) {
    // ...
}

if (progType == OLD) {
    // ...
} else {
    // ...
}

switch (progType) {
case OLD:
    // ...
    break;
case NEW:
    // ...
    break;
default:
    break;
}

In this case, the 1st if has an unnecessary second test. The 2nd feels a little bad because it hides the NEW.

I ended up choosing the switch because it just reads better.

PySpark: multiple conditions in when clause

You get SyntaxError error exception because Python has no && operator. It has and and & where the latter one is the correct choice to create boolean expressions on Column (| for a logical disjunction and ~ for logical negation).

Condition you created is also invalid because it doesn't consider operator precedence. & in Python has a higher precedence than == so expression has to be parenthesized.

(col("Age") == "") & (col("Survived") == "0")
## Column<b'((Age = ) AND (Survived = 0))'>

On a side note when function is equivalent to case expression not WHEN clause. Still the same rules apply. Conjunction:

df.where((col("foo") > 0) & (col("bar") < 0))

Disjunction:

df.where((col("foo") > 0) | (col("bar") < 0))

You can of course define conditions separately to avoid brackets:

cond1 = col("Age") == "" 
cond2 = col("Survived") == "0"

cond1 & cond2

How to describe table in SQL Server 2008?

Just enter the below line.

exec sp_help [table_name]

How can I use the python HTMLParser library to extract data from a specific div tag?

class LinksParser(HTMLParser.HTMLParser):
  def __init__(self):
    HTMLParser.HTMLParser.__init__(self)
    self.recording = 0
    self.data = []

  def handle_starttag(self, tag, attributes):
    if tag != 'div':
      return
    if self.recording:
      self.recording += 1
      return
    for name, value in attributes:
      if name == 'id' and value == 'remository':
        break
    else:
      return
    self.recording = 1

  def handle_endtag(self, tag):
    if tag == 'div' and self.recording:
      self.recording -= 1

  def handle_data(self, data):
    if self.recording:
      self.data.append(data)

self.recording counts the number of nested div tags starting from a "triggering" one. When we're in the sub-tree rooted in a triggering tag, we accumulate the data in self.data.

The data at the end of the parse are left in self.data (a list of strings, possibly empty if no triggering tag was met). Your code from outside the class can access the list directly from the instance at the end of the parse, or you can add appropriate accessor methods for the purpose, depending on what exactly is your goal.

The class could be easily made a bit more general by using, in lieu of the constant literal strings seen in the code above, 'div', 'id', and 'remository', instance attributes self.tag, self.attname and self.attvalue, set by __init__ from arguments passed to it -- I avoided that cheap generalization step in the code above to avoid obscuring the core points (keep track of a count of nested tags and accumulate data into a list when the recording state is active).

Adding Counter in shell script

Try this:

counter=0
while true; do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       break
  elif [[ "$counter" -gt 20 ]]; then
       echo "Counter limit reached, exit script."
       exit 1
  else
       let counter++
       echo "Sleeping for another half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

Explanation

  • break - if files are present, it will break and allow the script to process the files.
  • [[ "$counter" -gt 20 ]] - if the counter variable is greater than 20, the script will exit.
  • let counter++ - increments the counter by 1 at each pass.

MySQL GROUP BY two columns

Using Concat on the group by will work

SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30

"No such file or directory" error when executing a binary

The answer is in this line of the output of readelf -a in the original question

  [Requesting program interpreter: /lib/ld-linux.so.2]

I was missing the /lib/ld-linux.so.2 file, which is needed to run 32-bit apps. The Ubuntu package that has this file is libc6-i386.

NULL or BLANK fields (ORACLE)

Try the nvl function. select count(nvl(col_name,0)) from table.

Sorry I reread the OP. What is the table structure? is the column varchar or char as that will make a difference?

try

select count(col_name), distinct(col_name) from table group by distinct(col_name)  

/can't remember if you need distinct in the group by but I think not/

and see if it gives you a return with a column name that is blank.

Saving Excel workbook to constant path with filename from two fields

Ok, at that time got it done with the help of a friend and the code looks like this.

Sub Saving()

Dim part1 As String

Dim part2 As String


part1 = Range("C5").Value

part2 = Range("C8").Value


ActiveWorkbook.SaveAs Filename:= _

"C:\-docs\cmat\Desktop\pieteikumi\" & part1 & " " & part2 & ".xlsm", FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False

End Sub

How do I edit this part (FileFormat:= _ xlOpenXMLWorkbookMacroEnabled) for it to save as Excel 97-2013 Workbook, have tried several variations with no success. Thankyou

Seems, that I found the solution, but my idea is flawed. By doing this FileFormat:= _ xlOpenXMLWorkbook, it drops out a popup saying, the you cannot save this workbook as a file without Macro enabled. So, is this impossible?

How to display the function, procedure, triggers source code in postgresql?

\sf function_name in psql yields editable source code of a single function.

From https://www.postgresql.org/docs/9.6/static/app-psql.html:

\sf[+] function_description This command fetches and shows the definition of the named function, in the form of a CREATE OR REPLACE FUNCTION command.

If + is appended to the command name, then the output lines are numbered, with the first line of the function body being line 1.

Replacing accented characters php

It's worked like magically, i have used only array, this pattern is worked for me. check this pattern

jQuery removeClass wildcard

If you want to use it in other places I suggest you an extension. This one is working fine for me.

 $.fn.removeClassStartingWith = function (filter) {
    $(this).removeClass(function (index, className) {
        return (className.match(new RegExp("\\S*" + filter + "\\S*", 'g')) || []).join(' ')
    });
    return this;
};

Usage:

$(".myClass").removeClassStartingWith('color');

Should I use pt or px?

pt is a derivation (abbreviation) of "point" which historically was used in print type faces where the size was commonly "measured" in "points" where 1 point has an approximate measurement of 1/72 of an inch, and thus a 72 point font would be 1 inch in size.

px is an abbreviation for "pixel" which is a simple "dot" on either a screen or a dot matrix printer or other printer or device which renders in a dot fashion - as opposed to old typewriters which had a fixed size, solid striker which left an imprint of the character by pressing on a ribbon, thus leaving an image of a fixed size.

Closely related to point are the terms "uppercase" and "lowercase" which historically had to do with the selection of the fixed typographical characters where the "captital" characters where placed in a box (case) above the non-captitalized characters which were place in a box below, and thus the "lower" case.

There were different boxes (cases) for different typographical fonts and sizes, but still and "upper" and "lower" case for each of those.

Another term is the "pica" which is a measure of one character in the font, thus a pica is 1/6 of an inch or 12 point units of measure (12/72) of measure.

Strickly speaking the measurement is on computers 4.233mm or 0.166in whereas the old point (American) is 1/72.27 of an inch and French is 4.512mm (0.177in.). Thus my statement of "approximate" regarding the measurements.

Further, typewriters as used in offices, had either and "Elite" or a "Pica" size where the size was 10 and 12 characters per inch repectivly.

Additionally, the "point", prior to standardization was based on the metal typographers "foot" size, the size of the basic footprint of one character, and varied somewhat in size.

Note that a typographical "foot" was originally from a deceased printers actual foot. A typographic foot contains 72 picas or 864 points.

As to CSS use, I prefer to use EM rather than px or pt, thus gaining the advantage of scaling without loss of relative location and size.

EDIT: Just for completeness you can think of EM (em) as an element of measure of one font height, thus 1em for a 12pt font would be the height of that font and 2em would be twice that height. Note that for a 12px font, 2em is 24 pixels. SO 10px is typically 0.63em of a standard font as "most" browsers base on 16px = 1em as a standard font size.

How to write a large buffer into a binary file in C++, fast?

I'd suggest trying file mapping. I used mmapin the past, in a UNIX environment, and I was impressed by the high performance I could achieve

In which case do you use the JPA @JoinTable annotation?

It's the only solution to map a ManyToMany association : you need a join table between the two entities tables to map the association.

It's also used for OneToMany (usually unidirectional) associations when you don't want to add a foreign key in the table of the many side and thus keep it independent of the one side.

Search for @JoinTable in the hibernate documentation for explanations and examples.

Paste text on Android Emulator

I got tired of this problem so I just made this alias to handle it:

alias ap="pbpaste | xargs adb shell input text"

Then when you open a new terminal window, typing "ap" will paste whatever is on your clipboard into the emulator's actively selected text field.

Setup

Simply add this to your profile (for most users that's ~/.bash_profile for zsh users that's ~/.zshrc) to make the alias available everywhere. Alternatively, if you're a bash user (the default for MacOS), then you can run the following command in the terminal to set it up for you:

echo "alias ap='pbpaste | xargs adb shell input text'" >> ~/.bash_profile && source ~/.bash_profile

How to copy files between two nodes using ansible

As ant31 already pointed out you can use the synchronize module to this. By default, the module transfers files between the control machine and the current remote host (inventory_host), however that can be changed using the task's delegate_to parameter (it's important to note that this is a parameter of the task, not of the module).

You can place the task on either ServerA or ServerB, but you have to adjust the direction of the transfer accordingly (using the mode parameter of synchronize).

Placing the task on ServerB

- hosts: ServerB
  tasks:
    - name: Transfer file from ServerA to ServerB
      synchronize:
        src: /path/on/server_a
        dest: /path/on/server_b
      delegate_to: ServerA

This uses the default mode: push, so the file gets transferred from the delegate (ServerA) to the current remote (ServerB).

This might sound like strange, since the task has been placed on ServerB (via hosts: ServerB). However, one has to keep in mind that the task is actually executed on the delegated host, which in this case is ServerA. So pushing (from ServerA to ServerB) is indeed the correct direction. Also remember that we cannot simply choose not to delegate at all, since that would mean that the transfer happens between the control machine and ServerB.

Placing the task on ServerA

- hosts: ServerA
  tasks:
    - name: Transfer file from ServerA to ServerB
      synchronize:
        src: /path/on/server_a
        dest: /path/on/server_b
        mode: pull
      delegate_to: ServerB

This uses mode: pull to invert the transfer direction. Again, keep in mind that the task is actually executed on ServerB, so pulling is the right choice.

Can I set background image and opacity in the same property?

Simple solution

if you need to set the gradient to background-image only:

background-image: url(IMAGE_URL); /* fallback for older browsers */

background-image: linear-gradient(to bottom, rgba(0,0,0,0.6) 0%,rgba(0,0,0,0.6) 100%), url(IMAGE_URL);

Can I automatically increment the file build version when using Visual Studio?

I came up with a solution similar to Christians but without depending on the Community MSBuild tasks, this is not an option for me as I do not want to install these tasks for all of our developers.

I am generating code and compiling to an Assembly and want to auto-increment version numbers. However, I can not use the VS 6.0.* AssemblyVersion trick as it auto-increments build numbers each day and breaks compatibility with Assemblies that use an older build number. Instead, I want to have a hard-coded AssemblyVersion but an auto-incrementing AssemblyFileVersion. I've accomplished this by specifying AssemblyVersion in the AssemblyInfo.cs and generating a VersionInfo.cs in MSBuild like this,

  <PropertyGroup>
    <Year>$([System.DateTime]::Now.ToString("yy"))</Year>
    <Month>$([System.DateTime]::Now.ToString("MM"))</Month>
    <Date>$([System.DateTime]::Now.ToString("dd"))</Date>
    <Time>$([System.DateTime]::Now.ToString("HHmm"))</Time>
    <AssemblyFileVersionAttribute>[assembly:System.Reflection.AssemblyFileVersion("$(Year).$(Month).$(Date).$(Time)")]</AssemblyFileVersionAttribute>
  </PropertyGroup>
  <Target Name="BeforeBuild">
    <WriteLinesToFile File="Properties\VersionInfo.cs" Lines="$(AssemblyFileVersionAttribute)" Overwrite="true">
    </WriteLinesToFile>
  </Target>

This will generate a VersionInfo.cs file with an Assembly attribute for AssemblyFileVersion where the version follows the schema of YY.MM.DD.TTTT with the build date. You must include this file in your project and build with it.

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

How to set a CMake option() at command line

An additional option is to go to your build folder and use the command ccmake .

This is like the GUI but terminal based. This obviously won't help with an installation script but at least it can be run without a UI.

The one warning I have is it won't let you generate sometimes when you have warnings. if that is the case, exit the interface and call cmake .

Unable to install pyodbc on Linux

Execute the following commands (tested on centos 6.5):

yum install install unixodbc-dev
yum install gcc-c++
yum install python-devel
pip install --allow-external pyodbc --allow-unverified pyodbc pyodbc

What is the main purpose of setTag() getTag() methods of View?

Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.

Reference: http://developer.android.com/reference/android/view/View.html

How do I loop through a date range?

Here are my 2 cents in 2020.

Enumerable.Range(0, (endDate - startDate).Days + 1)
.ToList()
.Select(a => startDate.AddDays(a));

How can the size of an input text box be defined in HTML?

The size attribute works, as well

<input size="25" type="text">

Using event.target with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

<button 
  data-space="home" 
  className="home" 
  data-txt="Home" 
  onClick={ this.props.onClick } 
/> 
  Button
</button>

onClick(e) {
   console.log(e.target.dataset.txt, e.target.dataset.space);
}

Example

HTML Upload MAX_FILE_SIZE does not appear to work

MAX_FILE_SIZE is in KB not bytes. You were right, it is in bytes. So, for a limit of 4MB convert 4MB in bytes {1024 * (1024 * 4)} try:

<input type="hidden" name="MAX_FILE_SIZE" value="4194304" /> 

enter image description here

Update 1

As explained by others, you will never get a warning for this. It's there just to impose a soft limit on server side.

Update 2

To answer your sub-question. Yes, there is a difference, you NEVER trust the user input. If you want to always impose a limit, you always must check its size. Don't trust what MAX_FILE_SIZE does, because it can be changed by a user. So, yes, you should check to make sure it's always up to or above the size you want it to be.

The difference is that if you have imposed a MAX_FILE_SIZE of 2MB and the user tries to upload a 4MB file, once they reach roughly the first 2MB of upload, the transfer will terminate and the PHP will stop accepting more data for that file. It will report the error on the files array.

How to send Basic Auth with axios

There is an "auth" parameter for Basic Auth:

auth: {
  username: 'janedoe',
  password: 's00pers3cret'
}

Source/Docs: https://github.com/mzabriskie/axios

Example:

await axios.post(session_url, {}, {
  auth: {
    username: uname,
    password: pass
  }
});

Dealing with float precision in Javascript

From this post: How to deal with floating point number precision in JavaScript?

You have a few options:

  • Use a special datatype for decimals, like decimal.js
  • Format your result to some fixed number of significant digits, like this: (Math.floor(y/x) * x).toFixed(2)
  • Convert all your numbers to integers

Simple InputBox function

The simplest way to get an input box is with the Read-Host cmdlet and -AsSecureString parameter.

$us = Read-Host 'Enter Your User Name:' -AsSecureString
$pw = Read-Host 'Enter Your Password:' -AsSecureString

This is especially useful if you are gathering login info like my example above. If you prefer to keep the variables obfuscated as SecureString objects you can convert the variables on the fly like this:

[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw))

If the info does not need to be secure at all you can convert it to plain text:

$user = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))

Read-Host and -AsSecureString appear to have been included in all PowerShell versions (1-6) but I do not have PowerShell 1 or 2 to ensure the commands work identically. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/read-host?view=powershell-3.0

Persist javascript variables across pages?

For completeness, also look into the local storage capabilities & sessionStorage of HTML5. These are supported in the latest versions of all modern browsers, and are much easier to use and less fiddly than cookies.

http://www.w3.org/TR/2009/WD-webstorage-20091222/

https://www.w3.org/TR/webstorage/. (second edition)

Here are some sample code for setting and getting the values using sessionStorage and localStorage :

 // HTML5 session Storage
 sessionStorage.setItem("variableName","test");
 sessionStorage.getItem("variableName");


//HTML5 local storage 
localStorage.setItem("variableName","Text");
// Receiving the data:
localStorage.getItem("variableName");

Iterate over array of objects in Typescript

You can use the built-in forEach function for arrays.

Like this:

//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
    element.product_desc = element.product_desc.substring(0,10);
});

Your version wasn't wrong though. It should look more like this:

for(let i=0; i<data.products.length; i++){
    console.log(data.products[i].product_desc); //use i instead of 0
}

Remove last character from C++ string

str.erase( str.end()-1 )

Reference: std::string::erase() prototype 2

no c++11 or c++0x needed.

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

What about this :


    public static bool SafeInvoke( this Control control, MethodInvoker method )
    {
        if( control != null && ! control.IsDisposed && control.IsHandleCreated && control.FindForm().IsHandleCreated )
        {
            if( control.InvokeRequired )
            {
                control.Invoke( method );
            }
            else
            {
                method();
            }
            return true;
        }
        else return false;
    }

Use latest version of Internet Explorer in the webbrowser control

Rather than changing the RegKey, I was able to put a line in the header of my HTML:

<html>
    <head>
        <!-- Use lastest version of Internet Explorer -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />

        <!-- Insert other header tags here -->
    </head>
    ...
</html>

See Web Browser Control & Specifying the IE Version.

PHP - remove all non-numeric characters from a string

Use \D to match non-digit characters.

preg_replace('~\D~', '', $str);

How to get the python.exe location programmatically?

This works in Linux & Windows:

Python 3.x

>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe

Python 2.x

>>> import sys
>>> print sys.executable
/usr/bin/python

Are (non-void) self-closing tags valid in HTML5?

I would be very careful with self closing tags as this example demonstrates:

var a = '<span/><span/>';
var d = document.createElement('div');
d.innerHTML = a
console.log(d.innerHTML) // "<span><span></span></span>"

My gut feeling would have been <span></span><span></span> instead

ALTER DATABASE failed because a lock could not be placed on database

I will add this here in case someone will be as lucky as me.

When reviewing the sp_who2 list of processes note the processes that run not only for the effected database but also for master. In my case the issue that was blocking the database was related to a stored procedure that started a xp_cmdshell.

Check if you have any processes in KILL/RollBack state for master database

SELECT *
FROM sys.sysprocesses
WHERE cmd = 'KILLED/ROLLBACK'

If you have the same issue, just the KILL command will probably not help. You can restarted the SQL server, or better way is to find the cmd.exe under windows processes on SQL server OS and kill it.

PHP 7 simpleXML

Had the same problem on AWS Linux 2, phpinfo() shows SimpleXML installed but not working, below cmd solved my issue

sudo yum install php-xml

Switching to a TabBar tab view programmatically?

Note that the tabs are indexed starting from 0. So the following code snippet works

tabBarController = [[UITabBarController alloc] init];
.
.
.
tabBarController.selectedViewController = [tabBarController.viewControllers objectAtIndex:4];

goes to the fifth tab in the bar.

Initialising a multidimensional array in Java

 int[][] myNums = { {1, 2, 3, 4, 5, 6, 7}, {5, 6, 7, 8, 9, 10, 11} };
 for (int x = 0; x < myNums.length; ++x) {
    for(int y = 0; y < myNums[i].length; ++y) {
       System.out.print(myNums[x][y]);
    }
 }

Output

1 2 3 4 5 6 7 5 6 7 8 9 10 11

Checking Bash exit status of several commands efficiently

For what it's worth, a shorter way to write code to check each command for success is:

command1 || echo "command1 borked it"
command2 || echo "command2 borked it"

It's still tedious but at least it's readable.

Convert double to string C++?

I believe the sprintf is the right function for you. I's in the standard library, like printf. Follow the link below for more information:

http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

How do I programmatically set the value of a select box element using JavaScript?

You can use this function:

selectElement('leaveCode', '11')

function selectElement(id, valueToSelect) {    
    let element = document.getElementById(id);
    element.value = valueToSelect;
}

Get value of Span Text

_x000D_
_x000D_
var span_Text = document.getElementById("span_Id").innerText;_x000D_
_x000D_
console.log(span_Text)
_x000D_
<span id="span_Id">I am the Text </span>
_x000D_
_x000D_
_x000D_

Is there a command to undo git init?

remove the .git folder in your project root folder

if you installed submodules and want to remove their git, also remove .git from submodules folders

How to search for rows containing a substring?

Well, you can always try WHERE textcolumn LIKE "%SUBSTRING%" - but this is guaranteed to be pretty slow, as your query can't do an index match because you are looking for characters on the left side.

It depends on the field type - a textarea usually won't be saved as VARCHAR, but rather as (a kind of) TEXT field, so you can use the MATCH AGAINST operator.

To get the columns that don't match, simply put a NOT in front of the like: WHERE textcolumn NOT LIKE "%SUBSTRING%".

Whether the search is case-sensitive or not depends on how you stock the data, especially what COLLATION you use. By default, the search will be case-insensitive.

Updated answer to reflect question update:

I say that doing a WHERE field LIKE "%value%" is slower than WHERE field LIKE "value%" if the column field has an index, but this is still considerably faster than getting all values and having your application filter. Both scenario's:

1/ If you do SELECT field FROM table WHERE field LIKE "%value%", MySQL will scan the entire table, and only send the fields containing "value".

2/ If you do SELECT field FROM table and then have your application (in your case PHP) filter only the rows with "value" in it, MySQL will also scan the entire table, but send all the fields to PHP, which then has to do additional work. This is much slower than case #1.

Solution: Please do use the WHERE clause, and use EXPLAIN to see the performance.

DIV height set as percentage of screen?

Try using Viewport Height

div {
    height:100vh; 
}

It is already discussed here in detail

How to pattern match using regular expression in Scala?

You can do this because regular expressions define extractors but you need to define the regex pattern first. I don't have access to a Scala REPL to test this but something like this should work.

val Pattern = "([a-cA-C])".r
word.firstLetter match {
   case Pattern(c) => c bound to capture group here
   case _ =>
}

Overlay a background-image with an rgba background-color

Ideally the background property would allow us to layer various backgrounds similar to the background image layering detailed at http://www.css3.info/preview/multiple-backgrounds/. Unfortunately, at least in Chrome (40.0.2214.115), adding an rgba background alongside a url() image background seems to break the property.

The solution I've found is to render the rgba layer as a 1px*1px Base64 encoded image and inline it.

.the-div:hover {
  background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgkAQAABwAGkn5GOoAAAAASUVORK5CYII=), url("the-image.png");
}

for base64 encoded 1*1 pixel images I used http://px64.net/

Here is your jsfiddle with these changes made. http://jsfiddle.net/325Ft/49/ (I also swapped the image to one that still exists on the internet)

How to enable loglevel debug on Apache2 server

You need to use LogLevel rewrite:trace3 to your httpd.conf in newer version http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#logging

How can I see the request headers made by curl when sending a request to the server?

dump the headers in one file and the payload of the response in a different file

curl -k -v -u user:pass  "url" --trace-ascii headers.txt >> response.txt

How do you enable mod_rewrite on any OS?

Nope, mod_rewrite is an Apache module and has nothing to do with PHP.

To activate the module, the following line in httpd.conf needs to be active:

LoadModule rewrite_module modules/mod_rewrite.so

to see whether it is already active, try putting a .htaccess file into a web directory containing the line

RewriteEngine on

if this works without throwing a 500 internal server error, and the .htaccess file gets parsed, URL rewriting works.

Unique constraint on multiple columns

USE [TSQL2012]
GO

/****** Object:  Table [dbo].[Table_1]    Script Date: 11/22/2015 12:45:47 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Table_1](
    [seq] [bigint] IDENTITY(1,1) NOT NULL,
    [ID] [int] NOT NULL,
    [name] [nvarchar](50) NULL,
    [cat] [nvarchar](50) NULL,
 CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [IX_Table_1] UNIQUE NONCLUSTERED 
(
    [name] ASC,
    [cat] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Creating .exe distributions isn't typical for Java. While such wrappers do exist, the normal mode of operation is to create a .jar file.

To create a .jar file from a Java project in Eclipse, use file->export->java->Jar file. This will create an archive with all your classes.

On the command prompt, use invocation like the following:

java -cp myapp.jar foo.bar.MyMainClass

What is the maximum length of a valid email address?

The other answers muddy the water a bit. Simple answer: 254 total chars in our control for email 256 are for the ENTIRE email address, which includes implied "<" at the beginning, and ">" at the end. Therefore, 254 are left over for our use.

Concatenate multiple node values in xpath

Try this expression...

string-join(//element3/(concat(element4/text(), '.', element5/text())), "&#10;")

Regex to match string containing two names in any order

Try:

james.*jack

If you want both at the same time, then or them:

james.*jack|jack.*james

How to remove "disabled" attribute using jQuery?

to remove disabled attribute use,

 $("#elementID").removeAttr('disabled');

and to add disabled attribute use,

$("#elementID").prop("disabled", true);

Enjoy :)

Converting double to string

double.toString() should work. Not the variable type Double, but the variable itself double.

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

final Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msgs) {
        //write your code hear which give error
        }
        }

new Thread(new Runnable() {
    @Override
    public void run() {
    handler.sendEmptyMessage(1);
        //this will call handleMessage function and hendal all error
    }
    }).start();

EF Core add-migration Build Failed

The developer ended up un-mapping the project from TFS, deleting it, and re-mapping it. It's now working for him.

Is there a way to get the XPath in Google Chrome?

I tried almost all the available extensions and found the below to be one of the best.

ChroPath Extension link

Just like FirePath, this extension directly gives you the Xpath when you click on Inspect.

enter image description here

Google Maps V3 - How to calculate the zoom level for a given bounds

Thanks to Giles Gardam for his answer, but it addresses only longitude and not latitude. A complete solution should calculate the zoom level needed for latitude and the zoom level needed for longitude, and then take the smaller (further out) of the two.

Here is a function that uses both latitude and longitude:

function getBoundsZoomLevel(bounds, mapDim) {
    var WORLD_DIM = { height: 256, width: 256 };
    var ZOOM_MAX = 21;

    function latRad(lat) {
        var sin = Math.sin(lat * Math.PI / 180);
        var radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
        return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
    }

    function zoom(mapPx, worldPx, fraction) {
        return Math.floor(Math.log(mapPx / worldPx / fraction) / Math.LN2);
    }

    var ne = bounds.getNorthEast();
    var sw = bounds.getSouthWest();

    var latFraction = (latRad(ne.lat()) - latRad(sw.lat())) / Math.PI;

    var lngDiff = ne.lng() - sw.lng();
    var lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;

    var latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction);
    var lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction);

    return Math.min(latZoom, lngZoom, ZOOM_MAX);
}

Demo on jsfiddle

Parameters:

The "bounds" parameter value should be a google.maps.LatLngBounds object.

The "mapDim" parameter value should be an object with "height" and "width" properties that represent the height and width of the DOM element that displays the map. You may want to decrease these values if you want to ensure padding. That is, you may not want map markers within the bounds to be too close to the edge of the map.

If you are using the jQuery library, the mapDim value can be obtained as follows:

var $mapDiv = $('#mapElementId');
var mapDim = { height: $mapDiv.height(), width: $mapDiv.width() };

If you are using the Prototype library, the mapDim value can be obtained as follows:

var mapDim = $('mapElementId').getDimensions();

Return Value:

The return value is the maximum zoom level that will still display the entire bounds. This value will be between 0 and the maximum zoom level, inclusive.

The maximum zoom level is 21. (I believe it was only 19 for Google Maps API v2.)


Explanation:

Google Maps uses a Mercator projection. In a Mercator projection the lines of longitude are equally spaced, but the lines of latitude are not. The distance between lines of latitude increase as they go from the equator to the poles. In fact the distance tends towards infinity as it reaches the poles. A Google Maps map, however, does not show latitudes above approximately 85 degrees North or below approximately -85 degrees South. (reference) (I calculate the actual cutoff at +/-85.05112877980658 degrees.)

This makes the calculation of the fractions for the bounds more complicated for latitude than for longitude. I used a formula from Wikipedia to calculate the latitude fraction. I am assuming this matches the projection used by Google Maps. After all, the Google Maps documentation page I link to above contains a link to the same Wikipedia page.

Other Notes:

  1. Zoom levels range from 0 to the maximum zoom level. Zoom level 0 is the map fully zoomed out. Higher levels zoom the map in further. (reference)
  2. At zoom level 0 the entire world can be displayed in an area that is 256 x 256 pixels. (reference)
  3. For each higher zoom level the number of pixels needed to display the same area doubles in both width and height. (reference)
  4. Maps wrap in the longitudinal direction, but not in the latitudinal direction.

What is the difference between x86 and x64

"When programming with C# you don’t usually need to worry about the underlying target platform. There are however a few cases when the Application and OS architecture can affect program logic, change functionality and cause unexpected exceptions."

"It is common misconception that selecting a specific target will result in the compiler generating platform specific code. This is not the case and instead it simply sets a flag in the assembly’s CLR header. This information can be easily extracted, and modified, using Microsoft’s CoreFlags tool"

https://medium.com/@trapdoorlabs/c-target-platforms-x64-vs-x86-vs-anycpu-5f0c3be6c9e2

How can I validate google reCAPTCHA v2 using javascript/jQuery?

_x000D_
_x000D_
if (typeof grecaptcha !== 'undefined' && $("#dvCaptcha").length > 0 && $("#dvCaptcha").html() == "") {_x000D_
                dvcontainer = grecaptcha.render('dvCaptcha', {_x000D_
                    'sitekey': ReCaptchSiteKey,_x000D_
                    'expired-callback' :function (response){_x000D_
                        recaptch.reset();_x000D_
                        c_responce = null;_x000D_
                    },_x000D_
                    'callback': function (response) {_x000D_
                        $("[id*=txtCaptcha]").val(c_responce);_x000D_
                        $("[id*=rfvCaptcha]").hide();_x000D_
                        c_responce = response;_x000D_
_x000D_
                    }_x000D_
                });_x000D_
            }_x000D_
            _x000D_
            function callonanybuttonClick(){_x000D_
             _x000D_
                if (c_responce == null) {_x000D_
                    $("[id*=txtCaptcha]").val("");_x000D_
                    $("[id*=rfvCaptcha]").show();_x000D_
_x000D_
                    return false;_x000D_
                }_x000D_
                else {_x000D_
                    $("[id*=txtCaptcha]").val(c_responce);_x000D_
                    $("[id*=rfvCaptcha]").hide();_x000D_
                    return true;_x000D_
                }_x000D_
            _x000D_
}
_x000D_
<div id="dvCaptcha" class="captchdiv"></div>_x000D_
    <asp:TextBox ID="txtCaptcha" runat="server" Style="display: none" />_x000D_
    <label id="rfvCaptcha" style="color:red;display:none;font-weight:normal;">Captcha validation is required.</label>
_x000D_
_x000D_
_x000D_

Captcha validation is required.

compareTo with primitives -> Integer / int

If you need just logical value (as it almost always is), the following one-liner will help you:

boolean ifIntsEqual = !((Math.max(a,b) - Math.min(a, b)) > 0);

And it works even in Java 1.5+, maybe even in 1.1 (i don't have one). Please tell us, if you can test it in 1.5-.

This one will do too:

boolean ifIntsEqual = !((Math.abs(a-b)) > 0);

force css grid container to fill full screen of device

You can add position: fixed; with top left right bottom 0 attribute, that solution work on older browsers too.

If you want to embed it, add position: absolute; to the wrapper, and position: relative to the div outside of the wrapper.

_x000D_
_x000D_
.wrapper {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
_x000D_
  display: grid;_x000D_
  border-style: solid;_x000D_
  border-color: red;_x000D_
  grid-template-columns: repeat(3, 1fr);_x000D_
  grid-template-rows: repeat(3, 1fr);_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
.one {_x000D_
  border-style: solid;_x000D_
  border-color: blue;_x000D_
  grid-column: 1 / 3;_x000D_
  grid-row: 1;_x000D_
}_x000D_
.two {_x000D_
  border-style: solid;_x000D_
  border-color: yellow;_x000D_
  grid-column: 2 / 4;_x000D_
  grid-row: 1 / 3;_x000D_
}_x000D_
.three {_x000D_
  border-style: solid;_x000D_
  border-color: violet;_x000D_
  grid-row: 2 / 5;_x000D_
  grid-column: 1;_x000D_
}_x000D_
.four {_x000D_
  border-style: solid;_x000D_
  border-color: aqua;_x000D_
  grid-column: 3;_x000D_
  grid-row: 3;_x000D_
}_x000D_
.five {_x000D_
  border-style: solid;_x000D_
  border-color: green;_x000D_
  grid-column: 2;_x000D_
  grid-row: 4;_x000D_
}_x000D_
.six {_x000D_
  border-style: solid;_x000D_
  border-color: purple;_x000D_
  grid-column: 3;_x000D_
  grid-row: 4;_x000D_
}
_x000D_
<html>_x000D_
<div class="wrapper">_x000D_
  <div class="one">One</div>_x000D_
  <div class="two">Two</div>_x000D_
  <div class="three">Three</div>_x000D_
  <div class="four">Four</div>_x000D_
  <div class="five">Five</div>_x000D_
  <div class="six">Six</div>_x000D_
</div>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What is a NoReverseMatch error, and how do I fix it?

And make sure your route in the list of routes:

./manage.py show_urls | grep path_or_name

https://github.com/django-extensions/django-extensions

How do you update Xcode on OSX to the latest version?

In my case (Xcode 6.1, iOS 8.2) I did not see the update in AppStore. I found Xcode 6.2 for download and pressed "Install". Then, it installed and asked for the update (more than 2 Gb). Xcode 6.2 works correctly with iOS 8.2 and iOS 8.1.2

Hopefully this tip will help somebody else...

What should my Objective-C singleton look like?

Since Kendall posted a threadsafe singleton that attempts to avoid locking costs, I thought I would toss one up as well:

#import <libkern/OSAtomic.h>

static void * volatile sharedInstance = nil;                                                

+ (className *) sharedInstance {                                                                    
  while (!sharedInstance) {                                                                          
    className *temp = [[self alloc] init];                                                                 
    if(!OSAtomicCompareAndSwapPtrBarrier(0x0, temp, &sharedInstance)) {
      [temp release];                                                                                   
    }                                                                                                    
  }                                                                                                        
  return sharedInstance;                                                                        
}

Okay, let me explain how this works:

  1. Fast case: In normal execution sharedInstance has already been set, so the while loop is never executed and the function returns after simply testing for the variable's existence;

  2. Slow case: If sharedInstance doesn't exist, then an instance is allocated and copied into it using a Compare And Swap ('CAS');

  3. Contended case: If two threads both attempt to call sharedInstance at the same time AND sharedInstance doesn't exist at the same time then they will both initialize new instances of the singleton and attempt to CAS it into position. Whichever one wins the CAS returns immediately, whichever one loses releases the instance it just allocated and returns the (now set) sharedInstance. The single OSAtomicCompareAndSwapPtrBarrier acts as both a write barrier for the setting thread and a read barrier from the testing thread.

How to read Data from Excel sheet in selenium webdriver

i have used following method to use input data from excel sheet: Need to import following as well

import jxl.Workbook;

then

Workbook wBook = Workbook.getWorkbook(new File("E:\\Testdata\\ShellData.xls"));
//get sheet
jxl.Sheet Sheet = wBook.getSheet(0); 
//Now in application i have given my Username and Password input in following way
driver.findElement(By.xpath("//input[@id='UserName']")).sendKeys(Sheet.getCell(0, i).getContents());
driver.findElement(By.xpath("//input[@id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
driver.findElement(By.xpath("//input[@name='Login']")).click();

it will Work

ActiveMQ connection refused

Your application is not able to connect to activemq. Check that your activemq is running and listening on localhost 61616.

You can try using: netstat -a to check if the activemq process has started. Or try check if you can access your actvemq using admin page: localhost:8161/admin/queues.jsp

On mac you will start your activemq using:

$ACTMQ_HOME/bin/activemq start 

Or if your config file (activemq.xml ) if located in another location you can use:

$ACTMQ_HOME/bin/activemq start xbean:file:${location_of_your_config_file}

In your case the executable is under: bin/macosx/activemq so you need to use: $ACTMQ_HOME/bin/macosx/activemq start

How to destroy JWT Tokens on logout?

You cannot manually expire a token after it has been created. Thus, you cannot log out with JWT on the server-side as you do with sessions.

JWT is stateless, meaning that you should store everything you need in the payload and skip performing a DB query on every request. But if you plan to have a strict log out functionality, that cannot wait for the token auto-expiration, even though you have cleaned the token from the client-side, then you might need to neglect the stateless logic and do some queries. so what's a solution?

  • Set a reasonable expiration time on tokens

  • Delete the stored token from client-side upon log out

  • Query provided token against The Blacklist on every authorized request

Blacklist

“Blacklist” of all the tokens that are valid no more and have not expired yet. You can use a DB that has a TTL option on documents which would be set to the amount of time left until the token is expired.

Redis

Redis is a good option for blacklist, which will allow fast in-memory access to the list. Then, in the middleware of some kind that runs on every authorized request, you should check if the provided token is in The Blacklist. If it is you should throw an unauthorized error. And if it is not, let it go and the JWT verification will handle it and identify if it is expired or still active.

For more information, see How to log out when using JWT. by Arpy Vanyan

How to use struct timeval to get the execution time?

Change:

struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
                                          delcare a variable with
                                          no name. */

to:

struct timeval tvalBefore, tvalAfter;

It is less likely (IMO) to make this mistake if there is a single declaration per line:

struct timeval tvalBefore;
struct timeval tvalAfter;

It becomes more error prone when declaring pointers to types on a single line:

struct timeval* tvalBefore, tvalAfter;

tvalBefore is a struct timeval* but tvalAfter is a struct timeval.

How do I start Mongo DB from Windows?

Clearly many people have answered upon your query of how to make mongoDb work, I'd answer the second part: Regarding an appropriate GUI for mongoDB

My suggestion is, go for MongoChef (now Studio 3T)

You can easily install and use it.

You might want want to refer to (from 03:10- to 08:50): https://www.youtube.com/watch?v=0ws3oIyqieY&index=2&list=PLS1QulWo1RIZtR6bncmSaH8fB81oRl6MP

For a step by step guide to the GUI tool.

How can we convert an integer to string in AngularJs

.toString() is available, or just add "" to the end of the int

var x = 3,
    toString = x.toString(),
    toConcat = x + "";

Angular is simply JavaScript at the core.