Programs & Examples On #Gmail

Gmail is a free email service offered by Google. ONLY use this tag for PROGRAMMING questions related to Gmail's APIs. General Gmail usage questions belong at https://webapps.stackexchange.com/questions/tagged/gmail

Sending email through Gmail SMTP server with C#

Dim SMTPClientObj As New Net.Mail.SmtpClient
SMTPClientObj.UseDefaultCredentials = False
SMTPClientObj.Credentials = New System.Net.NetworkCredential("[email protected]", "mypwd")
SMTPClientObj.Host = "smtp.gmail.com"
SMTPClientObj.Port = 587
SMTPClientObj.EnableSsl = True
SMTPClientObj.Send("[email protected]","[email protected]","test","testbody")

If you get an error like "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at" as I get before this, make sure the line SMTPClientObj.UseDefaultCredentials = False included and this line should before the SMTPClientObj.Credentials.

I did try to switch these 2 lines the opposite way and the 5.5.1 Authentication Required error returned.

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

Maybe useful for anyone else running into this issue: When setting the port on the properties:

props.put("mail.smtp.port", smtpPort);

..make sure to use a string object. Using a numeric (ie Long) object will cause this statement to seemingly have no effect.

HTML image not showing in Gmail

Google only allows images which are coming from trusted source .

So I solved this issue by hosting my images in google drive and using its url as source for my images.

Example: with: http://drive.google.com/uc?export=view&id=FILEID'>

to form URL please refer here.

How to to send mail using gmail in Laravel?

you need to enable first the App password of your google account -> security section link

then the app password that will be generated copy it and paste it in to .env file

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=app_password
MAIL_ENCRYPTION=ssl

How to configure WAMP (localhost) to send email using Gmail?

It's quite simple. (Adapt syntax for your convenience)

public $smtp = array(
    'transport' => 'Smtp',
    'from' => '[email protected]',
    'host' => 'ssl://smtp.gmail.com',
    'port' => 465,
    'timeout' => 30,
    'username' => '[email protected]',
    'password' => '*****'
)

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

You need to tell it that you are using SSL:

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

In case you miss anything, here is working code:

String  d_email = "[email protected]",
            d_uname = "Name",
            d_password = "urpassword",
            d_host = "smtp.gmail.com",
            d_port  = "465",
            m_to = "[email protected]",
            m_subject = "Indoors Readable File: " + params[0].getName(),
            m_text = "This message is from Indoor Positioning App. Required file(s) are attached.";
    Properties props = new Properties();
    props.put("mail.smtp.user", d_email);
    props.put("mail.smtp.host", d_host);
    props.put("mail.smtp.port", d_port);
    props.put("mail.smtp.starttls.enable","true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", d_port);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SMTPAuthenticator auth = new SMTPAuthenticator();
    Session session = Session.getInstance(props, auth);
    session.setDebug(true);

    MimeMessage msg = new MimeMessage(session);
    try {
        msg.setSubject(m_subject);
        msg.setFrom(new InternetAddress(d_email));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));

Transport transport = session.getTransport("smtps");
            transport.connect(d_host, Integer.valueOf(d_port), d_uname, d_password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();

        } catch (AddressException e) {
            e.printStackTrace();
            return false;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

This is my .env mail settings

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=hello27
MAIL_ENCRYPTION=tls

i was getting thesame error as stated in the question but by using

php artisan config:cache

Everything worked fine

How to encode the plus (+) symbol in a URL

It's safer to always percent-encode all characters except those defined as "unreserved" in RFC-3986.

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

So, percent-encode the plus character and other special characters.

The problem that you are having with pluses is because, according to RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1., "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped"). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.

How to send email using simple SMTP commands via Gmail?

to send over gmail, you need to use an encrypted connection. this is not possible with telnet alone, but you can use tools like openssl

either connect using the starttls option in openssl to convert the plain connection to encrypted...

openssl s_client -starttls smtp -connect smtp.gmail.com:587 -crlf -ign_eof

or connect to a ssl sockect directly...

openssl s_client -connect smtp.gmail.com:465 -crlf -ign_eof

EHLO localhost

after that, authenticate to the server using the base64 encoded username/password

AUTH PLAIN AG15ZW1haWxAZ21haWwuY29tAG15cGFzc3dvcmQ=

to get this from the commandline:

echo -ne '\[email protected]\00password' | base64
AHVzZXJAZ21haWwuY29tAHBhc3N3b3Jk

then continue with "mail from:" like in your example

example session:

openssl s_client -connect smtp.gmail.com:465 -crlf -ign_eof
[... lots of openssl output ...]
220 mx.google.com ESMTP m46sm11546481eeh.9
EHLO localhost
250-mx.google.com at your service, [1.2.3.4]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH
250 ENHANCEDSTATUSCODES
AUTH PLAIN AG5pY2UudHJ5QGdtYWlsLmNvbQBub2l0c25vdG15cGFzc3dvcmQ=
235 2.7.0 Accepted
MAIL FROM: <[email protected]>
250 2.1.0 OK m46sm11546481eeh.9
rcpt to: <[email protected]>
250 2.1.5 OK m46sm11546481eeh.9
DATA
354  Go ahead m46sm11546481eeh.9
Subject: it works

yay!
.
250 2.0.0 OK 1339757532 m46sm11546481eeh.9
quit
221 2.0.0 closing connection m46sm11546481eeh.9
read:errno=0

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "[email protected]";
$mail->Password = "password";
$mail->SetFrom("[email protected]");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("[email protected]");

 if(!$mail->Send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
 } else {
    echo "Message has been sent";
 }

This code above has been tested and worked for me.

It could be that you needed $mail->SMTPSecure = 'ssl';

Also make sure you don't have two step verification switched on for that account as that can cause problems also.

UPDATED

You could try changing $mail->SMTP to:

$mail->SMTPSecure = 'tls';

It's worth noting that some SMTP servers block connections. Some SMTP servers don't support SSL (or TLS) connections.

Connecting to smtp.gmail.com via command line

Using Linux or OSx, do what Sorin recommended but use port 465 instead. 25 is the generic SMTP port, but not what GMail uses. Also, I don't believe you want to use -starttls smtp

openssl s_client -connect smtp.gmail.com:465

You should get lots of information on the SSL session and the response:

220 mx.google.com ...

Type in

HELO smtp.gmail.com 

and you'll receive:

250 mx.google.com at your service

From there it is not quite as straightforward as just sending SMTP messages because Gmail has protections in place to ensure you only send emails appearing to be from accounts that actually belong to you. Instead of typing in "Helo", use "Ehlo". I don't know much about SMTP so I cannot explain the difference, and don't have time to research much. Perhaps someone with more knowledge can explain.

Then, type "auth login" and you will receive the following:

334 VXNlcm5hbWU6

This is essentially the word "Username" encoded in Base 64. Using a Base 64 encoder such as this one, encode your user name and enter it. Do the same for your password, which is requested next. You should see:

235 2.7.0 Accepted

And that's it, you're logged in.

There is one more oddity to overcome if you're using OSx or Linux terminals. Just pressing the "ENTER" key does not apparently result in a CRLF which SMTP needs to end a message. You have to use "CTRL+V+ENTER". So, this should look like the following:

^M
.^M
250 2.0.0 OK

Sending email in .NET through Gmail

The above answer doesn't work. You have to set DeliveryMethod = SmtpDeliveryMethod.Network or it will come back with a "client was not authenticated" error. Also it's always a good idea to put a timeout.

Revised code:

using System.Net.Mail;
using System.Net;

var fromAddress = new MailAddress("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "To Name");
const string fromPassword = "password";
const string subject = "test";
const string body = "Hey now!!";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
    Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

Send email from localhost running XAMMP in PHP using GMAIL mail server

Here's the link that gives me the answer:

[Install] the "fake sendmail for windows". If you are not using XAMPP you can download it here: http://glob.com.au/sendmail/sendmail.zip

[Modify] the php.ini file to use it (commented out the other lines):

[mail function]
; For Win32 only.
; SMTP = smtp.gmail.com
; smtp_port = 25

; For Win32 only.
; sendmail_from = <e-mail username>@gmail.com

; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(ignore the "Unix only" bit, since we actually are using sendmail)

You then have to configure the "sendmail.ini" file in the directory where sendmail was installed:

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=<username>
auth_password=<password>
force_sender=<e-mail username>@gmail.com

To access a Gmail account protected by 2-factor verification, you will need to create an application-specific password. (source)

The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp

If you get the error "Unrecognized attribute 'enableSsl'" when following the advice to add that parameter to your web.config. I found that I was able to workaround the error by adding it to my code file instead in this format:

SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;

try
{
    smtp.Send(mm);
}
catch (Exception ex)
{
    MsgBox("Message not emailed: " + ex.ToString());
}

This is the system.net section of my web.config:

<system.net>
  <mailSettings>
    <smtp from="<from_email>">
      <network host="smtp.gmail.com"
       port="587"
       userName="<your_email>"
       password="<your_app_password>" />
    </smtp>
  </mailSettings>
</system.net>

How to send an email with Gmail as provider using Python?

You can find it here: http://jayrambhia.com/blog/send-emails-using-python

smtp_host = 'smtp.gmail.com'
smtp_port = 587
server = smtplib.SMTP()
server.connect(smtp_host,smtp_port)
server.ehlo()
server.starttls()
server.login(user,passw)
fromaddr = raw_input('Send mail by the name of: ')
tolist = raw_input('To: ').split()
sub = raw_input('Subject: ')

msg = email.MIMEMultipart.MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = email.Utils.COMMASPACE.join(tolist)
msg['Subject'] = sub  
msg.attach(MIMEText(raw_input('Body: ')))
msg.attach(MIMEText('\nsent via python', 'plain'))
server.sendmail(user,tolist,msg.as_string())

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

Turn On "Access for less secure apps" in Security setting for the gmail account.(from mail), see the below link for references

http://www.ghacks.net/2014/07/21/gmail-starts-block-less-secure-apps-enable-access/

Sending mail attachment using Java

Working code, I have used Java Mail 1.4.7 jar

import java.util.Properties;
import javax.activation.*;
import javax.mail.*;

public class MailProjectClass {

public static void main(String[] args) {

    final String username = "[email protected]";
    final String password = "your.password";

    Properties props = new Properties();
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("[email protected]"));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("[email protected]"));
        message.setSubject("Testing Subject");
        message.setText("PFA");

        MimeBodyPart messageBodyPart = new MimeBodyPart();

        Multipart multipart = new MimeMultipart();
        
        String file = "path of file to be attached";
        String fileName = "attachmentName";
        DataSource source = new FileDataSource(file);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(fileName);
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        System.out.println("Sending");

        Transport.send(message);

        System.out.println("Done");

    } catch (MessagingException e) {
        e.printStackTrace();
    }
  }
}

Send mail via Gmail with PowerShell V2's Send-MailMessage

On a Windows 8.1 machine I got Send-MailMessage to send an email with an attachment through Gmail using the following script:

$EmFrom = "[email protected]"
$username = "[email protected]"
$pwd = "YOURPASSWORD"
$EmTo = "[email protected]"
$Server = "smtp.gmail.com"
$port = 587
$Subj = "Test"
$Bod = "Test 123"
$Att = "c:\Filename.FileType"
$securepwd = ConvertTo-SecureString $pwd -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $securepwd
Send-MailMessage -To $EmTo -From $EmFrom -Body $Bod -Subject $Subj -Attachments $Att -SmtpServer $Server -port $port -UseSsl  -Credential $cred

Styling HTML email for Gmail

As others have said, some email programs will not read the css styles. If you already have a web email written up you can use the following tool from zurb to inline all of your styles:

http://zurb.com/ink/inliner.php

This comes in extremely handy when using templates like those mentioned above from mailchimp, campaign monitor, etc. as they, as you have found, will not work in some email programs. This tool leaves your style section for the mail programs that will read it and puts all the styles inline to get more universal readability in the format that you wanted.

URL to compose a message in Gmail (with full Gmail interface and specified to, bcc, subject, etc.)

Many others have done an excellent job here giving a basic answer, especially Tobias Mühl. As mentioned, GMail's Api very closely matches the definition given by RFC2368 and RFC6068. This is true of the extended form of the mailto: links, but it's also true in the commonly-used forms found in the other answers. Of the five parameters, four are identical (such as to, cc, bcc and body) and one received only slight modification (su is gmail's version of subject).

If you want to know more about what you can do with mailTo gmail URLs, then these RFCs might be of help. Unfortunately, Google has not published any source themselves.

To clarify the parameters:

  • to - Email to who
  • su (gmail API) / subject (mailTo API) - Email Title
  • body - Email Body
  • bcc - Email Blind-Carbon Copy
  • cc - Email Carbon Copy address

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

//set CLASSPATH=%CLASSPATH%;activation.jar;mail.jar
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class Mail
{
    String  d_email = "[email protected]",
            d_password = "****",
            d_host = "smtp.gmail.com",
            d_port  = "465",
            m_to = "[email protected]",
            m_subject = "Testing",
            m_text = "Hey, this is the testing email using smtp.gmail.com.";
    public static void main(String[] args)
    {
        String[] to={"[email protected]"};
        String[] cc={"[email protected]"};
        String[] bcc={"[email protected]"};
        //This is for google
        Mail.sendMail("[email protected]", "password", "smtp.gmail.com", 
                      "465", "true", "true", 
                      true, "javax.net.ssl.SSLSocketFactory", "false", 
                      to, cc, bcc, 
                      "hi baba don't send virus mails..", 
                      "This is my style...of reply..If u send virus mails..");
    }

    public synchronized static boolean sendMail(
        String userName, String passWord, String host, 
        String port, String starttls, String auth, 
        boolean debug, String socketFactoryClass, String fallback, 
        String[] to, String[] cc, String[] bcc, 
        String subject, String text) 
    {
        Properties props = new Properties();
        //Properties props=System.getProperties();
        props.put("mail.smtp.user", userName);
        props.put("mail.smtp.host", host);
        if(!"".equals(port))
            props.put("mail.smtp.port", port);
        if(!"".equals(starttls))
            props.put("mail.smtp.starttls.enable",starttls);
        props.put("mail.smtp.auth", auth);
        if(debug) {
            props.put("mail.smtp.debug", "true");
        } else {
            props.put("mail.smtp.debug", "false");         
        }
        if(!"".equals(port))
            props.put("mail.smtp.socketFactory.port", port);
        if(!"".equals(socketFactoryClass))
            props.put("mail.smtp.socketFactory.class",socketFactoryClass);
        if(!"".equals(fallback))
            props.put("mail.smtp.socketFactory.fallback", fallback);

        try
        {
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);
            MimeMessage msg = new MimeMessage(session);
            msg.setText(text);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress("[email protected]"));
            for(int i=0;i<to.length;i++) {
                msg.addRecipient(Message.RecipientType.TO, 
                                 new InternetAddress(to[i]));
            }
            for(int i=0;i<cc.length;i++) {
                msg.addRecipient(Message.RecipientType.CC, 
                                 new InternetAddress(cc[i]));
            }
            for(int i=0;i<bcc.length;i++) {
                msg.addRecipient(Message.RecipientType.BCC, 
                                 new InternetAddress(bcc[i]));
            }
            msg.saveChanges();
            Transport transport = session.getTransport("smtp");
            transport.connect(host, userName, passWord);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
            return true;
        }
        catch (Exception mex)
        {
            mex.printStackTrace();
            return false;
        }
    }

}

Javamail Could not convert socket to TLS GMail

After a full day of search, I disabled Avast for 10 minutes and Windows Firewall (important) and everything started working!

This was my error:

Mail server connection failed; nested exception is javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target. Failed messages: javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target  

Here is how to fix the issue in Avast 19.8.2393 by adding an exclusion to SMTP port 587 (or whichever port your application uses):

  1. Open Avast

  2. Click on 'Settings'

  3. Click on 'Troubleshooting' and then 'Open old settings'

enter image description here

  1. Click again on 'Troubleshooting', scroll down to 'Redirect settings' and delete the port that your app uses.

enter image description here

In my case, I just removed 587 from SMTP ports.

Now I am able to use Avast and also have my Windows Firewall switched on (no need to add additional exclusion for the Firewall).

Here are my application.properties e-mail properties:

###### I am using a Google App Password which I generated in my Gmail Security settings ######
spring.mail.host = smtp.gmail.com
spring.mail.port = 587
spring.mail.protocol = smtp
spring.mail.username = gmail account
spring.mail.password = password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000

Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

Hi I had the same issue,

what I've done to solve it. is to turn on the less secure app. after connecting to my gmail account. I entered this link: https://www.google.com/settings/security/lesssecureapps

Then I turn on the secure app and, and the it worked. it has been said also above

Send email using the GMail SMTP server from a PHP page

Using Swift mailer, it is quite easy to send a mail through Gmail credentials:

<?php
require_once 'swift/lib/swift_required.php';

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
  ->setUsername('GMAIL_USERNAME')
  ->setPassword('GMAIL_PASSWORD');

$mailer = Swift_Mailer::newInstance($transport);

$message = Swift_Message::newInstance('Test Subject')
  ->setFrom(array('[email protected]' => 'ABC'))
  ->setTo(array('[email protected]'))
  ->setBody('This is a test mail.');

$result = $mailer->send($message);
?>

How to create Gmail filter searching for text only at start of subject line?

The only option I have found to do this is find some exact wording and put that under the "Has the words" option. Its not the best option, but it works.

Gmail: 530 5.5.1 Authentication Required. Learn more at

Derp! I signed into the account and there was a "Suspicious login attempt" warning message at the top of the page. After clicking the warning and authorizing the access, everything works.

how to implement Interfaces in C++?

There is no concept of interface in C++,
You can simulate the behavior using an Abstract class.
Abstract class is a class which has atleast one pure virtual function, One cannot create any instances of an abstract class but You could create pointers and references to it. Also each class inheriting from the abstract class must implement the pure virtual functions in order that it's instances can be created.

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

There are some third-party Java libraries that provide string join method, but you probably don't want to start using a library just for something simple like that. I would just create a helper method like this, which I think is a bit better than your version, It uses StringBuffer, which will be more efficient if you need to join many strings, and it works on a collection of any type.

public static <T> String join(Collection<T> values)
{
    StringBuffer ret = new StringBuffer();
    for (T value : values)
    {
        if (ret.length() > 0) ret.append(",");
        ret.append(value);
    }
    return ret.toString();
}

Another suggestion with using Collection.toString() is shorter, but that relies on Collection.toString() returning a string in a very specific format, which I would personally not want to rely on.

How to decompile an APK or DEX file on Android platform?

I have created a tool that combines dex2jar, jd-core and apktool: https://github.com/dirkvranckaert/AndroidDecompiler Just checkout the project locally and run the script as documented and you'll get all the resources and sources decompiled.

LINQ to SQL using GROUP BY and COUNT(DISTINCT)

I wouldn't bother doing it in Linq2SQL. Create a stored Procedure for the query you want and understand and then create the object to the stored procedure in the framework or just connect direct to it.

Python function to convert seconds into minutes, hours, and days

#1 min = 60
#1 hour = 60 * 60 = 3600
#1 day = 60 * 60 * 24 = 86400

    x=input('enter a positive integer: ')

    t=int(x)

    day= t//86400
    hour= (t-(day*86400))//3600
    minit= (t - ((day*86400) + (hour*3600)))//60
    seconds= t - ((day*86400) + (hour*3600) + (minit*60))
    print( day, 'days' , hour,' hours', minit, 'minutes',seconds,' seconds')

Copy directory contents into a directory with python

The python libs are obsolete with this function. I've done one that works correctly:

import os
import shutil

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)

    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')

How to add leading zeros for for-loop in shell?

why not printf '%02d' $num? See help printf for this internal bash command.

How may I sort a list alphabetically using jQuery?

I was looking to do this myself, and I wasnt satisfied with any of the answers provided simply because, I believe, they are quadratic time, and I need to do this on lists hundreds of items long.

I ended up extending jquery, and my solution uses jquery, but could easily be modified to use straight javascript.

I only access each item twice, and perform one linearithmic sort, so this should, I think, work out to be a lot faster on large datasets, though I freely confess I could be mistaken there:

sortList: function() {
   if (!this.is("ul") || !this.length)
      return
   else {
      var getData = function(ul) {
         var lis     = ul.find('li'),
             liData  = {
               liTexts : []
            }; 

         for(var i = 0; i<lis.length; i++){
             var key              = $(lis[i]).text().trim().toLowerCase().replace(/\s/g, ""),
             attrs                = lis[i].attributes;
             liData[key]          = {},
             liData[key]['attrs'] = {},
             liData[key]['html']  = $(lis[i]).html();

             liData.liTexts.push(key);

             for (var j = 0; j < attrs.length; j++) {
                liData[key]['attrs'][attrs[j].nodeName] = attrs[j].nodeValue;
             }
          }

          return liData;
       },

       processData = function (obj){
          var sortedTexts = obj.liTexts.sort(),
              htmlStr     = '';

          for(var i = 0; i < sortedTexts.length; i++){
             var attrsStr   = '',
                 attributes = obj[sortedTexts[i]].attrs;

             for(attr in attributes){
                var str = attr + "=\'" + attributes[attr] + "\' ";
                attrsStr += str;
             }

             htmlStr += "<li "+ attrsStr + ">" + obj[sortedTexts[i]].html+"</li>";
          }

          return htmlStr;

       };

       this.html(processData(getData(this)));
    }
}

Using jQuery to build table rows from AJAX response(json)

Data as JSON:

data = [
       {
       "rank":"9",
       "content":"Alon",
       "UID":"5"
       },
       {
       "rank":"6",
       "content":"Tala",
       "UID":"6"
       }
       ]

You can use jQuery to iterate over JSON and create tables dynamically:

num_rows = data.length;
num_cols = size_of_array(data[0]);

table_id = 'my_table';
table = $("<table id=" + table_id + "></table>");

header = $("<tr class='table_header'></tr>");
$.each(Object.keys(data[0]), function(ind_header, val_header) {
col = $("<td>" + val_header + "</td>");
header.append(col);
})
table.append(header);

$.each(data, function(ind_row, val) {
row = $("<tr></tr>");
$.each(val, function(ind_cell, val_cell) {
col = $("<td>" + val_cell + "</td>");
row.append(col);
})
table.append(row);
})

Here is the size_of_array function:

function size_of_array(obj) {
    size = Object.keys(obj).length;
    return(size)
    };

You can also add styling if needed:

$('.' + content['this_class']).children('canvas').remove();
$('.' + content['this_class']).append(table);
$('#' + table_id).css('width', '100%').css('border', '1px solid black').css('text-align', 'center').css('border-collapse', 'collapse');
$('#' + table_id + ' td').css('border', '1px solid black');

Result:

enter image description here

Removing MySQL 5.7 Completely

First of all, do a backup of your needed databases with mysqldump

Note: If you want to restore later, just backup your relevant databases, and not the WHOLE, because the whole database might actually be the reason you need to purge and reinstall).

In total, do this:

sudo service mysql stop  #or mysqld
sudo killall -9 mysql
sudo killall -9 mysqld
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo deluser -f mysql
sudo rm -rf /var/lib/mysql
sudo apt-get purge mysql-server-core-5.7
sudo apt-get purge mysql-client-core-5.7
sudo rm -rf /var/log/mysql
sudo rm -rf /etc/mysql

All above commands in single line (just copy and paste):

sudo service mysql stop && sudo killall -9 mysql && sudo killall -9 mysqld && sudo apt-get remove --purge mysql-server mysql-client mysql-common && sudo apt-get autoremove && sudo apt-get autoclean && sudo deluser mysql && sudo rm -rf /var/lib/mysql && sudo apt-get purge mysql-server-core-5.7 && sudo apt-get purge mysql-client-core-5.7 && sudo rm -rf /var/log/mysql && sudo rm -rf /etc/mysql

ListView with Add and Delete Buttons in each Row in android

on delete button click event

public void delete(View v){                

    ListView listview1;
    ArrayList<E> datalist;

    final int position = listview1.getPositionForView((View) v.getParent());
    datalist.remove(position);
    myAdapter.notifyDataSetChanged();

}

Visual Studio 2015 is very slow

Update PC Drivers

In my case, and I had bad lag doing the simplest of things, it helped to update my pc drivers. The system drivers are the foundation for everything.

I was fortunate that I have Dell and they have awesome website support to do this. I googled

dell <my model name> update drivers

or go to the drivers home page

I let it update all the drivers it wanted to (Dell driver update is pretty much automatic).

Much of the lag seems to have gone away.

How to iterate over rows in a DataFrame in Pandas

The easiest way, use the apply function

def print_row(row):
   print row['c1'], row['c2']

df.apply(lambda row: print_row(row), axis=1)

Show data on mouseover of circle

This concise example demonstrates common way how to create custom tooltip in d3.

_x000D_
_x000D_
var w = 500;_x000D_
var h = 150;_x000D_
_x000D_
var dataset = [5, 10, 15, 20, 25];_x000D_
_x000D_
// firstly we create div element that we can use as_x000D_
// tooltip container, it have absolute position and_x000D_
// visibility: hidden by default_x000D_
_x000D_
var tooltip = d3.select("body")_x000D_
  .append("div")_x000D_
  .attr('class', 'tooltip');_x000D_
_x000D_
var svg = d3.select("body")_x000D_
  .append("svg")_x000D_
  .attr("width", w)_x000D_
  .attr("height", h);_x000D_
_x000D_
// here we add some circles on the page_x000D_
_x000D_
var circles = svg.selectAll("circle")_x000D_
  .data(dataset)_x000D_
  .enter()_x000D_
  .append("circle");_x000D_
_x000D_
circles.attr("cx", function(d, i) {_x000D_
    return (i * 50) + 25;_x000D_
  })_x000D_
  .attr("cy", h / 2)_x000D_
  .attr("r", function(d) {_x000D_
    return d;_x000D_
  })_x000D_
  _x000D_
  // we define "mouseover" handler, here we change tooltip_x000D_
  // visibility to "visible" and add appropriate test_x000D_
  _x000D_
  .on("mouseover", function(d) {_x000D_
    return tooltip.style("visibility", "visible").text('radius = ' + d);_x000D_
  })_x000D_
  _x000D_
  // we move tooltip during of "mousemove"_x000D_
  _x000D_
  .on("mousemove", function() {_x000D_
    return tooltip.style("top", (event.pageY - 30) + "px")_x000D_
      .style("left", event.pageX + "px");_x000D_
  })_x000D_
  _x000D_
  // we hide our tooltip on "mouseout"_x000D_
  _x000D_
  .on("mouseout", function() {_x000D_
    return tooltip.style("visibility", "hidden");_x000D_
  });
_x000D_
.tooltip {_x000D_
    position: absolute;_x000D_
    z-index: 10;_x000D_
    visibility: hidden;_x000D_
    background-color: lightblue;_x000D_
    text-align: center;_x000D_
    padding: 4px;_x000D_
    border-radius: 4px;_x000D_
    font-weight: bold;_x000D_
    color: orange;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

  • Copy all business_key values to a temporary table
  • Sort the temporary table
  • Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

  • Scan the full table, storing each value of business key in a hashtable
  • Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

Android Linear Layout - How to Keep Element At Bottom Of View?

Step 1 : Create two view inside a linear layout

Step 2 : First view must set to android:layout_weight="1"

Step 3 : Second view will automatically putted downwards

<LinearLayout
android:id="@+id/botton_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

    <View
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

    <Button
    android:id="@+id/btn_health_advice"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>


</LinearLayout>

Where to download Microsoft Visual c++ 2003 redistributable

Another way:

using Unofficial (Full Size: 26.1 MB) VC++ All in one that contained your needed files:

http://www.wincert.net/forum/topic/9790-aio-microsoft-visual-bcfj-redistributable-x86x64/

OR (Smallest 5.10 MB) Microsoft Visual Basic/C++ Runtimes 1.1.1 RePacked Here:

http://www.wincert.net/forum/topic/9794-bonus-microsoft-visual-basicc-runtimes-111/

Redirect stdout to a file in Python?

you can try this too much better

import sys

class Logger(object):
    def __init__(self, filename="Default.log"):
        self.terminal = sys.stdout
        self.log = open(filename, "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

sys.stdout = Logger("yourlogfilename.txt")
print "Hello world !" # this is should be saved in yourlogfilename.txt

Expansion of variables inside single quotes in a command in Bash

Variables can contain single quotes.

myvar=\'....$variable\'

repo forall -c $myvar

c# open a new form then close the current form?

I think this is much easier :)

    private void btnLogin_Click(object sender, EventArgs e)
    {
        //this.Hide();
        //var mm = new MainMenu();
        //mm.FormClosed += (s, args) => this.Close();
        //mm.Show();

        this.Hide();
        MainMenu mm = new MainMenu();
        mm.Show();

    }

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

In your tsconfig.json file set the parameter "noImplicitAny": false under compilerOptions to get rid of this error.

What is a regex to match ONLY an empty string?

Wow, ya'll are overthinking it. It's as simple as the following. Besides, many of those answers aren't understood by the RE2 dialect used by C and golang.

^$

Why Maven uses JDK 1.6 but my java -version is 1.7

You can also do,

<properties>
      ...  

      <!-- maven-compiler-plugin , aka JAVA Compiler 1.7 -->
      <maven.compiler.target>1.7</maven.compiler.target>
      <maven.compiler.source>1.7</maven.compiler.source>

      ...  
</properties>

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Also remember that they all encode different sets of characters, and select the one you need appropriately. encodeURI() encodes fewer characters than encodeURIComponent(), which encodes fewer (and also different, to dannyp's point) characters than escape().

Android ListView headers

You probably are looking for an ExpandableListView which has headers (groups) to separate items (childs).

Nice tutorial on the subject: here.

Adding a Button to a WPF DataGrid

First create a DataGridTemplateColumn to contain the button:

<DataGridTemplateColumn>
  <DataGridTemplateColumn.CellTemplate> 
    <DataTemplate> 
      <Button Click="ShowHideDetails">Details</Button> 
    </DataTemplate> 
  </DataGridTemplateColumn.CellTemplate> 
</DataGridTemplateColumn>

When the button is clicked, update the containing DataGridRow's DetailsVisibility:

void ShowHideDetails(object sender, RoutedEventArgs e)
{
    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
    if (vis is DataGridRow)
    {
        var row = (DataGridRow)vis;
        row.DetailsVisibility = 
        row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
        break;
    }
}

Type Checking: typeof, GetType, or is?

1.

Type t = typeof(obj1);
if (t == typeof(int))

This is illegal, because typeof only works on types, not on variables. I assume obj1 is a variable. So, in this way typeof is static, and does its work at compile time instead of runtime.

2.

if (obj1.GetType() == typeof(int))

This is true if obj1 is exactly of type int. If obj1 derives from int, the if condition will be false.

3.

if (obj1 is int)

This is true if obj1 is an int, or if it derives from a class called int, or if it implements an interface called int.

How can I decode HTML characters in C#?

For strings containing &#x20; I've had to double-decode the string. First decode would turn it into the second pass would correctly decode it to the expected character.

Predicate Delegates in C#

A predicate is a function that returns true or false. A predicate delegate is a reference to a predicate.

So basically a predicate delegate is a reference to a function that returns true or false. Predicates are very useful for filtering a list of values - here is an example.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list = new List<int> { 1, 2, 3 };

        Predicate<int> predicate = new Predicate<int>(greaterThanTwo);

        List<int> newList = list.FindAll(predicate);
    }

    static bool greaterThanTwo(int arg)
    {
        return arg > 2;
    }
}

Now if you are using C# 3 you can use a lambda to represent the predicate in a cleaner fashion:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list = new List<int> { 1, 2, 3 };

        List<int> newList = list.FindAll(i => i > 2);
    }
}

Create JPA EntityManager without persistence.xml configuration file

Yes you can without using any xml file using spring like this inside a @Configuration class (or its equivalent spring config xml):

@Bean
public LocalContainerEntityManagerFactoryBean emf(){
    properties.put("javax.persistence.jdbc.driver", dbDriverClassName);
    properties.put("javax.persistence.jdbc.url", dbConnectionURL);
    properties.put("javax.persistence.jdbc.user", dbUser); //if needed

    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setPersistenceProviderClass(org.eclipse.persistence.jpa.PersistenceProvider.class); //If your using eclipse or change it to whatever you're using
    emf.setPackagesToScan("com.yourpkg"); //The packages to search for Entities, line required to avoid looking into the persistence.xml
    emf.setPersistenceUnitName(SysConstants.SysConfigPU);
    emf.setJpaPropertyMap(properties);
    emf.setLoadTimeWeaver(new ReflectiveLoadTimeWeaver()); //required unless you know what your doing
    return emf;
}

C#: Assign same value to multiple variables in single statement

int num1, num2, num3;

num1 = num2 = num3 = 5;

Console.WriteLine(num1 + "=" + num2 + "=" + num3);    // 5=5=5

C++ - Hold the console window open?

How about std::cin.get(); ?

Also, if you're using Visual Studio, you can run without debugging (CTRL-F5 by default) and it won't close the console at the end. If you run it with debugging, you could always put a breakpoint at the closing brace of main().

Conda update failed: SSL error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

That SSL error is misleading. I am using Anaconda 3, conda version 4.6.11, have the most current version of openssl on a Windows 10 instance. I got the issue resolved by changing the security settings on the Anaconda3 folder to Full Control. Don't think this helped, but I also have modified the ..\Anaconda3\Lib\site-packages\certifi\cacert.pem file to include the company's SSL cert.

Hope this info helps you.

"Exception has been thrown by the target of an invocation" error (mscorlib)

I'd suggest checking for an inner exception. If there isn't one, check your logs for the exception that occurred immediately prior to this one.

This isn't a web-specific exception, I've also encountered it in desktop-app development. In short, what's happening is that the thread receiving this exception is running some asynchronous code (via Invoke(), e.g.) and that code that's being run asynchronously is exploding with an exception. This target invocation exception is the aftermath of that failure.

If you haven't already, place some sort of exception logging wrapper around the asynchronous callbacks that are being invoked when you trigger this error. Event handlers, for instance. That ought to help you track down the problem.

Good luck!

iOS Simulator to test website on Mac

You can use the iOS simulator to do this. You need to enable "Developer Mode" on Safari (Preferences -> Advanced).

Then open the website you want to debug in the iOS simulator. Go back to safari and under Develop you will see the simulator and the tabs open on safari.

If you want to test an actual device, then just plug it into your computer and it should show there too.

That's how I do it.

Read properties file outside JAR file

Here if you mention .getPath() then that will return the path of Jar and I guess you will need its parent to refer to all other config files placed with the jar. This code works on Windows. Add the code within the main class.

File jarDir = new File(MyAppName.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String jarDirpath = jarDir.getParent();

System.out.println(jarDirpath);

How do you run a Python script as a service in Windows?

A complete pywin32 example using loop or subthread

After working on this on and off for a few days, here is the answer I would have wished to find, using pywin32 to keep it nice and self contained.

This is complete working code for one loop-based and one thread-based solution. It may work on both python 2 and 3, although I've only tested the latest version on 2.7 and Win7. The loop should be good for polling code, and the tread should work with more server-like code. It seems to work nicely with the waitress wsgi server that does not have a standard way to shut down gracefully.

I would also like to note that there seems to be loads of examples out there, like this that are almost useful, but in reality misleading, because they have cut and pasted other examples blindly. I could be wrong. but why create an event if you never wait for it?

That said I still feel I'm on somewhat shaky ground here, especially with regards to how clean the exit from the thread version is, but at least I believe there are nothing misleading here.

To run simply copy the code to a file and follow the instructions.

update:

Use a simple flag to terminate thread. The important bit is that "thread done" prints.
For a more elaborate example exiting from an uncooperative server thread see my post about the waitress wsgi server.

# uncomment mainthread() or mainloop() call below
# run without parameters to see HandleCommandLine options
# install service with "install" and remove with "remove"
# run with "debug" to see print statements
# with "start" and "stop" watch for files to appear
# check Windows EventViever for log messages

import socket
import sys
import threading
import time
from random import randint
from os import path

import servicemanager
import win32event
import win32service
import win32serviceutil
# see http://timgolden.me.uk/pywin32-docs/contents.html for details


def dummytask_once(msg='once'):
    fn = path.join(path.dirname(__file__),
                '%s_%s.txt' % (msg, randint(1, 10000)))
    with open(fn, 'w') as fh:
        print(fn)
        fh.write('')


def dummytask_loop():
    global do_run
    while do_run:
        dummytask_once(msg='loop')
        time.sleep(3)


class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        global do_run
        do_run = True
        print('thread start\n')
        dummytask_loop()
        print('thread done\n')

    def exit(self):
        global do_run
        do_run = False


class SMWinservice(win32serviceutil.ServiceFramework):
    _svc_name_ = 'PyWinSvc'
    _svc_display_name_ = 'Python Windows Service'
    _svc_description_ = 'An example of a windows service in Python'

    @classmethod
    def parse_command_line(cls):
        win32serviceutil.HandleCommandLine(cls)

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.stopEvt = win32event.CreateEvent(None, 0, 0, None)  # create generic event
        socket.setdefaulttimeout(60)

    def SvcStop(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                            servicemanager.PYS_SERVICE_STOPPED,
                            (self._svc_name_, ''))
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.stopEvt)  # raise event

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                            servicemanager.PYS_SERVICE_STARTED,
                            (self._svc_name_, ''))
        # UNCOMMENT ONE OF THESE
        # self.mainthread()
        # self.mainloop()

    # Wait for stopEvt indefinitely after starting thread.
    def mainthread(self):
        print('main start')
        self.server = MyThread()
        self.server.start()
        print('wait for win32event')
        win32event.WaitForSingleObject(self.stopEvt, win32event.INFINITE)
        self.server.exit()
        print('wait for thread')
        self.server.join()
        print('main done')

    # Wait for stopEvt event in loop.
    def mainloop(self):
        print('loop start')
        rc = None
        while rc != win32event.WAIT_OBJECT_0:
            dummytask_once()
            rc = win32event.WaitForSingleObject(self.stopEvt, 3000)
        print('loop done')


if __name__ == '__main__':
    SMWinservice.parse_command_line()

How can I read a large text file line by line using Java?

You can use streams to do it more precisely:

Files.lines(Paths.get("input.txt")).forEach(s -> stringBuffer.append(s);

How to install VS2015 Community Edition offline

The following worked for me on a Windows 8.1 machine to download and prepare the setup folder, and then on a Windows 10 laptop to install:

  1. Go to https://my.visualstudio.com/downloads?q=visual%20studio%20community%202015
  2. Select “Visual Studio Community 2015 with Update 3” x64, English, DVD, and Download.
  3. Open the folder containing the download, which is called: en_visual_studio_community_2015_with_update_3_x86_x64_dvd_8923300.iso and its size is 7,617,847,296 bytes.
  4. Right-click on the file name: Mount
  5. On the mount folder, shift-right-click on an empty space: Open command window here
  6. On the command window: vs_community.exe /layout "blah blah blah blah \Visual Studio 2015\Setup" (or whatever path you want; the Setup folder gets created).
  7. Follow the dialog box instructions.

When I did this, it remained for exactly two hours and ten secs in the Acquiring: Optional items. Don’t despair.

When it completed, the size of the Setup folder was 12.9 GB. Compare with the size of the .iso above.

After completion, I succeeded on installing without a network connection, and that even though on completion I had got the following: enter image description here

SSL "Peer Not Authenticated" error with HttpClient 4.1

Im not a java developer but was using a java app to test a RESTful API. In order for me to fix the error I had to install the intermediate certificates in the webserver in order to make the error go away. I was using lighttpd, the original certificate was installed on an IIS server. Hope it helps. These were the certificates I had missing on the server.

  • CA.crt
  • UTNAddTrustServer_CA.crt
  • AddTrustExternalCARoot.crt

convert string date to java.sql.Date

worked for me too:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date parsed = null;
    try {
        parsed = sdf.parse("02/01/2014");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    java.sql.Date data = new java.sql.Date(parsed.getTime());
    contato.setDataNascimento( data);

    // Contato DataNascimento era Calendar
    //contato.setDataNascimento(Calendar.getInstance());         

    // grave nessa conexão!!! 
    ContatoDao dao = new ContatoDao("mysql");           

    // método elegante 
    dao.adiciona(contato); 
    System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());

Where do I mark a lambda expression async?

And for those of you using an anonymous expression:

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});

How to change the Title of the window in Qt?

For new Qt users this is a little more confusing than it seems if you are using QT Designer and .ui files.

Initially I tried to use ui->setWindowTitle, but that doesn't exist. ui is not a QDialog or a QMainWindow.

The owner of the ui is the QDialog or QMainWindow, the .ui just describes how to lay it out. In that case, you would use:

this->setWindowTitle("New Title");

I hope this helps someone else.

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

I'm not C++ developer so I will not provide code. But I can provide simple hsv2rgb algorithm (rgb2hsv here) which I currently discover - I update wiki with description: HSV and HLS. Main improvement is that I carefully observe r,g,b as hue functions and introduce simpler shape function to describe them (without loosing accuracy). The Algorithm - on input we have: h (0-255), s (0-255), v(0-255)

r = 255*f(5),   g = 255*f(3),   b = 255*f(1)

We use function f described as follows

f(n) = v/255 - (v/255)*(s/255)*max(min(k,4-k,1),0)

where (mod can return fraction part; k is floating point number)

k = (n+h*360/(255*60)) mod 6;

Here are snippets/PoV in SO in JS: HSV and HSL

How do I find the index of a character in a string in Ruby?

str="abcdef"

str.index('c') #=> 2 #String matching approach
str=~/c/ #=> 2 #Regexp approach 
$~ #=> #<MatchData "c">

Hope it helps. :)

How can I check if PostgreSQL is installed or not via Linux script?

There is no straightforward way to do this. All you can do is check with the package manager (rpm, dpkg) or probe some likely locations for the files you want. Or you could try to connect to a likely port (5432) and see if you get a PostgreSQL protocol response. But none of this is going to be very robust. You might want to review your requirements.

Changing datagridview cell color dynamically

Considere use DataBindingComplete event for update the style. The next code change the style of the cell:

    private void Grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        this.Grid.Rows[2].Cells[1].Style.BackColor = Color.Green;
    }

How to get href value using jQuery?

**Replacing  href attribut value to other** 
 
 <div class="cpt">
   <a href="/ref/ref/testone.html">testoneLink</a>
 </div>

  <div class="test" >
      <a href="/ref/ref/testtwo.html">testtwoLInk</a>
  </div>

 <!--Remove first default Link from href attribut -->
<script>
     Remove first default Link from href attribut
    $(".cpt a").removeAttr("href");
    
    Add  Link to same href attribut
    var testurl= $(".test").find("a").attr("href");
    $(".test a").attr('href', testurl);
</script>

How can I create a blank/hardcoded column in a sql query?

This should work on most databases. You can also select a blank string as your extra column like so:

Select
  Hat, Show, Boat, '' as SomeValue
From
  Objects

Is there a way to list open transactions on SQL Server 2000 database?

DBCC OPENTRAN helps to identify active transactions that may be preventing log truncation. DBCC OPENTRAN displays information about the oldest active transaction and the oldest distributed and nondistributed replicated transactions, if any, within the transaction log of the specified database. Results are displayed only if there is an active transaction that exists in the log or if the database contains replication information.

An informational message is displayed if there are no active transactions in the log.

DBCC OPENTRAN

How can I specify the default JVM arguments for programs I run from eclipse?

Yes, right click the project. Click Run as then Run Configurations. You can change the parameters passed to the JVM in the Arguments tab in the VM Arguments box.

That configuration can then be used as the default when running the project.

How to get the onclick calling object?

http://docs.jquery.com/Events/jQuery.Event

Try with event.target

Contains the DOM element that issued the event. This can be the element that registered for the event or a child of it.

Access Https Rest Service using Spring RestTemplate

One point from me. I used a mutual cert authentication with spring-boot microservices. The following is working for me, key points here are keyManagerFactory.init(...) and sslcontext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()) lines of code without them, at least for me, things did not work. Certificates are packaged by PKCS12.

@Value("${server.ssl.key-store-password}")
private String keyStorePassword;
@Value("${server.ssl.key-store-type}")
private String keyStoreType;
@Value("${server.ssl.key-store}")
private Resource resource;

private RestTemplate getRestTemplate() throws Exception {
    return new RestTemplate(clientHttpRequestFactory());
}

private ClientHttpRequestFactory clientHttpRequestFactory() throws Exception {
    return new HttpComponentsClientHttpRequestFactory(httpClient());
}

private HttpClient httpClient() throws Exception {

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore trustStore = KeyStore.getInstance(keyStoreType);

    if (resource.exists()) {
        InputStream inputStream = resource.getInputStream();

        try {
            if (inputStream != null) {
                trustStore.load(inputStream, keyStorePassword.toCharArray());
                keyManagerFactory.init(trustStore, keyStorePassword.toCharArray());
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    } else {
        throw new RuntimeException("Cannot find resource: " + resource.getFilename());
    }

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
    sslcontext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
    SSLConnectionSocketFactory sslConnectionSocketFactory =
            new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1.2"}, null, getDefaultHostnameVerifier());

    return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
}

SVN checkout the contents of a folder, not the folder itself

Just add a . to it:

svn checkout file:///home/landonwinters/svn/waterproject/trunk .

That means: check out to current directory.

Remove commas from the string using JavaScript

To remove the commas, you'll need to use replace on the string. To convert to a float so you can do the maths, you'll need parseFloat:

var total = parseFloat('100,000.00'.replace(/,/g, '')) +
            parseFloat('500,000.00'.replace(/,/g, ''));

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

I think the least intrusive way of doing this is as follows:

  1. Check if the user-agent is that of an iPhone/iPod Touch
  2. Check for an appInstalled cookie
  3. If the cookie exists and is set to true, set window.location to your-uri:// (or do the redirect server side)
  4. If the cookie doesn't exist, open a "Did you know Your Site Name has an iPhone application?" modal with a "Yep, I've already got it", "Nope, but I'd love to try it", and "Leave me alone" button.
    1. The "Yep" button sets the cookie to true and redirects to your-uri://
    2. The "Nope" button redirects to "http://itunes.com/apps/yourappname" which will open the App Store on the device
    3. The "Leave me alone" button sets the cookie to false and closes the modal

The other option I've played with but found a little clunky was to do the following in Javascript:

setTimeout(function() {
  window.location = "http://itunes.com/apps/yourappname";
}, 25);

// If "custom-uri://" is registered the app will launch immediately and your
// timer won't fire. If it's not set, you'll get an ugly "Cannot Open Page"
// dialogue prior to the App Store application launching
window.location = "custom-uri://";

Is unsigned integer subtraction defined behavior?

With unsigned numbers of type unsigned int or larger, in the absence of type conversions, a-b is defined as yielding the unsigned number which, when added to b, will yield a. Conversion of a negative number to unsigned is defined as yielding the number which, when added to the sign-reversed original number, will yield zero (so converting -5 to unsigned will yield a value which, when added to 5, will yield zero).

Note that unsigned numbers smaller than unsigned int may get promoted to type int before the subtraction, the behavior of a-b will depend upon the size of int.

How do I center a window onscreen in C#?

  1. Using the Property window

    Select form ? go to property window ? select "start position" ? select whatever the place you want.

    "

  2. Programmatically

    Form form1 = new Form(); form1.StartPosition = FormStartPosition.CenterScreen; form1.ShowDialog();

    Note: Do not directly call Form.CenterToScreen() from your code. Read here.

How to escape special characters of a string with single backslashes

Just assuming this is for a regular expression, use re.escape.

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

How do I get the Session Object in Spring?

In my scenario, I've injected the HttpSession into the CustomAuthenticationProvider class like this

public class CustomAuthenticationProvider extends  AbstractUserDetailsAuthenticationProvider{

    @Autowired 
    private HttpSession httpSession;

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken)
             throws AuthenticationException
    {
        System.out.println("Method invoked : additionalAuthenticationChecks isAuthenticated ? :"+usernamePasswordAuthenticationToken.isAuthenticated());
    }

    @Override
    protected UserDetails retrieveUser(String username,UsernamePasswordAuthenticationToken authentication) throws AuthenticationException 
    {
        System.out.println("Method invoked : retrieveUser");
        //so far so good, i can authenticate user here, and throw exception 
if not authenticated!!
        //THIS IS WHERE I WANT TO ACCESS SESSION OBJECT
        httpSession.setAttribute("userObject", myUserObject);
    }
}

How to add a Try/Catch to SQL Stored Procedure

Create Proc[usp_mquestions]  
( 
 @title  nvarchar(500),   --0
 @tags  nvarchar(max),   --1
 @category  nvarchar(200),   --2
 @ispoll  char(1),   --3
 @descriptions  nvarchar(max),   --4
)              
 AS  
 BEGIN TRY




BEGIN
DECLARE @message varchar(1000); 
DECLARE @tempid bigint; 

IF((SELECT count(id) from  [xyz] WHERE title=@title)>0)
BEGIN
SELECT 'record already existed.';
END
ELSE
BEGIN               


if @id=0 
begin 
select @tempid =id from [xyz] where id=@id;

if @tempid is null 
BEGIN 
        INSERT INTO xyz
        (entrydate,updatedate)
        VALUES
        (GETDATE(),GETDATE())

        SET @tempid=@@IDENTITY;
 END 
END 
ELSE 
BEGIN 
set @tempid=@id 
END 
if @tempid>0 
BEGIN 

    -- Updation of table begin--


UPDATE  tab_questions
set title=@title, --0 
 tags=@tags, --1 
 category=@category, --2 
 ispoll=@ispoll, --3 
 descriptions=@descriptions, --4 
 status=@status, --5

WHERE id=@tempid ; --9 ;


IF @id=0 
BEGIN 
SET @message= 'success:Record added successfully:'+ convert(varchar(10), @tempid)
END 
ELSE 
BEGIN 
SET @message= 'success:Record updated successfully.:'+ convert(varchar(10), @tempid)

END 
END 
ELSE 
BEGIN 
SET @message= 'failed:invalid request:'+convert(varchar(10), @tempid)
END 

END
END

END TRY
BEGIN CATCH
    SET @message='failed:'+ ERROR_MESSAGE();
END CATCH
SELECT @message;

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

Thanks to Erhun's answer I finally realised that my JSON mapper was returning the quotation marks around my data too! I needed to use "asText()" instead of "toString()"

It's not an uncommon issue - one's brain doesn't see anything wrong with the correct data, surrounded by quotes!

discoveryJson.path("some_endpoint").toString();
"https://what.the.com/heck"

discoveryJson.path("some_endpoint").asText();
https://what.the.com/heck

How to get JSON object from Razor Model object in javascript

After use codevar json = @Html.Raw(Json.Encode(@Model.CollegeInformationlist));

You need use JSON.parse(JSON.stringify(json));

Disable webkit's spin buttons on input type="number"?

The below css works for both Chrome and Firefox

input[type=number]::-webkit-outer-spin-button,
input[type=number]::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

input[type=number] {
    -moz-appearance:textfield;
}

Responsive background image in div full width

I also tried this style for ionic hybrid app background. this is also having style for background blur effect.

.bg-image {
   position: absolute;
   background: url(../img/bglogin.jpg) no-repeat;
   height: 100%;
   width: 100%;
   background-size: cover;
   bottom: 0px;
   margin: 0 auto;
   background-position: 50%;


  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);

}

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

Your tried to turn that source file into an executable, which obviously isn't possible, because the mandatory entry point, the main function, isn't defined. Add a file main.cpp and define a main function. If you're working on the commandline (which I doubt), you can add /c to only compile and not link. This will produce an object file only, which needs to be linked into either a static or shared lib or an application (in which case you'll need an oject file with main defined).

_WinMain is Microsoft's name for main when linking.

Also: you're not running the code yet, you are compiling (and linking) it. C++ is not an interpreted language.

Return single column from a multi-dimensional array

Quite simple:

$input = array(
  array(
    'tag_name' => 'google'
  ),
  array(
    'tag_name' => 'technology'
  )
);

echo implode(', ', array_map(function ($entry) {
  return $entry['tag_name'];
}, $input));

http://3v4l.org/ltBZ0


and new in php v5.5.0, array_column:

echo implode(', ', array_column($input, 'tag_name'));

How to access the request body when POSTing using Node.js and Express?

Express 4.0 and above:

$ npm install --save body-parser

And then in your node app:

const bodyParser = require('body-parser');
app.use(bodyParser);

Express 3.0 and below:

Try passing this in your cURL call:

--header "Content-Type: application/json"

and making sure your data is in JSON format:

{"user":"someone"}

Also, you can use console.dir in your node.js code to see the data inside the object as in the following example:

var express = require('express');
var app = express.createServer();

app.use(express.bodyParser());

app.post('/', function(req, res){
    console.dir(req.body);
    res.send("test");
}); 

app.listen(3000);

This other question might also help: How to receive JSON in express node.js POST request?

If you don't want to use the bodyParser check out this other question: https://stackoverflow.com/a/9920700/446681

Connect different Windows User in SQL Server Management Studio (2005 or later)

The only way to achieve what you want is opening several instances of SSMS by right clicking on shortcut and using the 'Run-as' feature.

UITableView Separator line

Here is an alternate way to add a custom separator line to a UITableView by making a CALayer for the image and using that as the separator line.

// make a CALayer for the image for the separator line

CALayer *separator = [CALayer layer];
separator.contents = (id)[UIImage imageNamed:@"myImage.png"].CGImage;
separator.frame = CGRectMake(0, 54, self.view.frame.size.width, 2);
[cell.layer addSublayer:separator];

SQL Inner Join On Null Values

I'm pretty sure that the join doesn't even do what you want. If there are 100 records in table a with a null qid and 100 records in table b with a null qid, then the join as written should make a cross join and give 10,000 results for those records. If you look at the following code and run the examples, I think that the last one is probably more the result set you intended:

create table #test1 (id int identity, qid int)
create table #test2 (id int identity, qid int)

Insert #test1 (qid)
select null
union all
select null
union all
select 1
union all
select 2
union all
select null

Insert #test2 (qid)
select null
union all
select null
union all
select 1
union all
select 3
union all
select null


select * from #test2 t2
join #test1 t1 on t2.qid = t1.qid

select * from #test2 t2
join #test1 t1 on isnull(t2.qid, 0) = isnull(t1.qid, 0)


select * from #test2 t2
join #test1 t1 on 
 t1.qid = t2.qid OR ( t1.qid IS NULL AND t2.qid IS NULL )


select t2.id, t2.qid, t1.id, t1.qid from #test2 t2
join #test1 t1 on t2.qid = t1.qid
union all
select null, null,id, qid from #test1 where qid is null
union all
select id, qid, null, null from #test2  where qid is null

Java Wait and Notify: IllegalMonitorStateException

You're calling both wait and notifyAll without using a synchronized block. In both cases the calling thread must own the lock on the monitor you call the method on.

From the docs for notify (wait and notifyAll have similar documentation but refer to notify for the fullest description):

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Only one thread will be able to actually exit wait at a time after notifyAll as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.

Finding element's position relative to the document

For those that want to get the x and y coordinates of various positions of an element, relative to the document.

const getCoords = (element, position) => {
  const { top, left, width, height } = element.getBoundingClientRect();
  let point;
  switch (position) {
    case "top left":
      point = {
        x: left + window.pageXOffset,
        y: top + window.pageYOffset
      };
      break;
    case "top center":
      point = {
        x: left + width / 2 + window.pageXOffset,
        y: top + window.pageYOffset
      };
      break;
    case "top right":
      point = {
        x: left + width + window.pageXOffset,
        y: top + window.pageYOffset
      };
      break;
    case "center left":
      point = {
        x: left + window.pageXOffset,
        y: top + height / 2 + window.pageYOffset
      };
      break;
    case "center":
      point = {
        x: left + width / 2 + window.pageXOffset,
        y: top + height / 2 + window.pageYOffset
      };
      break;
    case "center right":
      point = {
        x: left + width + window.pageXOffset,
        y: top + height / 2 + window.pageYOffset
      };
      break;
    case "bottom left":
      point = {
        x: left + window.pageXOffset,
        y: top + height + window.pageYOffset
      };
      break;
    case "bottom center":
      point = {
        x: left + width / 2 + window.pageXOffset,
        y: top + height + window.pageYOffset
      };
      break;
    case "bottom right":
      point = {
        x: left + width + window.pageXOffset,
        y: top + height + window.pageYOffset
      };
      break;
  }
  return point;
};

Usage

  • getCoords(document.querySelector('selector'), 'center')

  • getCoords(document.querySelector('selector'), 'bottom right')

  • getCoords(document.querySelector('selector'), 'top center')

What is the best way to remove the first element from an array?

Simplest way is probably as follows - you basically need to construct a new array that is one element smaller, then copy the elements you want to keep to the right positions.

int n=oldArray.length-1;
String[] newArray=new String[n];
System.arraycopy(oldArray,1,newArray,0,n);

Note that if you find yourself doing this kind of operation frequently, it could be a sign that you should actually be using a different kind of data structure, e.g. a linked list. Constructing a new array every time is an O(n) operation, which could get expensive if your array is large. A linked list would give you O(1) removal of the first element.

An alternative idea is not to remove the first item at all, but just increment an integer that points to the first index that is in use. Users of the array will need to take this offset into account, but this can be an efficient approach. The Java String class actually uses this method internally when creating substrings.

Is there any simple way to convert .xls file to .csv file? (Excel)

Install these 2 packages

<packages>
  <package id="ExcelDataReader" version="3.3.0" targetFramework="net451" />
  <package id="ExcelDataReader.DataSet" version="3.3.0" targetFramework="net451" />
</packages>

Helper function

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

namespace ExcelToCsv
{
    public class ExcelFileHelper
    {
        public static bool SaveAsCsv(string excelFilePath, string destinationCsvFilePath)
        {

            using (var stream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                IExcelDataReader reader = null;
                if (excelFilePath.EndsWith(".xls"))
                {
                    reader = ExcelReaderFactory.CreateBinaryReader(stream);
                }
                else if (excelFilePath.EndsWith(".xlsx"))
                {
                    reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                }

                if (reader == null)
                    return false;

                var ds = reader.AsDataSet(new ExcelDataSetConfiguration()
                {
                    ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                    {
                        UseHeaderRow = false
                    }
                });

                var csvContent = string.Empty;
                int row_no = 0;
                while (row_no < ds.Tables[0].Rows.Count)
                {
                    var arr = new List<string>();
                    for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                    {
                        arr.Add(ds.Tables[0].Rows[row_no][i].ToString());
                    }
                    row_no++;
                    csvContent += string.Join(",", arr) + "\n";
                }
                StreamWriter csv = new StreamWriter(destinationCsvFilePath, false);
                csv.Write(csvContent);
                csv.Close();
                return true;
            }
        }
    }
}

Usage :

var excelFilePath = Console.ReadLine();
string output = Path.ChangeExtension(excelFilePath, ".csv");
ExcelFileHelper.SaveAsCsv(excelFilePath, output);

How to get am pm from the date time string using moment js

you will get the time without specifying the date format. convert the string to date using Date object

var myDate = new Date('Mon 03-Jul-2017, 06:00 PM');

working solution:

_x000D_
_x000D_
var myDate= new Date('Mon 03-Jul-2017, 06:00 PM');_x000D_
console.log(moment(myDate).format('HH:mm')); // 24 hour format _x000D_
console.log(moment(myDate).format('hh:mm'));_x000D_
console.log(moment(myDate).format('hh:mm A'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

How to set JAVA_HOME for multiple Tomcat instances?

Also, note that there shouldn't be any space after =:

set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_27

CSS background-image - What is the correct usage?

Have a look at the respective sitepoint reference pages for background-image and URIs

  1. It does not have to be in quotes but can use them if you like. (I think IE5/Mac does not support single quotes).
  2. Both relative and absolute is possible; a relative path is relative to the path of the css file.

Align Div at bottom on main Div

Please try this:

#b {
display: -webkit-inline-flex;
display: -moz-inline-flex;
display: inline-flex;

-webkit-flex-flow: row nowrap;
-moz-flex-flow: row nowrap;
flex-flow: row nowrap;

-webkit-align-items: flex-end;
-moz-align-items: flex-end;
align-items: flex-end;}

Here's a JSFiddle demo: http://jsfiddle.net/rudiedirkx/7FGKN/.

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

If you're thinking about manually removing Apple's default Python 2.7, I'd suggest you hang-fire and do-noting: Looks like Apple will very shortly do it for you:

Python 2.7 Deprecated in OSX 10.15 Catalina

Python 2.7- as well as Ruby & Perl- are deprecated in Catalina: (skip to section "Scripting Language Runtimes" > "Deprecations")

https://developer.apple.com/documentation/macos_release_notes/macos_catalina_10_15_release_notes

Apple To Remove Python 2.7 in OSX 10.16

Indeed, if you do nothing at all, according to The Mac Observer, by OSX version 10.16, Python 2.7 will disappear from your system:

https://www.macobserver.com/analysis/macos-catalina-deprecates-unix-scripting-languages/

Given this revelation, I'd suggest the best course of action is do nothing and wait for Apple to wipe it for you. As Apple is imminently about to remove it for you, doesn't seem worth the risk of tinkering with your Python environment.

NOTE: I see the question relates specifically to OSX v 10.6.4, but it appears this question has become a pivot-point for all OSX folks interested in removing Python 2.7 from their systems, whatever version they're running.

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

Here is an handy solution! I'm using SQL Server 2008 R2.

As you want to modify the FK constraint by adding ON DELETE/UPDATE CASCADE, follow these steps:

NUMBER 1:

Right click on the constraint and click to Modify

enter image description here

NUMBER 2:

Choose your constraint on the left side (if there are more than one). Then on the right side, collapse "INSERT And UPDATE Specification" point and specify the actions on Delete Rule or Update Rule row to suit your need. After that, close the dialog box.

enter image description here

NUMBER 3:

The final step is to save theses modifications (of course!)

enter image description here

PS: It's saved me from a bunch of work as I want to modify a primary key referenced in another table.

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

I ran across a site a few weeks back. This is a working example of the first column locked but it is not browser compatible with Firefox. I didn't do a lot of checking around but it seems it only works in IE. There are some notes the author provided along with it that you can read.

Lock the First column: http://home.tampabay.rr.com/bmerkey/examples/locked-column-csv.html

Let me know if you need the Javascript to lock the Table headers too.

How to check Network port access and display useful message?

Great answer by mshutov & Salselvaprabu. I needed something a little bit more robust, and that checked all IPAddresses that was provided instead of checking only the first one.

I also wanted to replicate some of the parameter names and functionality than the Test-Connection function.

This new function allows you to set a Count for the number of retries, and the Delay between each try. Enjoy!

function Test-Port {

    [CmdletBinding()]
    Param (
        [string] $ComputerName,
        [int] $Port,
        [int] $Delay = 1,
        [int] $Count = 3
    )

    function Test-TcpClient ($IPAddress, $Port) {

        $TcpClient = New-Object Net.Sockets.TcpClient
        Try { $TcpClient.Connect($IPAddress, $Port) } Catch {}

        If ($TcpClient.Connected) { $TcpClient.Close(); Return $True }
        Return $False

    }

    function Invoke-Test ($ComputerName, $Port) {

        Try   { [array]$IPAddress = [System.Net.Dns]::GetHostAddresses($ComputerName) | Select-Object -Expand IPAddressToString } 
        Catch { Return $False }

        [array]$Results = $IPAddress | % { Test-TcpClient -IPAddress $_ -Port $Port }
        If ($Results -contains $True) { Return $True } Else { Return $False }

    }

    for ($i = 1; ((Invoke-Test -ComputerName $ComputerName -Port $Port) -ne $True); $i++)
    {
        if ($i -ge $Count) {
            Write-Warning "Timed out while waiting for port $Port to be open on $ComputerName!"
            Return $false
        }

        Write-Warning "Port $Port not open, retrying..."
        Sleep $Delay
    }

    Return $true

}

How to declare Return Types for Functions in TypeScript

You are correct - here is a fully working example - you'll see that var result is implicitly a string because the return type is specified on the greet() function. Change the type to number and you'll get warnings.

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() : string {
        return "Hello, " + this.greeting;
    }
} 

var greeter = new Greeter("Hi");
var result = greeter.greet();

Here is the number example - you'll see red squiggles in the playground editor if you try this:

greet() : number {
    return "Hello, " + this.greeting;
}

DataTrigger where value is NOT null?

Stop! No converter! I dont want to "sell" the library of this guy, but I hated the fact of doing converter everytime I wanted to compare stuff in XAML.

So with this library : https://github.com/Alex141/CalcBinding

you can do that [and a lot more] :

First, In the declaration of the windows/userControl :

<Windows....
     xmlns:conv="clr-namespace:CalcBinding;assembly=CalcBinding"
>

then, in the textblock

<TextBlock>
      <TextBlock.Style>
          <Style.Triggers>
          <DataTrigger Binding="{conv:Binding 'MyValue==null'}" Value="false">
             <Setter Property="Background" Value="#FF80C983"></Setter>
          </DataTrigger>
        </Style.Triggers>
      </TextBlock.Style>
    </TextBlock>

The magic part is the conv:Binding 'MYValue==null'. In fact, you could set any condition you wanted [look at the doc].

note that I am not a fan of third party. but this library is Free, and little impact (just add 2 .dll to the project).

What datatype should be used for storing phone numbers in SQL Server 2005?

Since you need to accommodate many different phone number formats (and probably include things like extensions etc.) it may make the most sense to just treat it as you would any other varchar. If you could control the input, you could take a number of approaches to make the data more useful, but it doesn't sound that way.

Once you decide to simply treat it as any other string, you can focus on overcoming the inevitable issues regarding bad data, mysterious phone number formating and whatever else will pop up. The challenge will be in building a good search strategy for the data and not how you store it in my opinion. It's always a difficult task having to deal with a large pile of data which you had no control over collecting.

Templated check for the existence of a class member function?

Now this was a nice little puzzle - great question!

Here's an alternative to Nicola Bonelli's solution that does not rely on the non-standard typeof operator.

Unfortunately, it does not work on GCC (MinGW) 3.4.5 or Digital Mars 8.42n, but it does work on all versions of MSVC (including VC6) and on Comeau C++.

The longer comment block has the details on how it works (or is supposed to work). As it says, I'm not sure which behavior is standards compliant - I'd welcome commentary on that.


update - 7 Nov 2008:

It looks like while this code is syntactically correct, the behavior that MSVC and Comeau C++ show does not follow the standard (thanks to Leon Timmermans and litb for pointing me in the right direction). The C++03 standard says the following:

14.6.2 Dependent names [temp.dep]

Paragraph 3

In the definition of a class template or a member of a class template, if a base class of the class template depends on a template-parameter, the base class scope is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.

So, it looks like that when MSVC or Comeau consider the toString() member function of T performing name lookup at the call site in doToString() when the template is instantiated, that is incorrect (even though it's actually the behavior I was looking for in this case).

The behavior of GCC and Digital Mars looks to be correct - in both cases the non-member toString() function is bound to the call.

Rats - I thought I might have found a clever solution, instead I uncovered a couple compiler bugs...


#include <iostream>
#include <string>

struct Hello
{
    std::string toString() {
        return "Hello";
    }
};

struct Generic {};


// the following namespace keeps the toString() method out of
//  most everything - except the other stuff in this
//  compilation unit

namespace {
    std::string toString()
    {
        return "toString not defined";
    }

    template <typename T>
    class optionalToStringImpl : public T
    {
    public:
        std::string doToString() {

            // in theory, the name lookup for this call to 
            //  toString() should find the toString() in 
            //  the base class T if one exists, but if one 
            //  doesn't exist in the base class, it'll 
            //  find the free toString() function in 
            //  the private namespace.
            //
            // This theory works for MSVC (all versions
            //  from VC6 to VC9) and Comeau C++, but
            //  does not work with MinGW 3.4.5 or 
            //  Digital Mars 8.42n
            //
            // I'm honestly not sure what the standard says 
            //  is the correct behavior here - it's sort 
            //  of like ADL (Argument Dependent Lookup - 
            //  also known as Koenig Lookup) but without
            //  arguments (except the implied "this" pointer)

            return toString();
        }
    };
}

template <typename T>
std::string optionalToString(T & obj)
{
    // ugly, hacky cast...
    optionalToStringImpl<T>* temp = reinterpret_cast<optionalToStringImpl<T>*>( &obj);

    return temp->doToString();
}



int
main(int argc, char *argv[])
{
    Hello helloObj;
    Generic genericObj;

    std::cout << optionalToString( helloObj) << std::endl;
    std::cout << optionalToString( genericObj) << std::endl;
    return 0;
}

iOS (iPhone, iPad, iPodTouch) view real-time console log terminal

You have three options:

  • Xcode Organizer
  • Jailbroken device with syslogd + openSSH
  • Use dup2 to redirect all STDERR and STDOUT to a file and then "tail -f" that file (this last one is more a simulator thing, since you are stuck with the same problem of tailing a file on the device).

So, to get the 2º one you just need to install syslogd and OpenSSH from Cydia, restart required after to get syslogd going; now just open a ssh session to your device (via terminal or putty on windows), and type "tail -f /var/log/syslog". And there you go, wireless real time system log.

If you would like to try the 3º just search for "dup2" online, it's a system call.

How can I remove file extension from a website address?

same as Igor but should work without line 2:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

type object 'datetime.datetime' has no attribute 'datetime'

For python 3.3

from datetime import datetime, timedelta
futuredate = datetime.now() + timedelta(days=10)

How do I get DOUBLE_MAX?

You are looking for the float.h header.

How to check if a subclass is an instance of a class at runtime?

Maybe I'm missing something, but wouldn't this suffice:

if (view instanceof B) {
    // this view is an instance of B
}

Set a thin border using .css() in javascript

After a few futile hours battling with a 'SyntaxError: missing : after property id' message I can now expand on this topic:

border-width is a valid css property but it is not included in the jQuery css oject definition, so .css({border-width: '2px'}) will cause an error, but it's quite happy with .css({'border-width': '2px'}), presumably property names in quotes are just passed on as received.

How to keep a Python script output window open?

On Python 3

input('Press Enter to Exit...')

Will do the trick.

Eclipse gives “Java was started but returned exit code 13”

I had the same problem. i was using windows8 with 64 bit OS. I just changed the path to Program Files(*86) and then it started work. I put this line in eclipse.ini file like,

-vm
 C:\Program Files (x86)\Java\jre7\bin\javaw.exe

How to connect Robomongo to MongoDB

Robomongo 0.8.5 definitely works with MongoDB 3.X (mine version of MongoDB is 3.0.7, the newest one).

The following steps should be done to connect to the MongoDB server:

  1. Install MongoDB server (on Windows, Linux, etc. Your choice)
  2. Run the MongoDB server. Don't set net.bind_ip = 127.0.0.1 if you want the client to connect to the server by server's own IP address!
  3. Connect to the server from Robomongo with the server IP address + set authentication if needed.

Bootstrap 4 img-circle class not working

Now the class is this

_x000D_
_x000D_
 <img src="img/img5.jpg" width="200px" class="rounded-circle float-right">
_x000D_
_x000D_
_x000D_

Subdomain on different host

UPDATE - I do not have Total DNS enabled at GoDaddy because the domain is hosted at DiscountASP. As such, I could not add an A Record and that is why GoDaddy was only offering to forward my subdomain to a different site. I finally realized that I had to go to DiscountASP to add the A Record to point to DreamHost. Now waiting to see if it all works!

Of course, use the stinkin' IP! I'm not sure why that wasn't registering for me. I guess their helper text example of pointing to another url was throwing me off.

Thanks for both of the replies. I 'got it' as soon as I read Bryant's response which was first but Saif kicked it up a notch and added a little more detail.

Thanks!

TypeScript hashmap/dictionary interface

The most simple and the correct way is to use Record type Record<string, string>

const myVar : Record<string, string> = {
   key1: 'val1',
   key2: 'val2',
}

Add ArrayList to another ArrayList in java

Initiate the NodeList inside the for loop and you will get the desired output.

ArrayList<String> nodes = new ArrayList<String>();
 ArrayList list=new ArrayList();

        for(int i=0;i<PropertyNode.getLength()-1;i++){
            ArrayList NodeList=new ArrayList();
            Node childNode =  PropertyNode.item(i);
                NodeList Children = childNode.getChildNodes();

                if(Children!=null){
                    nodes.clear();
                    nodes.add("PropertyStart");
                    nodes.add(Children.item(3).getTextContent());
                    nodes.add(Children.item(7).getTextContent());
                    nodes.add(Children.item(9).getTextContent());
                    nodes.add(Children.item(11).getTextContent());
                    nodes.add(Children.item(13).getTextContent());
                    nodes.add("PropertyEnd");

                }   
                NodeList.addAll(nodes);
                list.add(NodeList);
        }

Explanation: NodeList is an object which remains same throughout the loop so adding same variable to list in a loop will actually add it only once. The loop is only adding its variables in single NodeList array hence you must be seeing

[/*list*/    [  /*NodeList*/   ]   ]

and NodeList contains [prostart, a,b,c,proend,prostart,d,e,f,proend ...]

Typescript: How to extend two classes?

In design patterns there is a principle called "favouring composition over inheritance". It says instead of inheriting Class B from Class A ,put an instance of class A inside class B as a property and then you can use functionalities of class A inside class B. You can see some examples of that here and here.

Commenting code in Notepad++

Yes in Notepad++ you can do that!

Some hotkeys regarding comments:

  • Ctrl+Q Toggle block comment
  • Ctrl+K Block comment
  • Ctrl+Shift+K Block uncomment
  • Ctrl+Shift+Q Stream comment

Source: shortcutworld.com from the Comment / uncomment section.

On the link you will find many other useful shortcuts too.

How to run a command in the background and get no output?

Use nohup if your background job takes a long time to finish or you just use SecureCRT or something like it login the server.

Redirect the stdout and stderr to /dev/null to ignore the output.

nohup /path/to/your/script.sh > /dev/null 2>&1 &

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

There are some classes in the Java platform libraries that do extend an instantiable class and add a value component. For example, java.sql.Timestamp extends java.util.Date and adds a nanoseconds field. The equals implementation for Timestamp does violate symmetry and can cause erratic behavior if Timestamp and Date objects are used in the same collection or are otherwise intermixed. The Timestamp class has a disclaimer cautioning programmers against mixing dates and timestamps. While you won’t get into trouble as long as you keep them separate, there’s nothing to prevent you from mixing them, and the resulting errors can be hard to debug. This behavior of the Timestamp class was a mistake and should not be emulated.

check out this link

http://blogs.sourceallies.com/2012/02/hibernate-date-vs-timestamp/

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

For bootstrap 3.0, this worked for me:

.myclass .glyphicon {color:blue !important;}

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

Per @Slauma's answer and @Milton's suggestion I've extended our base class's custom save method with a try/catch that will handle (and hence log in our error logging!) these sorts of exceptions.

// Where `BaseDB` is your Entities object... (it could be `this` in a different design)
public void Save(bool? validateEntities = null)
{
    try
    {
        //Capture and set the validation state if we decide to
        bool validateOnSaveEnabledStartState = BaseDB.Configuration.ValidateOnSaveEnabled;
        if (validateEntities.HasValue)
            BaseDB.Configuration.ValidateOnSaveEnabled = validateEntities.Value;

        BaseDB.SaveChanges();

        //Revert the validation state when done
        if (validateEntities.HasValue)
            BaseDB.Configuration.ValidateOnSaveEnabled = validateOnSaveEnabledStartState;
    }
    catch (DbEntityValidationException e)
    {
        StringBuilder sb = new StringBuilder();
        foreach (var eve in e.EntityValidationErrors)
        {
            sb.AppendLine(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", 
                                            eve.Entry.Entity.GetType().Name,
                                            eve.Entry.State));
            foreach (var ve in eve.ValidationErrors)
            {
                sb.AppendLine(string.Format("- Property: \"{0}\", Error: \"{1}\"",
                                            ve.PropertyName,
                                            ve.ErrorMessage));
            }
        }
        throw new DbEntityValidationException(sb.ToString(), e);
    }
}

jQuery form validation on button click

$(document).ready(function() {
    $("#form1").validate({
        rules: {
            field1: "required"
        },
        messages: {
            field1: "Please specify your name"
        }
    })
});

<form id="form1" name="form1">
     Field 1: <input id="field1" type="text" class="required">
    <input id="btn" type="submit" value="Validate">
</form>

You are also you using type="button". And I'm not sure why you ought to separate the submit button, place it within the form. It's more proper to do it that way. This should work.

How can I get a list of all values in select box?

Change:

x.length

to:

x.options.length

Link to fiddle

And I agree with Abraham - you might want to use text instead of value

Update
The reason your fiddle didn't work was because you chose the option: "onLoad" instead of: "No wrap - in "

What are all possible pos tags of NLTK?

The below can be useful to access a dict keyed by abbreviations:

>>> from nltk.data import load
>>> tagdict = load('help/tagsets/upenn_tagset.pickle')
>>> tagdict['NN'][0]
'noun, common, singular or mass'
>>> tagdict.keys()
['PRP$', 'VBG', 'VBD', '``', 'VBN', ',', "''", 'VBP', 'WDT', ...

Is 'bool' a basic datatype in C++?

bool is a fundamental datatype in C++. Converting true to an integer type will yield 1, and converting false will yield 0 (4.5/4 and 4.7/4). In C, until C99, there was no bool datatype, and people did stuff like

enum bool {
    false, true
};

So did the Windows API. Starting with C99, we have _Bool as a basic data type. Including stdbool.h will typedef #define that to bool and provide the constants true and false. They didn't make bool a basic data-type (and thus a keyword) because of compatibility issues with existing code.

All shards failed

If you're running a single node cluster for some reason, you might simply need to do avoid replicas, like this:

curl -XPUT -H 'Content-Type: application/json' 'localhost:9200/_settings' -d '
{
    "index" : {
        "number_of_replicas" : 0
    }
}'

Doing this you'll force to use es without replicas

How to vertical align an inline-block in a line of text?

_x000D_
_x000D_
code {_x000D_
    background: black;_x000D_
    color: white;_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>
_x000D_
_x000D_
_x000D_

Tested and works in Safari 5 and IE6+.

How to filter a data frame

Another method utilizing the dplyr package:

library(dplyr)
df <- mtcars %>%
        filter(mpg > 25)

Without the chain (%>%) operator:

library(dplyr)
df <- filter(mtcars, mpg > 25)

how to execute php code within javascript

Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below

<script type="text/javascript">
    var1 = "<?php echo 'Hello';?>";
</script>

Then in the .js file, you can use the variable

alert(var1);

If you try to evaluate php declaration in the .js file, it will NOT work

Html- how to disable <a href>?

You can use CSS to accomplish this:

_x000D_
_x000D_
.disabled {
  pointer-events: none;
  cursor: default;
}
_x000D_
<a href="somelink.html" class="disabled">Some link</a>
_x000D_
_x000D_
_x000D_

Or you can use JavaScript to prevent the default action like this:

$('.disabled').click(function(e){
    e.preventDefault();
})

How can I check if a program exists from a Bash script?

I second the use of "command -v". E.g. like this:

md=$(command -v mkdirhier) ; alias md=${md:=mkdir}  # bash

emacs="$(command -v emacs) -nw" || emacs=nano
alias e=$emacs
[[ -z $(command -v jed) ]] && alias jed=$emacs

Insert into a MySQL table or update if exists

When using batch insert use the following syntax:

INSERT INTO TABLE (id, name, age) VALUES (1, "A", 19), (2, "B", 17), (3, "C", 22)
ON DUPLICATE KEY UPDATE
    name = VALUES (name),
    ...

Hide/encrypt password in bash file to stop accidentally seeing it

Another solution, without regard to security (I also think it is better to keep the credentials in another file or in a database) is to encrypt the password with gpg and insert it in the script.

I use a password-less gpg key pair that I keep in a usb. (Note: When you export this key pair don't use --armor, export them in binary format).

First encrypt your password:

EDIT: Put a space before this command, so it is not recorded by the bash history.

echo -n "pAssw0rd" | gpg --armor --no-default-keyring --keyring /media/usb/key.pub --recipient [email protected] --encrypt

That will be print out the gpg encrypted password in the standart output. Copy the whole message and add this to the script:

password=$(gpg --batch --quiet --no-default-keyring --secret-keyring /media/usb/key.priv --decrypt <<EOF 
-----BEGIN PGP MESSAGE-----

hQEMA0CjbyauRLJ8AQgAkZT5gK8TrdH6cZEy+Ufl0PObGZJ1YEbshacZb88RlRB9
h2z+s/Bso5HQxNd5tzkwulvhmoGu6K6hpMXM3mbYl07jHF4qr+oWijDkdjHBVcn5
0mkpYO1riUf0HXIYnvCZq/4k/ajGZRm8EdDy2JIWuwiidQ18irp07UUNO+AB9mq8
5VXUjUN3tLTexg4sLZDKFYGRi4fyVrYKGsi0i5AEHKwn5SmTb3f1pa5yXbv68eYE
lCVfy51rBbG87UTycZ3gFQjf1UkNVbp0WV+RPEM9JR7dgR+9I8bKCuKLFLnGaqvc
beA3A6eMpzXQqsAg6GGo3PW6fMHqe1ZCvidi6e4a/dJDAbHq0XWp93qcwygnWeQW
Ozr1hr5mCa+QkUSymxiUrRncRhyqSP0ok5j4rjwSJu9vmHTEUapiyQMQaEIF2e2S
/NIWGg==
=uriR
-----END PGP MESSAGE-----
EOF)

In this way only if the usb is mounted in the system the password can be decrypted. Of course you can also import the keys into the system (less secure, or no security at all) or you can protect the private key with password (so it can not be automated).

How to determine the longest increasing subsequence using dynamic programming?

OK, I will describe first the simplest solution which is O(N^2), where N is the size of the collection. There also exists a O(N log N) solution, which I will describe also. Look here for it at the section Efficient algorithms.

I will assume the indices of the array are from 0 to N - 1. So let's define DP[i] to be the length of the LIS (Longest increasing subsequence) which is ending at element with index i. To compute DP[i] we look at all indices j < i and check both if DP[j] + 1 > DP[i] and array[j] < array[i] (we want it to be increasing). If this is true we can update the current optimum for DP[i]. To find the global optimum for the array you can take the maximum value from DP[0...N - 1].

int maxLength = 1, bestEnd = 0;
DP[0] = 1;
prev[0] = -1;

for (int i = 1; i < N; i++)
{
   DP[i] = 1;
   prev[i] = -1;

   for (int j = i - 1; j >= 0; j--)
      if (DP[j] + 1 > DP[i] && array[j] < array[i])
      {
         DP[i] = DP[j] + 1;
         prev[i] = j;
      }

   if (DP[i] > maxLength)
   {
      bestEnd = i;
      maxLength = DP[i];
   }
}

I use the array prev to be able later to find the actual sequence not only its length. Just go back recursively from bestEnd in a loop using prev[bestEnd]. The -1 value is a sign to stop.


OK, now to the more efficient O(N log N) solution:

Let S[pos] be defined as the smallest integer that ends an increasing sequence of length pos. Now iterate through every integer X of the input set and do the following:

  1. If X > last element in S, then append X to the end of S. This essentialy means we have found a new largest LIS.

  2. Otherwise find the smallest element in S, which is >= than X, and change it to X. Because S is sorted at any time, the element can be found using binary search in log(N).

Total runtime - N integers and a binary search for each of them - N * log(N) = O(N log N)

Now let's do a real example:

Collection of integers: 2 6 3 4 1 2 9 5 8

Steps:

0. S = {} - Initialize S to the empty set
1. S = {2} - New largest LIS
2. S = {2, 6} - New largest LIS
3. S = {2, 3} - Changed 6 to 3
4. S = {2, 3, 4} - New largest LIS
5. S = {1, 3, 4} - Changed 2 to 1
6. S = {1, 2, 4} - Changed 3 to 2
7. S = {1, 2, 4, 9} - New largest LIS
8. S = {1, 2, 4, 5} - Changed 9 to 5
9. S = {1, 2, 4, 5, 8} - New largest LIS

So the length of the LIS is 5 (the size of S).

To reconstruct the actual LIS we will again use a parent array. Let parent[i] be the predecessor of element with index i in the LIS ending at element with index i.

To make things simpler, we can keep in the array S, not the actual integers, but their indices(positions) in the set. We do not keep {1, 2, 4, 5, 8}, but keep {4, 5, 3, 7, 8}.

That is input[4] = 1, input[5] = 2, input[3] = 4, input[7] = 5, input[8] = 8.

If we update properly the parent array, the actual LIS is:

input[S[lastElementOfS]], 
input[parent[S[lastElementOfS]]],
input[parent[parent[S[lastElementOfS]]]],
........................................

Now to the important thing - how do we update the parent array? There are two options:

  1. If X > last element in S, then parent[indexX] = indexLastElement. This means the parent of the newest element is the last element. We just prepend X to the end of S.

  2. Otherwise find the index of the smallest element in S, which is >= than X, and change it to X. Here parent[indexX] = S[index - 1].

How to add option to select list in jQuery

Your code fails because you are executing a method (addOption) on the jQuery object (and this object does not support the method)

You can use the standard Javascript function like this:

$("#dropListBuilding")[0].options.add( new Option("My Text","My Value") )

How to open a new HTML page using jQuery?

Use window.open("file2.html");

Syntax

var windowObjectReference = window.open(strUrl, strWindowName[, strWindowFeatures]);

Return value and parameters

windowObjectReference 

A reference to the newly created window. If the call failed, it will be null. The reference can be used to access properties and methods of the new window provided it complies with Same origin policy security requirements.

strUrl 

The URL to be loaded in the newly opened window. strUrl can be an HTML document on the web, image file or any resource supported by the browser.

strWindowName 

A string name for the new window. The name can be used as the target of links and forms using the target attribute of an <a> or <form> element. The name should not contain any blank space. Note that strWindowName does not specify the title of the new window.

strWindowFeatures 

Optional parameter listing the features (size, position, scrollbars, etc.) of the new window. The string must not contain any blank space, each feature name and value must be separated by a comma.

Postgres: check if array field contains value?

Instead of IN we can use ANY with arrays casted to enum array, for example:

create type example_enum as enum (
  'ENUM1', 'ENUM2'
);

create table example_table (
  id integer,
  enum_field example_enum
);

select 
  * 
from 
  example_table t
where
  t.enum_field = any(array['ENUM1', 'ENUM2']::example_enum[]);

Or we can still use 'IN' clause, but first, we should 'unnest' it:

select 
  * 
from 
  example_table t
where
  t.enum_field in (select unnest(array['ENUM1', 'ENUM2']::example_enum[]));

Example: https://www.db-fiddle.com/f/LaUNi42HVuL2WufxQyEiC/0

Quick way to retrieve user information Active Directory

You can call UserPrincipal.FindByIdentity inside System.DirectoryServices.AccountManagement:

using System.DirectoryServices.AccountManagement;

using (var pc = new PrincipalContext(ContextType.Domain, "MyDomainName"))
{
    var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "MyDomainName\\" + userName);
}

Printing without newline (print 'a',) prints a space, how to remove?

From PEP 3105: print As a Function in the What’s New in Python 2.6 document:

>>> from __future__ import print_function
>>> print('a', end='')

Obviously that only works with python 3.0 or higher (or 2.6+ with a from __future__ import print_function at the beginning). The print statement was removed and became the print() function by default in Python 3.0.

HTTP Status 405 - Method Not Allowed Error for Rest API

I also had this problem and was able to solve it by enabling CORS support on the server. In my case it was an Azure server and it was easy: Enable CORS on Azure

So check for your server how it works and enable CORS. I didn't even need a browser plugin or proxy :)

How to get file creation & modification date/times in Python?

It may worth taking a look at the crtime library which implements cross-platform access to the file creation time.

from crtime import get_crtimes_in_dir

for fname, date in get_crtimes_in_dir(".", raise_on_error=True, as_epoch=False):
    print(fname, date)
    # file_a.py Mon Mar 18 20:51:18 CET 2019

How many spaces will Java String.trim() remove?

Based on the Java docs here, the .trim() replaces '\u0020' which is commonly known as whitespace.

But take note, the '\u00A0' (Unicode NO-BREAK SPACE &nbsp; ) is also seen as a whitespace, and .trim() will NOT remove this. This is especially common in HTML.

To remove it, I use :

tmpTrimStr = tmpTrimStr.replaceAll("\\u00A0", "");

An example of this problem was discussed here.

javascript Unable to get property 'value' of undefined or null reference

The issue is how you're attempting to get the value. Things like...

if ( document.frm_new_user_request.u_isid.value == '' )

won't work. You need to find the element you want to get the value of first. It's not quite like a server side language where you can type in an object's reference name and a period to get or assign values.

document.getElementById('[id goes here]').value;

will work. Note: JavaScript is case-sensitive

I would recommend using:

var variablename = document.getElementById('[id goes here]');

or

var variablename = document.getElementById('[id goes here]').value;

Append an object to a list in R in amortized constant time, O(1)?

in fact there is a subtelty with the c() function. If you do:

x <- list()
x <- c(x,2)
x = c(x,"foo")

you will obtain as expected:

[[1]]
[1]

[[2]]
[1] "foo"

but if you add a matrix with x <- c(x, matrix(5,2,2), your list will have another 4 elements of value 5 ! You would better do:

x <- c(x, list(matrix(5,2,2))

It works for any other object and you will obtain as expected:

[[1]]
[1]

[[2]]
[1] "foo"

[[3]]
     [,1] [,2]
[1,]    5    5
[2,]    5    5

Finally, your function becomes:

push <- function(l, ...) c(l, list(...))

and it works for any type of object. You can be smarter and do:

push_back <- function(l, ...) c(l, list(...))
push_front <- function(l, ...) c(list(...), l)

dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac

my issue:

# npm install -g canvas

dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.64.dylib
  Referenced from: /usr/local/opt/node@8/bin/node
  Reason: image not found

for now 20210118, after many try:

...
brew reinstall https://raw.githubusercontent.com/Homebrew/homebrew-core/master/Formula/icu4c.rb
brew upgrade npm
brew install node
brew uninstall --ignore-dependencies node@8 icu4c
brew install icu4c
...

Final worked solution is:

brew reinstall npm

Why are there two ways to unstage a file in Git?

Let's say you stage a whole directory via git add <folder>, but you want to exclude a file from the staged list (i.e. the list that generates when running git status) and keep the modifications within the excluded file (you were working on something and it's not ready for commit, but you don't want to lose your work...). You could simply use:

git reset <file>

When you run git status, you will see that whatever file(s) you reset are unstaged and the rest of the files you added are still in the staged list.

What do these operators mean (** , ^ , %, //)?

You are correct that ** is the power function.

^ is bitwise XOR.

% is indeed the modulus operation, but note that for positive numbers, x % m = x whenever m > x. This follows from the definition of modulus. (Additionally, Python specifies x % m to have the sign of m.)

// is a division operation that returns an integer by discarding the remainder. This is the standard form of division using the / in most programming languages. However, Python 3 changed the behavior of / to perform floating-point division even if the arguments are integers. The // operator was introduced in Python 2.6 and Python 3 to provide an integer-division operator that would behave consistently between Python 2 and Python 3. This means:

| context                                | `/` behavior   | `//` behavior |
---------------------------------------------------------------------------
| floating-point arguments, Python 2 & 3 | float division | int divison   |
---------------------------------------------------------------------------
| integer arguments, python 2            | int division   | int division  |
---------------------------------------------------------------------------
| integer arguments, python 3            | float division | int division  |

For more details, see this question: Division in Python 2.7. and 3.3

Handling click events on a drawable within an EditText

Actually you don't need to extend any class. Let's say I have an EditText editComment with a drawableRight

editComment.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        final int DRAWABLE_LEFT = 0;
        final int DRAWABLE_TOP = 1;
        final int DRAWABLE_RIGHT = 2;
        final int DRAWABLE_BOTTOM = 3;

        if(event.getAction() == MotionEvent.ACTION_UP) {
            if(event.getRawX() >= (editComment.getRight() - editComment.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                // your action here

                return true;
            }
        }
        return false;
    }
});

we getRawX() because we want to get the actual position of touch on screen, not relative to parent.

To get left side click

if(event.getRawX() <= (editComment.getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width())) 

How to execute a Windows command on a remote PC?

This can be done by using PsExec which can be downloaded here

psexec \\computer_name -u username -p password ipconfig

If this isn't working try doing this :-

  1. Open RegEdit on your remote server.
  2. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System.

  3. Add a new DWORD value called LocalAccountTokenFilterPolicy

  4. Set its value to 1.
  5. Reboot your remote server.
  6. Try running PSExec again from your local server.

How can I change property names when serializing with Json.net?

There is still another way to do it, which is using a particular NamingStrategy, which can be applied to a class or a property by decorating them with [JSonObject] or [JsonProperty].

There are predefined naming strategies like CamelCaseNamingStrategy, but you can implement your own ones.

The implementation of different naming strategies can be found here: https://github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization

How to start an application using android ADB tools?

linux/mac users can also create a script to run an apk with something like the following:

create a file named "adb-run.sh" with these 3 lines:

pkg=$(aapt dump badging $1|awk -F" " '/package/ {print $2}'|awk -F"'" '/name=/ {print $2}')
act=$(aapt dump badging $1|awk -F" " '/launchable-activity/ {print $2}'|awk -F"'" '/name=/ {print $2}')
adb shell am start -n $pkg/$act

then "chmod +x adb-run.sh" to make it executable.

now you can simply:

adb-run.sh myapp.apk

The benefit here is that you don't need to know the package name or launchable activity name. Similarly, you can create "adb-uninstall.sh myapp.apk"

Note: This requires that you have aapt in your path. You can find it under the new build tools folder in the SDK.

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

jQuery get the rendered height of an element?

I made a simple code that doesn't even need JQuery and probably gonna help some people. It gets the total height of 'ID1' after loaded and use it on 'ID2'

function anyName(){
    var varname=document.getElementById('ID1').offsetHeight;
    document.getElementById('ID2').style.height=varname+'px';
}

Then just set the body to load it

<body onload='anyName()'>

Convert date to YYYYMM format

It's month 1, so you're getting an expected value. you'll have to zeropad the month (1 -> 01), as per this answer: How do I convert an int to a zero padded string in T-SQL?

Best way to update data with a RecyclerView adapter

Found following solution working for my similar problem:

private ExtendedHashMap mData = new ExtendedHashMap();
private  String[] mKeys;

public void setNewData(ExtendedHashMap data) {
    mData.putAll(data);
    mKeys = data.keySet().toArray(new String[data.size()]);
    notifyDataSetChanged();
}

Using the clear-command

mData.clear()

is not nessescary

Get Selected value from dropdown using JavaScript

Working jsbin: http://jsbin.com/ANAYeDU/4/edit

Main bit:

function answers()
{

var element = document.getElementById("mySelect");
var elementValue = element.value;

if(elementValue == "To measure time"){
  alert("Thats correct"); 
  }
}

Django development IDE

The Wing IDE is a good IDE to use!

How to set background image in Java?

Or try this ;)

try {
  this.setContentPane(
    new JLabel(new ImageIcon(ImageIO.read(new File("your_file.jpeg")))));
} catch (IOException e) {};

Can't use Swift classes inside Objective-C

I had the same problem and finally it appeared that they weren't attached to the same targets. The ObjC class is attached to Target1 and Target2, the Swift class is only attached to the Target1 and is not visible inside the ObjC class.

Hope this helps someone.

Using 'sudo apt-get install build-essentials'

I know this has been answered, but I had the same question and this is what I needed to do to resolve it. During installation, I had not added a network mirror, so I had to add information about where a repo was on the internet. To do this, I ran:

sudo vi /etc/apt/sources.list

and added the following lines:

deb http://ftp.debian.org/debian wheezy main
deb-src http://ftp.debian.org/debian wheezy main

If you need to do this, you may need to replace "wheezy" with the version of debian you're running. Afterwards, run:

sudo apt-get update
sudo apt-get install build-essential

Hopefully this will help someone who had the same problem that I did.

Iterate through dictionary values?

You can just look for the value that corresponds with the key and then check if the input is equal to the key.

for key in PIX0:
    NUM = input("Which standard has a resolution of %s " % PIX0[key])
    if NUM == key:

Also, you will have to change the last line to fit in, so it will print the key instead of the value if you get the wrong answer.

print("I'm sorry but thats wrong. The correct answer was: %s." % key )

Also, I would recommend using str.format for string formatting instead of the % syntax.

Your full code should look like this (after adding in string formatting)

PIX0 = {"QVGA":"320x240", "VGA":"640x480", "SVGA":"800x600"}

for key in PIX0:
    NUM = input("Which standard has a resolution of {}".format(PIX0[key]))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but that's wrong. The correct answer was: {}.".format(key))

Notice: Undefined offset: 0 in

its just a warning use:

error_reporting(0);

it shows when we do not initialize array and direct assigning value to indexes.

somefunction{
$raja[0]="this";
$raja[1]="that";
}

instead :

somefunction{
$raja=array(0=>'this',1='that');
//or
$raja=array("this","that");
}

it just notification, do not generate any output error or any unexpected output.

SQL Server: Extract Table Meta-Data (description, fields and their data types)

Check this out:

SELECT TABLE_SCHEMA ,
       TABLE_NAME ,
       COLUMN_NAME ,
       ORDINAL_POSITION ,
       COLUMN_DEFAULT ,
       DATA_TYPE ,
       CHARACTER_MAXIMUM_LENGTH ,
       NUMERIC_PRECISION ,
       NUMERIC_PRECISION_RADIX ,
       NUMERIC_SCALE ,
       DATETIME_PRECISION
FROM   INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA in ('dbo','meta')
and table_name in (select name from sys.tables)
order by TABLE_SCHEMA ,       TABLE_NAME ,ORDINAL_POSITION

enter image description here

Accessing localhost:port from Android emulator

If you are using IIS Express you may need to bind to all hostnames instead of just `localhost'. Check this fine answer:

https://stackoverflow.com/a/15809698/383761

Tell IIS Express itself to bind to all ip addresses and hostnames. In your .config file (typically %userprofile%\My Documents\IISExpress\config\applicationhost.config, or $(solutionDir).vs\config\applicationhost.config for Visual Studio 2015), find your site's binding element, and add

<binding protocol="http" bindingInformation="*:8080:*" />

Make sure to add it as a second binding instead of modifying the existing one or VS will just re-add a new site appended with a (1) Also, you may need to run VS as an administrator.

Bundle ID Suffix? What is it?

If you don't have a company, leave your name, it doesn't matter as long as both bundle id in info.plist file and the one you've submitted in iTunes Connect match.

In Bundle ID Suffix you should write full name of bundle ID.

Example:

Bundle ID suffix = thebestapp (NOT CORRECT!!!!)

Bundle ID suffix = com.awesomeapps.thebestapp (CORRECT!!)

The reason for this is explained in the Developer Portal:

The App ID string contains two parts separated by a period (.) — an App ID Prefix (your Team ID by default, e.g. ABCDE12345), and an App ID Suffix (a Bundle ID search string, e.g. com.mycompany.appname). [emphasis added]

So in this case the suffix is the full string com.awesomeapps.thebestapp.

Android Studio - Failed to notify project evaluation listener error

I enabled "Offline-Work" under File -> Settings ->Build,Deploy, Exec -> Gradle And this finally resolved the issue for me.

How to tell if a JavaScript function is defined

Those methods to tell if a function is implemented also fail if variable is not defined so we are using something more powerful that supports receiving an string:

function isFunctionDefined(functionName) {
    if(eval("typeof(" + functionName + ") == typeof(Function)")) {
        return true;
    }
}

if (isFunctionDefined('myFunction')) {
    myFunction(foo);
}

How to create empty folder in java?

Looks file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml

// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
    // Directory creation failed
}

How to drop all tables from the database with manage.py CLI in Django?

If you are using psql and have django-more 2.0.0 installed, you can do

manage.py reset_schema

Sort a list of numerical strings in ascending order

in python sorted works like you want with integers:

>>> sorted([10,3,2])
[2, 3, 10]

it looks like you have a problem because you are using strings:

>>> sorted(['10','3','2'])
['10', '2', '3']

(because string ordering starts with the first character, and "1" comes before "2", no matter what characters follow) which can be fixed with key=int

>>> sorted(['10','3','2'], key=int)
['2', '3', '10']

which converts the values to integers during the sort (it is called as a function - int('10') returns the integer 10)

and as suggested in the comments, you can also sort the list itself, rather than generating a new one:

>>> l = ['10','3','2']
>>> l.sort(key=int)
>>> l
['2', '3', '10']

but i would look into why you have strings at all. you should be able to save and retrieve integers. it looks like you are saving a string when you should be saving an int? (sqlite is unusual amongst databases, in that it kind-of stores data in the same type as it is given, even if the table column type is different).

and once you start saving integers, you can also get the list back sorted from sqlite by adding order by ... to the sql command:

select temperature from temperatures order by temperature;

How to get the bluetooth devices as a list?

package com.sekurtrack.myapplication;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    ListView listView;
    private BluetoothAdapter BA;
    private ArrayList<String> mDeviceList = new ArrayList<String>();
    private Set<BluetoothDevice> pairedDevices;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=(ListView)findViewById(R.id.devicesList);



        BA = BluetoothAdapter.getDefaultAdapter();
        BA.startDiscovery();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

       /* BA = BluetoothAdapter.getDefaultAdapter();
        pairedDevices = BA.getBondedDevices();
        ArrayList list = new ArrayList();
        for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
        Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
        final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
        listView.setAdapter(adapter);*/

    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mDeviceList.add(device.getName() + "\n" + device.getAddress());
                Log.i("BT1", device.getName() + "\n" + device.getAddress());
                listView.setAdapter(new ArrayAdapter<String>(context,
                        android.R.layout.simple_list_item_1, mDeviceList));
            }
        }
    };
}

You have not accepted the license agreements of the following SDK components

I ran across this error when i ran cordova build android

I solved this issue by firing ./sdkmanager --licenses and accepting all the licenses.

  1. You have a sdkmanager.bat under the android sdk folder in the path: android/sdk/tools/bin
  2. To trigger that open a command prompt in android/sdk/tools/bin
  3. type ./sdkmanager --licenses and enter
  4. Press y to review all licenses and then press y to accept all licenses

Git - remote: Repository not found

I'm facing same issue and resolving through

git add .

git commit -m "message"

git remote set-url origin https://[email protected]/aceofwings/RotairERP.git

then

git pull

How to create a JPA query with LEFT OUTER JOIN

Normally the ON clause comes from the mapping's join columns, but the JPA 2.1 draft allows for additional conditions in a new ON clause.

See,

http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#ON

Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8

If you make an AJAX request with fetch, the response isn't shown unless it's read with .text(), .json(), etc.

If you just do:

 r = fetch("/some-path");

the response won't be shown in dev tools.
It shows up after you run:

r.then(r => r.text())

Import Maven dependencies in IntelliJ IDEA

If certain maven modules are not compiling check if their pom.xml is on the "ignored files" list. In IntelliJ goto

preferences -> project settings -> maven -> ignored files

and check if the related pom.xml is ignored.

How can I plot separate Pandas DataFrames as subplots?

How to create multiple plots from a dictionary of dataframes with long (tidy) data

  • Assumptions

    • There is a dictionary of multiple dataframes of tidy data
      • Created by reading in from files
      • Created by separating a single dataframe into multiple dataframes
    • The categories, cat, may be overlapping, but all dataframes may not contain all values of cat
    • hue='cat'
  • Because dataframes are being iterated through, there's not guarantee that colors will be mapped the same for each plot

    • A custom color map needs to be created from the unique 'cat' values for all the dataframes
    • Since the colors will be the same, place one legend to the side of the plots, instead of a legend in every plot

Imports and synthetic data

import pandas as pd
import numpy as np  # used for random data
import random  # used for random data
import matplotlib.pyplot as plt
from matplotlib.patches import Patch  # for custom legend
import seaborn as sns
import math import ceil  # determine correct number of subplot


# synthetic data
df_dict = dict()
for i in range(1, 7):
    np.random.seed(i)
    random.seed(i)
    data_length = 100
    data = {'cat': [random.choice(['A', 'B', 'C']) for _ in range(data_length)],
            'x': np.random.rand(data_length),
            'y': np.random.rand(data_length)}
    df_dict[i] = pd.DataFrame(data)


# display(df_dict[1].head())

  cat         x         y
0   A  0.417022  0.326645
1   C  0.720324  0.527058
2   A  0.000114  0.885942
3   B  0.302333  0.357270
4   A  0.146756  0.908535

Create color mappings and plot

# create color mapping based on all unique values of cat
unique_cat = {cat for v in df_dict.values() for cat in v.cat.unique()}  # get unique cats
colors = sns.color_palette('husl', n_colors=len(unique_cat))  # get a number of colors
cmap = dict(zip(unique_cat, colors))  # zip values to colors

# iterate through dictionary and plot
col_nums = 3  # how many plots per row
row_nums = math.ceil(len(df_dict) / col_nums)  # how many rows of plots
plt.figure(figsize=(10, 5))  # change the figure size as needed
for i, (k, v) in enumerate(df_dict.items(), 1):
    plt.subplot(row_nums, col_nums, i)  # create subplots
    p = sns.scatterplot(data=v, x='x', y='y', hue='cat', palette=cmap)
    p.legend_.remove()  # remove the individual plot legends
    plt.title(f'DataFrame: {k}')

plt.tight_layout()
# create legend from cmap
patches = [Patch(color=v, label=k) for k, v in cmap.items()]
# place legend outside of plot; change the right bbox value to move the legend up or down
plt.legend(handles=patches, bbox_to_anchor=(1.06, 1.2), loc='center left', borderaxespad=0)
plt.show()

enter image description here

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

To open the back camera:-

val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA)

To open the front camera:-

val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
when {
     Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.O -> {
         cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT)  // Tested on API 24 Android version 7.0(Samsung S6)
     }
     Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
         cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT) // Tested on API 27 Android version 8.0(Nexus 6P)
         cameraIntent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true)
     }
     else -> cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", 1)  // Tested API 21 Android version 5.0.1(Samsung S4)
}
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA)

I could not make it work for API 28 and above. Also, opening the front camera directly is not possible in some devices(depends on the manufacturer).

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

Being aware of the transaction (autocommit, explicit and implicit) handling for your database can save you from having to restore data from a backup.

Transactions control data manipulation statement(s) to ensure they are atomic. Being "atomic" means the transaction either occurs, or it does not. The only way to signal the completion of the transaction to database is by using either a COMMIT or ROLLBACK statement (per ANSI-92, which sadly did not include syntax for creating/beginning a transaction so it is vendor specific). COMMIT applies the changes (if any) made within the transaction. ROLLBACK disregards whatever actions took place within the transaction - highly desirable when an UPDATE/DELETE statement does something unintended.

Typically individual DML (Insert, Update, Delete) statements are performed in an autocommit transaction - they are committed as soon as the statement successfully completes. Which means there's no opportunity to roll back the database to the state prior to the statement having been run in cases like yours. When something goes wrong, the only restoration option available is to reconstruct the data from a backup (providing one exists). In MySQL, autocommit is on by default for InnoDB - MyISAM doesn't support transactions. It can be disabled by using:

SET autocommit = 0

An explicit transaction is when statement(s) are wrapped within an explicitly defined transaction code block - for MySQL, that's START TRANSACTION. It also requires an explicitly made COMMIT or ROLLBACK statement at the end of the transaction. Nested transactions is beyond the scope of this topic.

Implicit transactions are slightly different from explicit ones. Implicit transactions do not require explicity defining a transaction. However, like explicit transactions they require a COMMIT or ROLLBACK statement to be supplied.

Conclusion

Explicit transactions are the most ideal solution - they require a statement, COMMIT or ROLLBACK, to finalize the transaction, and what is happening is clearly stated for others to read should there be a need. Implicit transactions are OK if working with the database interactively, but COMMIT statements should only be specified once results have been tested & thoroughly determined to be valid.

That means you should use:

SET autocommit = 0;

START TRANSACTION;
  UPDATE ...;

...and only use COMMIT; when the results are correct.

That said, UPDATE and DELETE statements typically only return the number of rows affected, not specific details. Convert such statements into SELECT statements & review the results to ensure correctness prior to attempting the UPDATE/DELETE statement.

Addendum

DDL (Data Definition Language) statements are automatically committed - they do not require a COMMIT statement. IE: Table, index, stored procedure, database, and view creation or alteration statements.

How to always show scrollbar

As of now the best way is to use android:fadeScrollbars="false" in xml which is equivalent to ScrollView.setScrollbarFadingEnabled(false); in java code.

Deleting Objects in JavaScript

The delete operator deletes only a reference, never an object itself. If it did delete the object itself, other remaining references would be dangling, like a C++ delete. (And accessing one of them would cause a crash. To make them all turn null would mean having extra work when deleting or extra memory for each object.)

Since Javascript is garbage collected, you don't need to delete objects themselves - they will be removed when there is no way to refer to them anymore.

It can be useful to delete references to an object if you are finished with them, because this gives the garbage collector more information about what is able to be reclaimed. If references remain to a large object, this can cause it to be unreclaimed - even if the rest of your program doesn't actually use that object.

Converting string to tuple without splitting characters

Just in case someone comes here trying to know how to create a tuple assigning each part of the string "Quattro" and "TT" to an element of the list, it would be like this print tuple(a.split())

Nested attributes unpermitted parameters

From the docs

To whitelist an entire hash of parameters, the permit! method can be used

params.require(:log_entry).permit!

Nested attributes are in the form of a hash. In my app, I have a Question.rb model accept nested attributes for an Answer.rb model (where the user creates answer choices for a question he creates). In the questions_controller, I do this

  def question_params

      params.require(:question).permit!

  end

Everything in the question hash is permitted, including the nested answer attributes. This also works if the nested attributes are in the form of an array.

Having said that, I wonder if there's a security concern with this approach because it basically permits anything that's inside the hash without specifying exactly what it is, which seems contrary to the purpose of strong parameters.

check if a key exists in a bucket in s3 using boto3

For boto3, ObjectSummary can be used to check if an object exists.

Contains the summary of an object stored in an Amazon S3 bucket. This object doesn't contain contain the object's full metadata or any of its contents

import boto3
from botocore.errorfactory import ClientError
def path_exists(path, bucket_name):
    """Check to see if an object exists on S3"""
    s3 = boto3.resource('s3')
    try:
        s3.ObjectSummary(bucket_name=bucket_name, key=path).load()
    except ClientError as e:
        if e.response['Error']['Code'] == "404":
            return False
        else:
            raise e
    return True

path_exists('path/to/file.html')

In ObjectSummary.load

Calls s3.Client.head_object to update the attributes of the ObjectSummary resource.

This shows that you can use ObjectSummary instead of Object if you are planning on not using get(). The load() function does not retrieve the object it only obtains the summary.

How do I make XAML DataGridColumns fill the entire DataGrid?

I added a HorizontalAlignment="Center" (The default is "Strech") and it solved my problem because it made the datagrid only as wide as needed. (Removed the datagrid's Width setting if you have one.)

enter image description here

JFrame.dispose() vs System.exit()

System.exit(); causes the Java VM to terminate completely.

JFrame.dispose(); causes the JFrame window to be destroyed and cleaned up by the operating system. According to the documentation, this can cause the Java VM to terminate if there are no other Windows available, but this should really just be seen as a side effect rather than the norm.

The one you choose really depends on your situation. If you want to terminate everything in the current Java VM, you should use System.exit() and everything will be cleaned up. If you only want to destroy the current window, with the side effect that it will close the Java VM if this is the only window, then use JFrame.dispose().

How can git be installed on CENTOS 5.5?

I'm sure this question is about to die now that RHEL 5 is nearing end of life, but the answer seems to have gotten a lot simpler now:

sudo yum install epel-release
sudo yum install git

worked for me on a fresh install of CentOS 5.11.

How to merge 2 JSON objects from 2 files using jq?

Here's a version that works recursively (using *) on an arbitrary number of objects:

echo '{"A": {"a": 1}}' '{"A": {"b": 2}}' '{"B": 3}' |\
  jq --slurp 'reduce .[] as $item ({}; . * $item)'

{
  "A": {
    "a": 1,
    "b": 2
  },
  "B": 3
}

Is it possible to center text in select box?

_x000D_
_x000D_
select {_x000D_
  text-align: center;_x000D_
  text-align-last: center;_x000D_
}_x000D_
option {_x000D_
  text-align: left;_x000D_
}
_x000D_
<select>_x000D_
   <option value="">(please select a state)</option>_x000D_
   <option class="lt" value="--">none</option>_x000D_
   <option class="lt" value="AL">Alabama</option>_x000D_
   <option class="lt" value="AK">Alaska</option>_x000D_
   <option class="lt" value="AZ">Arizona</option>_x000D_
   <option class="lt" value="AR">Arkansas</option>_x000D_
   <option class="lt" value="CA">California</option>_x000D_
   <option class="lt" value="CO">Colorado</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Does --disable-web-security Work In Chrome Anymore?

Open target location of chrome and navigate through cmd type

chrome.exe --disable-web-security --user-data-dir=c:\my\dat

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

Preventing HTML and Script injections in Javascript

Use this,

function restrict(elem){
  var tf = _(elem);
  var rx = new RegExp;
  if(elem == "email"){
       rx = /[ '"]/gi;
  }else if(elem == "search" || elem == "comment"){
    rx = /[^a-z 0-9.,?]/gi;
  }else{
      rx =  /[^a-z0-9]/gi;
  }
  tf.value = tf.value.replace(rx , "" );
}

On the backend, for java , Try using StringUtils class or a custom script.

public static String HTMLEncode(String aTagFragment) {
        final StringBuffer result = new StringBuffer();
        final StringCharacterIterator iterator = new
                StringCharacterIterator(aTagFragment);
        char character = iterator.current();
        while (character != StringCharacterIterator.DONE )
        {
            if (character == '<')
                result.append("&lt;");
            else if (character == '>')
                result.append("&gt;");
            else if (character == '\"')
                result.append("&quot;");
            else if (character == '\'')
                result.append("&#039;");
            else if (character == '\\')
                result.append("&#092;");
            else if (character == '&')
                result.append("&amp;");
            else {
            //the char is not a special one
            //add it to the result as is
                result.append(character);
            }
            character = iterator.next();
        }
        return result.toString();
    }

jQuery duplicate DIV into another DIV

You'll want to use the clone() method in order to get a deep copy of the element:

$(function(){
  var $button = $('.button').clone();
  $('.package').html($button);
});

Full demo: http://jsfiddle.net/3rXjx/

From the jQuery docs:

The .clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes. When used in conjunction with one of the insertion methods, .clone() is a convenient way to duplicate elements on a page.

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

I encountered a similar problem using windows command line for R script, Rscript.exe, which is very sensitive to spaces in the path. The solution was to create a virtual path to the binary folder using the windows subst command.

The following fails: "C:\Program Files\R\R-3.4.0\bin\Rscript.exe"

Doing following succeeds:

subst Z: "C:\Program Files\R\R-3.4.0"
Z:\bin\Rscript.exe

The reason the above-proposed solutions didn't work, evidently, has to do with the Rscript.exe executable's own internal path resolution from its working directory (which has a space in it) rather the windows command line being confused with the space. So using ~ or " to resolve the issue at the command line is moot. The executable must be called within a path lacking spaces.

How to resume Fragment from BackStack if exists

getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {

    @Override
    public void onBackStackChanged() {

        if(getFragmentManager().getBackStackEntryCount()==0) {
            onResume();
        }    
    }
});

Disable a Button

Disable a button on Swift 3:

yourButton.isEnabled = false

Copying an array of objects into another array in javascript

The key things here are

  1. The entries in the array are objects, and
  2. You don't want modifications to an object in one array to show up in the other array.

That means we need to not just copy the objects to a new array (or a target array), but also create copies of the objects.

If the destination array doesn't exist yet...

...use map to create a new array, and copy the objects as you go:

const newArray = sourceArray.map(obj => /*...create and return copy of `obj`...*/);

...where the copy operation is whatever way you prefer to copy objects, which varies tremendously project to project based on use case. That topic is covered in depth in the answers to this question. But for instance, if you only want to copy the objects but not any objects their properties refer to, you could use spread notation (ES2015+):

const newArray = sourceArray.map(obj => ({...obj}));

That does a shallow copy of each object (and of the array). Again, for deep copies, see the answers to the question linked above.

Here's an example using a naive form of deep copy that doesn't try to handle edge cases, see that linked question for edge cases:

_x000D_
_x000D_
function naiveDeepCopy(obj) {
    const newObj = {};
    for (const key of Object.getOwnPropertyNames(obj)) {
        const value = obj[key];
        if (value && typeof value === "object") {
            newObj[key] = {...value};
        } else {
            newObj[key] = value;
        }
    }
    return newObj;
}
const sourceArray = [
    {
        name: "joe",
        address: {
            line1: "1 Manor Road",
            line2: "Somewhere",
            city: "St Louis",
            state: "Missouri",
            country: "USA",
        },
    },
    {
        name: "mohammed",
        address: {
            line1: "1 Kings Road",
            city: "London",
            country: "UK",
        },
    },
    {
        name: "shu-yo",
    },
];
const newArray = sourceArray.map(naiveDeepCopy);
// Modify the first one and its sub-object
newArray[0].name = newArray[0].name.toLocaleUpperCase();
newArray[0].address.country = "United States of America";
console.log("Original:", sourceArray);
console.log("Copy:", newArray);
_x000D_
.as-console-wrapper {
    max-height: 100% !important;
}
_x000D_
_x000D_
_x000D_

If the destination array exists...

...and you want to append the contents of the source array to it, you can use push and a loop:

for (const obj of sourceArray) {
    destinationArray.push(copy(obj));
}

Sometimes people really want a "one liner," even if there's no particular reason for it. If you refer that, you could create a new array and then use spread notation to expand it into a single push call:

destinationArray.push(...sourceArray.map(obj => copy(obj)));

How to store Emoji Character in MySQL Database

My answer only adds to Selvamani P answer.

You might also need to change any SET NAMES utf8 queries with SET NAMES utf8mb4. That did the trick for me.

Also, this is a great article to port your website from utf8 to utf8mb4. In particular the article makes 2 good points on indexes and repairing tables after converting them to utf8mb4:

INDEXES

When converting from utf8 to utf8mb4, the maximum length of a column or index key is unchanged in terms of bytes. Therefore, it is smaller in terms of characters, because the maximum length of a character is now four bytes instead of three. [...] The InnoDB storage engine has a maximum index length of 767 bytes, so for utf8 or utf8mb4 columns, you can index a maximum of 255 or 191 characters, respectively. If you currently have utf8 columns with indexes longer than 191 characters, you will need to index a smaller number of characters when using utf8mb4.

REPAIRING TABLES

After upgrading the MySQL server and making the necessary changes explained above, make sure to repair and optimize all databases and tables. I didn’t do this right away after upgrading (I didn’t think it was necessary, as everything seemed to work fine at first glance), and ran into some weird bugs where UPDATE statements didn’t have any effect, even though no errors were thrown.

Read more about the queries to repair tables on the article.

HMAC-SHA256 Algorithm for signature calculation

Here is my solution:

public static String encode(String key, String data) throws Exception {
  Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
  SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
  sha256_HMAC.init(secret_key);

  return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
}

public static void main(String [] args) throws Exception {
  System.out.println(encode("key", "The quick brown fox jumps over the lazy dog"));
}

Or you can return the hash encoded in Base64:

Base64.encodeBase64String(sha256_HMAC.doFinal(data.getBytes("UTF-8")));

The output in hex is as expected:

f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8

How to start IIS Express Manually

Or you simply manage it like full IIS by using Jexus Manager for IIS Express, an open source project I work on

https://jexusmanager.com

Jexus Manager for IIS Express

Start a site and the process will be launched for you.

generate model using user:references vs user_id:integer

For the former, convention over configuration. Rails default when you reference another table with

 belongs_to :something

is to look for something_id.

references, or belongs_to is actually newer way of writing the former with few quirks.

Important is to remember that it will not create foreign keys for you. In order to do that, you need to set it up explicitly using either:

t.references :something, foreign_key: true
t.belongs_to :something_else, foreign_key: true

or (note the plural):

add_foreign_key :table_name, :somethings
add_foreign_key :table_name, :something_elses`

Loop code for each file in a directory

Use the glob function in a foreach loop to do whatever is an option. I also used the file_exists function in the example below to check if the directory exists before going any further.

$directory = 'my_directory/';
$extension = '.txt';

if ( file_exists($directory) ) {
   foreach ( glob($directory . '*' . $extension) as $file ) {
      echo $file;
   }
}
else {
   echo 'directory ' . $directory . ' doesn\'t exist!';
}

Why does "pip install" inside Python raise a SyntaxError?

you need to type it in cmd not in the IDLE. becuse IDLE is not an command prompt if you want to install something from IDLE type this

>>>from pip.__main__ import _main as main
>>>main(#args splitted by space in list example:['install', 'requests'])

this is calling pip like pip <commands> in terminal. The commands will be seperated by spaces that you are doing there to.

HTTP authentication logout via PHP

AFAIK, there's no clean way to implement a "logout" function when using htaccess (i.e. HTTP-based) authentication.

This is because such authentication uses the HTTP error code '401' to tell the browser that credentials are required, at which point the browser prompts the user for the details. From then on, until the browser is closed, it will always send the credentials without further prompting.

Focus Next Element In Tab Index

I checked above solutions and found them quite lengthy. It can be accomplished with just one line of code:

currentElement.nextElementSibling.focus();

or

currentElement.previousElementSibling.focus();

here currentElement may be any i.e. document.activeElement or this if current element is in function's context.

I tracked tab and shift-tab events with keydown event Here is a snippet that relies on "JQuery":

let cursorDirection = ''
$(document).keydown(function (e) {
    let key = e.which || e.keyCode;
    if (e.shiftKey) {
        //does not matter if user has pressed tab key or not.
        //If it matters for you then compare it with 9
        cursorDirection = 'prev';
    }
    else if (key == 9) {
        //if tab key is pressed then move next.
        cursorDirection = 'next';
    }
    else {
        cursorDirection == '';
    }
});

once you have cursor direction then you can use nextElementSibling.focus or previousElementSibling.focus methods

How to call Android contacts list?

I'm not 100% sure what your sample code is supposed to do, but the following snippet should help you 'call the contacts list function, pick a contact, then return to [your] app with the contact's name'.

There are three steps to this process.

1. Permissions

Add a permission to read contacts data to your application manifest.

<uses-permission android:name="android.permission.READ_CONTACTS"/>

2. Calling the Contact Picker

Within your Activity, create an Intent that asks the system to find an Activity that can perform a PICK action from the items in the Contacts URI.

Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);

Call startActivityForResult, passing in this Intent (and a request code integer, PICK_CONTACT in this example). This will cause Android to launch an Activity that's registered to support ACTION_PICK on the People.CONTENT_URI, then return to this Activity when the selection is made (or canceled).

startActivityForResult(intent, PICK_CONTACT);

3. Listening for the Result

Also in your Activity, override the onActivityResult method to listen for the return from the 'select a contact' Activity you launched in step 2. You should check that the returned request code matches the value you're expecting, and that the result code is RESULT_OK.

You can get the URI of the selected contact by calling getData() on the data Intent parameter. To get the name of the selected contact you need to use that URI to create a new query and extract the name from the returned cursor.

@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
  super.onActivityResult(reqCode, resultCode, data);

  switch (reqCode) {
    case (PICK_CONTACT) :
      if (resultCode == Activity.RESULT_OK) {
        Uri contactData = data.getData();
        Cursor c =  getContentResolver().query(contactData, null, null, null, null);
        if (c.moveToFirst()) {
          String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
          // TODO Whatever you want to do with the selected contact name.
        }
      }
      break;
  }
}

Full source code: tutorials-android.blogspot.com (how to call android contacts list).

Should I use `import os.path` or `import os`?

Interestingly enough, importing os.path will import all of os. try the following in the interactive prompt:

import os.path
dir(os)

The result will be the same as if you just imported os. This is because os.path will refer to a different module based on which operating system you have, so python will import os to determine which module to load for path.

reference

With some modules, saying import foo will not expose foo.bar, so I guess it really depends the design of the specific module.


In general, just importing the explicit modules you need should be marginally faster. On my machine:

import os.path: 7.54285810068e-06 seconds

import os: 9.21904878972e-06 seconds

These times are close enough to be fairly negligible. Your program may need to use other modules from os either now or at a later time, so usually it makes sense just to sacrifice the two microseconds and use import os to avoid this error at a later time. I usually side with just importing os as a whole, but can see why some would prefer import os.path to technically be more efficient and convey to readers of the code that that is the only part of the os module that will need to be used. It essentially boils down to a style question in my mind.

SQL Server : GROUP BY clause to get comma-separated values

try this:

SELECT ReportId, Email = 
    STUFF((SELECT ', ' + Email
           FROM your_table b 
           WHERE b.ReportId = a.ReportId 
          FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId


SQL fiddle demo

Difference between 'struct' and 'typedef struct' in C++?

There is a difference, but subtle. Look at it this way: struct Foo introduces a new type. The second one creates an alias called Foo (and not a new type) for an unnamed struct type.

7.1.3 The typedef specifier

1 [...]

A name declared with the typedef specifier becomes a typedef-name. Within the scope of its declaration, a typedef-name is syntactically equivalent to a keyword and names the type associated with the identifier in the way described in Clause 8. A typedef-name is thus a synonym for another type. A typedef-name does not introduce a new type the way a class declaration (9.1) or enum declaration does.

8 If the typedef declaration defines an unnamed class (or enum), the first typedef-name declared by the declaration to be that class type (or enum type) is used to denote the class type (or enum type) for linkage purposes only (3.5). [ Example:

typedef struct { } *ps, S; // S is the class name for linkage purposes

So, a typedef always is used as an placeholder/synonym for another type.

IE8 css selector

In the light of the evolving thread, see below for a more complete answer:

IE 6

* html .ie6 {property:value;}

or

.ie6 { _property:value;}

IE 7

*+html .ie7 {property:value;}

or

*:first-child+html .ie7 {property:value;}

IE 6 and 7

@media screen\9 {
    .ie67 {property:value;}
}

or

.ie67 { *property:value;}

or

.ie67 { #property:value;}

IE 6, 7 and 8

@media \0screen\,screen\9 {
    .ie678 {property:value;}
}

IE 8

html>/**/body .ie8 {property:value;}

or

@media \0screen {
    .ie8 {property:value;}
}

IE 8 Standards Mode Only

.ie8 { property /*\**/: value\9 }

IE 8,9 and 10

@media screen\0 {
    .ie8910 {property:value;}
}

IE 9 only

@media screen and (min-width:0) and (min-resolution: .001dpcm) { 
 // IE9 CSS
 .ie9{property:value;}
}

IE 9 and above

@media screen and (min-width:0) and (min-resolution: +72dpi) {
  // IE9+ CSS
  .ie9up{property:value;}
}

IE 9 and 10

@media screen and (min-width:0) {
    .ie910{property:value;}
}

IE 10 only

_:-ms-lang(x), .ie10 { property:value\9; }

IE 10 and above

_:-ms-lang(x), .ie10up { property:value; }

or

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
   .ie10up{property:value;}
}

IE 11 (and above..)

_:-ms-fullscreen, :root .ie11up { property:value; }

Javascript alternatives

Modernizr

Modernizr runs quickly on page load to detect features; it then creates a JavaScript object with the results, and adds classes to the html element

User agent selection

The Javascript:

var b = document.documentElement;
        b.setAttribute('data-useragent',  navigator.userAgent);
        b.setAttribute('data-platform', navigator.platform );
        b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');

Adds (e.g) the below to the html element:

data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'

Allowing very targetted CSS selectors, e.g.:

html[data-useragent*='Chrome/13.0'] .nav{
    background:url(img/radial_grad.png) center bottom no-repeat;
}

Footnote

If possible, avoid browser targeting. Identify and fix any issue(s) you identify. Support progressive enhancement and graceful degradation. With that in mind, this is an 'ideal world' scenario not always obtainable in a production environment, as such- the above should help provide some good options.


Attribution / Essential Reading