Programs & Examples On #Mailer

require(vendor/autoload.php): failed to open stream

First, review route inside index.php

require __DIR__.'/../vendor/autoload.php';

$app = require_once __DIR__.'/../bootstrap/app.php';

in my case the route did not work, I had to review the directories.

How to insert TIMESTAMP into my MySQL table?

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

You can use this Query. CURRENT_TIMESTAMP

Remember to use the parenthesis CURRENT_TIMESTAMP()

Failed to authenticate on SMTP server error using gmail

If you still get this error when sending email: "Failed to authenticate on SMTP server with username "[email protected]" using 3 possible authenticators"

You may try one of these methods:

  1. Go to https://accounts.google.com/UnlockCaptcha, click continue and unlock your account for access through other media/sites.

  2. Using a double quote password: "your password" <-- this one also solved my problem.

What does the ELIFECYCLE Node.js error mean?

Likewise, I saw this error as a result of too little RAM. I cranked up the RAM on the VM and the error disappeared.

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

'default' => env('DB_CONNECTION', 'mysql'),

add this in your code

Fatal error: Class 'PHPMailer' not found

I suggest you look into getting composer. https://getcomposer.org Composer makes getting third-party libraries a LOT easier and using a single autoloader for all of them. It also standardizes on where all your dependencies are located, along with some automatization capabilities.

Download https://getcomposer.org/composer.phar to C:\Inetpub\wwwroot\php

Delete your C:\Inetpub\wwwroot\php\PHPMailer\ directory.

Use composer.phar to get the phpmailer package using the command line to execute

cd C:\Inetpub\wwwroot\php
php composer.phar require phpmailer/phpmailer

After it is finished it will create a C:\Inetpub\wwwroot\php\vendor directory along with all of the phpmailer files and generate an autoloader.

Next in your main project configuration file you need to include the autoload file.

require_once 'C:\Inetpub\wwwroot\php\vendor\autoload.php';

The vendor\autoload.php will include the information for you to use $mail = new \PHPMailer;

Additional information on the PHPMailer package can be found at https://packagist.org/packages/phpmailer/phpmailer

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

In my case, my problem was environmental. Meaning, I did something wrong in my bash session. After attempting nearly everything in this thread, I opened a new bash session and everything was back to normal.

535-5.7.8 Username and Password not accepted

UPDATE:

Notice: This setting is not available for accounts with 2-Step Verification enabled, which mean you have to disable 2 factor authentication.

enter image description here

If you disable the 2-Step Verification:

enter image description here

SMTP connect() failed PHPmailer - PHP

I fixed it ...

https://github.com/PHPMailer/PHPMailer/tree/5.2-stable

_x000D_
_x000D_
<?php_x000D_
require 'PHPMailerAutoload.php';_x000D_
_x000D_
$mail = new PHPMailer;_x000D_
_x000D_
//$mail->SMTPDebug = 3;                               // Enable verbose debug output_x000D_
_x000D_
$mail->isSMTP();                                      // Set mailer to use SMTP_x000D_
$mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers_x000D_
$mail->SMTPAuth = true;                               // Enable SMTP authentication_x000D_
$mail->Username = '[email protected]';                 // SMTP username_x000D_
$mail->Password = 'pass';                           // SMTP password_x000D_
//$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted_x000D_
$mail->Port = 25;                                    // TCP port to connect to_x000D_
_x000D_
$mail->setFrom('[email protected]', 'Mailer');_x000D_
$mail->addAddress('[email protected]', 'User');     // Add a recipient_x000D_
_x000D_
$mail->isHTML(true);                                  // Set email format to HTML_x000D_
_x000D_
$mail->Subject = 'Here is the subject';_x000D_
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';_x000D_
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';_x000D_
_x000D_
if(!$mail->send()) {_x000D_
    echo 'Message could not be sent.';_x000D_
    echo 'Mailer Error: ' . $mail->ErrorInfo;_x000D_
} else {_x000D_
    echo 'Message has been sent';_x000D_
}
_x000D_
_x000D_
_x000D_

Turn on access and enjoy..! That is on Gmail account setting.

Turn On access

PHPMailer - SMTP ERROR: Password command failed when send mail from my server

Just in caser anyone ends here like me. In may case despite having enabled unsecure access to my google account, it refused to send the email throwing an SMTP ERROR: Password command failed: 534-5.7.14.

(Solution found at https://know.mailsbestfriend.com/smtp_error_password_command_failed_5345714-1194946499.shtml)

Steps:

  1. log into your google account

  2. Go to https://accounts.google.com/b/0/DisplayUnlockCaptcha and click continue to enable.

  3. Setup your phpmailer as smtp with ssl:

    $mail = new PHPMailer(true);
    
    $mail->CharSet  ="utf-8";
    $mail->SMTPDebug = SMTP::DEBUG_SERVER; // or 0 for no debuggin at all        
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 465; 
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; 
    $mail->SMTPAuth   = true;
    $mail->Username = 'yourgmailaccount';
    $mail->Password = 'yourpassword';
    

And the other $mail object properties as needed.

Hope it helps someone!!

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. when email is in a variable

I had very similar problem today and solution was as it is..

$email = Array("Zaffar Saffee" => "[email protected]");
        $schedule->command('cmd:mycmd')
                 ->everyMinute()
                 ->sendOutputTo("/home/forge/dev.mysite.com/storage/logs/cron.log")
                 ->emailWrittenOutputTo($email);

It laravel 5.2 though...

my basic problem was , I was passing string instead of array so, error was

->emailWrittenOutputTo('[email protected]'); // string, we need an array

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

I also came across this problem. Google detected my Mac as a new device and blocked it. To unblock, in a web browser log in to your Google account and go to "Account Settings".

Scroll down and you'll find "Recent activities". Click just below that on "Devices".

Your device will be listed. Okay your device. SMTP started working for me after I did this and lowered the protection as mentioned above.

Nodemailer with Gmail and NodeJS

You should use an XOAuth2 token to connect to Gmail. No worries, Nodemailer already knows about that:

var smtpTransport = nodemailer.createTransport('SMTP', {
    service: 'Gmail',
    auth: {
      XOAuth2: {
        user: smtpConfig.user,
        clientId: smtpConfig.client_id,
        clientSecret: smtpConfig.client_secret,
        refreshToken: smtpConfig.refresh_token,
        accessToken: smtpConfig.access_token,
        timeout: smtpConfig.access_timeout - Date.now()
      }
    }
  };

You'll need to go to the Google Cloud Console to register your app. Then you need to retrieve access tokens for the accounts you wish to use. You can use passportjs for that.

Here's how it looks in my code:

var passport = require('passport'),
    GoogleStrategy = require('./google_oauth2'),
    config = require('../config');

passport.use('google-imap', new GoogleStrategy({
  clientID: config('google.api.client_id'),
  clientSecret: config('google.api.client_secret')
}, function (accessToken, refreshToken, profile, done) {
  console.log(accessToken, refreshToken, profile);
  done(null, {
    access_token: accessToken,
    refresh_token: refreshToken,
    profile: profile
  });
}));

exports.mount = function (app) {
  app.get('/add-imap/:address?', function (req, res, next) {
    passport.authorize('google-imap', {
        scope: [
          'https://mail.google.com/',
          'https://www.googleapis.com/auth/userinfo.email'
        ],
        callbackURL: config('web.vhost') + '/add-imap',
        accessType: 'offline',
        approvalPrompt: 'force',
        loginHint: req.params.address
      })(req, res, function () {
        res.send(req.user);
      });
  });
};

How to configure SMTP settings in web.config

Set IIS to forward your mail to the remote server. The specifics vary greatly depending on the version of IIS. For IIS 7.5:

  1. Open IIS Manager
  2. Connect to your server if needed
  3. Select the server node; you should see an SMTP option on the right in the ASP.NET section
  4. Double-click the SMTP icon.
  5. Select the "Deliver e-mail to SMTP server" option and enter your server name, credentials, etc.

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

[sendmail]

smtp_server=smtp.gmail.com  
smtp_port=25  
error_logfile=error.log  
debug_logfile=debug.log  
[email protected] 
auth_password=gmailpassword  
[email protected]

need authenticate username and password of mail then only once can successfully send mail from localhost

Mail not sending with PHPMailer over SSL using SMTP

$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]";
$mail->Password = "**********";
$mail->Port = "465";

That is a working configuration.

try to replace what you have

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

You've got no SMTPSecure setting to define the type of authentication being used, and you're running the Host setting with the unnecessary 'ssl://' (PS -- ssl is over port 465, if you need to run it over ssl instead, see the accepted answer here. Here's the lines to add/change:

+ $mail->SMTPSecure = 'tls';

- $mail->Host = "ssl://smtp.gmail.com";
+ $mail->Host = "smtp.gmail.com";

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

Use Message.get_payload

b = email.message_from_string(a)
if b.is_multipart():
    for payload in b.get_payload():
        # if payload.is_multipart(): ...
        print payload.get_payload()
else:
    print b.get_payload()

Error 500: Premature end of script headers

u forgot to add proper content-type header in the response which is a must have http header when hosting on apache2

use

print "Content-type:text/html\r\n\r\n"

or

header('Content-Type: text/html');

PHP Redirect to another page after form submit

Once had this issue, thought it reasonable to share how I resolved it;

I think the way to do that in php is to use the header function as:

header ("Location: exampleFile.php");

You could just enclose that header file in an if statement so that it redirects only when a certain condition is met, as in:

if (isset($_POST['submit'])){   header("Location: exampleFile.php")   }

Hope that helps.

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

Try to login via the terminal using the following command:

mysql -u root -p

It will then prompt for your password. If this fails, then definitely the username or password is incorrect. If this works, then your database's password needs to be enclosed in quotes:

database_password: "0000"

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?

this code working fine for me

    $mail = new PHPMailer;
    //Enable SMTP debugging. 
    $mail->SMTPDebug = 0;
    //Set PHPMailer to use SMTP.
    $mail->isSMTP();
    //Set SMTP host name                          
    $mail->Host = $hostname;
    //Set this to true if SMTP host requires authentication to send email
    $mail->SMTPAuth = true;
    //Provide username and password     
    $mail->Username = $sender;
    $mail->Password = $mail_password;
    //If SMTP requires TLS encryption then set it
    $mail->SMTPSecure = "ssl";
    //Set TCP port to connect to 
    $mail->Port = 465;
    $mail->From = $sender;  
    $mail->FromName = $sender_name;
    $mail->addAddress($to);
    $mail->isHTML(true);
    $mail->Subject = $Subject;
    $mail->Body = $Body;
    $mail->AltBody = "This is the plain text version of the email content";
    if (!$mail->send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    }
    else {
           echo 'Mail Sent Successfully';
    }

phpmailer - The following SMTP Error: Data not accepted

I was using just

$mail->Body    = $message;

and for some sumbited forms the PHP was returning the error:

SMTP Error: data not accepted.SMTP server error: DATA END command failed Detail: This message was classified as SPAM and may not be delivered SMTP code: 550

I got it fixed adding this code after $mail->Body=$message :

$mail->MsgHTML = $message;
$mail->AltBody = $message;

What is the default Jenkins password?

The password is present in the log generated by docker run image as shown in the example below.

Jenkins Docker run log

Additionally you can check the directory /var/jenkins_home/secrets/ Its in the file name initialAdminPassword

You can use cat /var/jenkins_home/secrets/initialAdminPassword to read it.

How to get list of all installed packages along with version in composer?

If you only want to check version for only one, you can do

composer show -- twig/twig

Note that only installed packages are shown by default now, and installed option is now deprecated.

Swift_TransportException Connection could not be established with host smtp.gmail.com

My solution was to change:

  'driver' => 'smtp',

to

 'driver' => 'mail',

In app/config/mail

Hope that helps

Exception: Serialization of 'Closure' is not allowed

You have to disable Globals

 /**
 * @backupGlobals disabled
 */

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

Well try ini_set('memory_limit', '256M');

134217728 bytes = 128 MB

Or rewrite the code to consume less memory.

PHP form send email to multiple recipients

Use comma separated values as below.

$email_to = 'Mary <[email protected]>, Kelly <[email protected]>';
@mail($email_to, $email_subject, $email_message, $headers);

or run a foreach for email address

//list of emails in array format and each one will see their own to email address
$arrEmail = array('Mary <[email protected]>', 'Kelly <[email protected]>');

foreach($arrEmail as $key => $email_to)
    @mail($email_to, $email_subject, $email_message, $headers);

Failed to build gem native extension — Rails install

The suggested answer only works for certain versions of ruby. Some commenters suggest using ruby-dev; that didn't work for me either.

sudo apt-get install ruby-all-dev

worked for me.

TCPDF Save file to folder?

If you still get

TCPDF ERROR: Unable to create output file: myfile.pdf

you can avoid TCPDF's file saving logic by putting PDF data to a variable and saving this string to a file:

$pdf_string = $pdf->Output('pseudo.pdf', 'S');
file_put_contents('./mydir/myfile.pdf', $pdf_string);

Send File Attachment from Form Using phpMailer and PHP

File could not be Attached from client PC (upload)

In the HTML form I have not added following line, so no attachment was going:

enctype="multipart/form-data"

After adding above line in form (as below), the attachment went perfect.

<form id="form1" name="form1" method="post" action="form_phpm_mailer.php"  enctype="multipart/form-data">

You have not concluded your merge (MERGE_HEAD exists)

If you are sure that you already resolved all merge conflicts:

rm -rf .git/MERGE*

And the error will disappear.

PHPmailer sending HTML CODE

do like this-paste your html code inside your separate html file using GET method.

$mail->IsHTML(true);                                 
    $mail->WordWrap = 70;                                 
    $mail->addAttachment= $_GET['addattachment']; $mail->AltBody   
    =$_GET['AltBody'];  $mail->Subject = $_GET['subject']; $mail->Body = $_GET['body'];

phpmailer: Reply using only "Reply To" address

At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.

    $mail->ClearReplyTos();
    $mail->addReplyTo([email protected], 'EXAMPLE');

Has anyone gotten HTML emails working with Twitter Bootstrap?

The best approach I've come up with is to use Sass imports on a selected basis to pull in your bootstrap (or any other) styles into emails as might be needed.

First, create a new scss parent file something like email.scss for your email style. This could look like this:

    // Core variables and mixins
    @import "css/main/ezdia-variables";

    @import "css/bootstrap/mixins";
    @import "css/main/ezdia-mixins";

    // Import base classes
    @import "css/bootstrap/scaffolding";
    @import "css/bootstrap/type";
    @import "css/bootstrap/buttons";
    @import "css/bootstrap/alerts";

    // nest conflicting bootstrap styles
    .bootstrap-style {
        //use single quotes for nested imports
        @import 'css/bootstrap/normalize';
        @import 'css/bootstrap/tables';
    }

    @import "css/main/main";

    // Main email classes
    @import "css/email/zurb";
    @import "css/email/main";

Then in your email templates, only reference your compiled email.css file, which only contains the selected bootstrap styles referenced and nested properly in your email.scss.

For example, certain bootstrap styles will conflict with Zurb's responsive table style. To fix that, you can nest bootstrap's styles within a parent class or other selector in order to call bootstrap's table styles only when needed.

This way, you have the flexibility to pull in classes only when needed. You'll see that I use http://zurb.com/ which is a great responsive email library to use. See also http://zurb.com/ink/

Lastly, use a premailer like https://github.com/fphilipe/premailer-rails3 mentioned above to process the style into inline css, compiling inline styles to only what is used in that particular email template. For instance, for premailer, your ruby file could look something like this to compile an email into inline style.

    require 'rubygems' # optional for Ruby 1.9 or above.
    require 'premailer'

    premailer = Premailer.new('http://www.yourdomain.com/TestSnap/view/emailTemplates/DeliveryReport.jsp', :warn_level => Premailer::Warnings::SAFE)

    # Write the HTML output
    File.open("delivery_report.html", "w") do |fout|
      fout.puts premailer.to_inline_css
    end

    # Write the plain-text output
    File.open("output.txt", "w") do |fout|
      fout.puts premailer.to_plain_text
    end

    # Output any CSS warnings
    premailer.warnings.each do |w|
      puts "#{w[:message]} (#{w[:level]}) may not render properly in #{w[:clients]}"
    end

Hope this helps! Been struggling to find a flexible email templating framework across Pardot, Salesforce, and our product's built-in auto-response and daily emails.

PHP Email sending BCC

You were setting BCC but then overwriting the variable with the FROM

$to = "[email protected]";
     $subject .= "".$emailSubject."";
 $headers .= "Bcc: ".$emailList."\r\n";
 $headers .= "From: [email protected]\r\n" .
     "X-Mailer: php";
     $headers .= "MIME-Version: 1.0\r\n";
     $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
 $message = '<html><body>';
 $message .= 'THE MESSAGE FROM THE FORM';

     if (mail($to, $subject, $message, $headers)) {
     $sent = "Your email was sent!";
     } else {
      $sent = ("Error sending email.");
     }

jQuery ajax success error

I had the same problem;

textStatus = 'error'
errorThrown = (empty)
xhr.status = 0

That fits my problem exactly. It turns out that when I was loading the HTML-page from my own computer this problem existed, but when I loaded the HTML-page from my webserver it went alright. Then I tried to upload it to another domain, and again the same error occoured. Seems to be a cross-domain problem. (in my case at least)

I have tried calling it this way also:

var request = $.ajax({
url: "http://crossdomain.url.net/somefile.php", dataType: "text",
crossDomain: true,
xhrFields: {
withCredentials: true
}
});

but without success.

This post solved it for me: jQuery AJAX cross domain

jQuery - Getting form values for ajax POST

Use the serialize method:

$.ajax({
    ...
    data: $("#registerSubmit").serialize(),
    ...
})

Docs: serialize()

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

go to config/environments/test.rb

Rails.application.routes.default_url_options[:host] = 'localhost:3000'

Setting SMTP details for php mail () function

Under Windows only: You may try to use ini_set() functionDocs for the SMTPDocs and smtp_portDocs settings:

ini_set('SMTP', 'mysmtphost'); 
ini_set('smtp_port', 25); 

incompatible character encodings: ASCII-8BIT and UTF-8

For prevent an error "can't modify frozen string" for encoding a varible you can use: var.dup.force_encoding(Encoding::ASCII_8BIT) or var.dup.force_encoding(Encoding::UTF_8)

php mail setup in xampp

Unless you have a mail server set up on your local computer, setting SMTP = localhost won't have any effect.

In days gone by (long ago), it was sufficient to set the value of SMTP to the address of your ISP's SMTP server. This now rarely works because most ISPs insist on authentication with a username and password. However, the PHP mail() function doesn't support SMTP authentication. It's designed to work directly with the mail transport agent of the local server.

You either need to set up a local mail server or to use a PHP classs that supports SMTP authentication, such as Zend_Mail or PHPMailer. The simplest solution, however, is to upload your mail processing script to your remote server.

"SMTP Error: Could not authenticate" in PHPMailer

The other post is correct to resolve the issue but doesn't address how to do it if the 2-step-verification is turned on. The option to allow the less secure apps is NOT available then. Here is an answer to how to do it:

a. Go to the URL of `https://myaccount.google.com/` and click `Sing-in and security`

b. Click on the app password. 

enter image description here

You will reach a page like this,

enter image description here

c. Create name of your app and generate a password for the respective app.  

d. Use that password acquired here inside the app.

This should resolve the issue.

Send email with PHPMailer - embed image in body

I found the answer:

$mail->AddEmbeddedImage('img/2u_cs_mini.jpg', 'logo_2u');

and on the <img> tag put src='cid:logo_2u'

Sending emails through SMTP with PHPMailer

Simple smtp client with php stream socket with tls/ssl smtp STARTTLS command: https://github.com/breakermind/PhpMimeParser/blob/master/PhpSmtpSslSocketClient.php

works with gmail.com with authenticate:

<?php
// Login email and password
$login = "[email protected]";
$pass = "123456";

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'verify_peer', false);
stream_context_set_option($ctx, 'ssl', 'verify_peer_name', false);
try{
    // echo $socket = stream_socket_client('ssl://smtp.gmail.com:587', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
    echo $socket = stream_socket_client('tcp://smtp.gmail.com:587', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
    if (!$socket) {
        print "Failed to connect $err $errstr\n";
        return;
    }else{
        // Http
        // fwrite($socket, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
        // Smtp
        echo fread($socket,8192);
        echo fwrite($socket, "EHLO cool.xx\r\n");
        echo fread($socket,8192);

        // Start tls connection
        echo fwrite($socket, "STARTTLS\r\n");
        echo fread($socket,8192);

        echo stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);

        // Send ehlo
        echo fwrite($socket, "EHLO cool.xx\r\n");
        echo fread($socket,8192);

        // echo fwrite($socket, "MAIL FROM: <[email protected]>\r\n");
        // echo fread($socket,8192);

        echo fwrite($socket, "AUTH LOGIN\r\n");
        echo fread($socket,8192);

        echo fwrite($socket, base64_encode($login)."\r\n");
        echo fread($socket,8192);

        echo fwrite($socket, base64_encode($pass)."\r\n");
        echo fread($socket,8192);

        echo fwrite($socket, "rcpt to: <[email protected]>\r\n");
        echo fread($socket,8192);

        echo fwrite($socket, "DATA\n");
        echo fread($socket,8192);

        echo fwrite($socket, "Date: ".time()."\r\nTo: <[email protected]>\r\nFrom:<[email protected]\r\nSubject:Hello from php socket tls\r\n.\r\n");
        echo fread($socket,8192);

        echo fwrite($socket, "QUIT \n");
        echo fread($socket,8192);

        /* Turn off encryption for the rest */
        // stream_socket_enable_crypto($fp, false);

        fclose($socket);
    }
}catch(Exception $e){
    echo $e;
}

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

You perhaps use the wrong username.

I had a similar error. Ensure you're not using uppercase while logging into server.

Example: [email protected]

If you use ->setUsername('JacekPL'), this can cause an error. Use ->setUsername('jacekpl') instead. This solved my problem.

smtp configuration for php mail

Since some of the answers give here relate to setting up SMTP in general (and not just for @shinod particular issue where it had been working and stopped), I thought it would be helpful if I updated the answer because this is a lot simpler to do now than it used to be :-)

In PHP 4 the PEAR Mail package is typically already installed, and this really simple tutorial shows you the few lines of code that you need to add to your php file http://email.about.com/od/emailprogrammingtips/qt/PHP_Email_SMTP_Authentication.htm

Most hosting companies list the SMTP settings that you'll need. I use JustHost, and they list theirs at https://my.justhost.com/cgi/help/26 (under Outgoing Mail Server)

Page redirect with successful Ajax request

In your mail3.php file you should trap errors in a try {} catch {}

try {
    /*code here for email*/
} catch (Exception $e) {
    header('HTTP/1.1 500 Internal Server Error');
}

Then in your success call you wont have to worry about your errors, because it will never return as a success.

and you can use: window.location.href = "thankyou.php"; inside your success function like Nick stated.

PHPMailer: SMTP Error: Could not connect to SMTP host

I had a similar issue. I had installed PHPMailer version 1.72 which is not prepared to manage SSL connections. Upgrading to last version solved the problem.

PHP mailer multiple address

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

Creating email templates with Django

Django Mail Templated is a feature-rich Django application to send emails with Django template system.

Installation:

pip install django-mail-templated

Configuration:

INSTALLED_APPS = (
    ...
    'mail_templated'
)

Template:

{% block subject %}
Hello {{ user.name }}
{% endblock %}

{% block body %}
{{ user.name }}, this is the plain text part.
{% endblock %}

Python:

from mail_templated import send_mail
send_mail('email/hello.tpl', {'user': user}, from_email, [user.email])

More info: https://github.com/artemrizhov/django-mail-templated

PHPMailer character encoding issues

I was getting &oacute; in $mail->Subject /w PHPMailer.

So for me the complete solution is:

// Your Subject with tildes. Example.
$someSubjectWithTildes = 'Subscripción España';

$mailer->CharSet = 'UTF-8';
$mailer->Encoding = 'quoted-printable';
$mailer->Subject = html_entity_decode($someSubjectWithTildes);

Hope it helps.

Error handling with PHPMailer

This one works fine

use try { as above

use Catch as above but comment out the echo lines
} catch (phpmailerException $e) { 
//echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {   
//echo $e->getMessage(); //Boring error messages from anything else!
}

Then add this

if ($e) {
//enter yor error message or redirect the user
} else {
//do something else 
}

problem with php mail 'From' header

I solved this by adding email accounts in Cpanel and also adding that same email to the header from field like this

$header = 'From: XXXXXXXX <[email protected]>' . "\r\n";

Could not instantiate mail function. Why this error occurring

This a system error.

Check error of the system with:

tail /var/log/httpd/error_log

It can be any reason.

PHPMailer AddAddress()

All answers are great. Here is an example use case for multiple add address: The ability to add as many email you want on demand with a web form:

See it in action with jsfiddle here (except the php processor)

### Send unlimited email with a web form
# Form for continuously adding e-mails:
<button type="button" onclick="emailNext();">Click to Add Another Email.</button>
<div id="addEmail"></div>
<button type="submit">Send All Emails</button>
# Script function:
<script>
function emailNext() {
    var nextEmail, inside_where;
    nextEmail = document.createElement('input');
    nextEmail.type = 'text';
    nextEmail.name = 'emails[]';
    nextEmail.className = 'class_for_styling';
    nextEmail.style.display = 'block';
    nextEmail.placeholder  = 'Enter E-mail Here';
    inside_where = document.getElementById('addEmail');
    inside_where.appendChild(nextEmail);
    return false;
}
</script>
# PHP Data Processor:
<?php
// ...
// Add the rest of your $mailer here...
if ($_POST[emails]){
    foreach ($_POST[emails] AS $postEmail){
        if ($postEmail){$mailer->AddAddress($postEmail);}
    }
} 
?>

So what it does basically is to generate a new input text box on every click with the name "emails[]".

The [] added at the end makes it an array when posted.

Then we go through each element of the array with "foreach" on PHP side adding the:

    $mailer->AddAddress($postEmail);

Sending email with gmail smtp with codeigniter email library

It can be this:

If you are using cpanel for your website smtp restrictions are problem and cause this error. SMTP Restrictions

Error while sending an email with CodeIgniter

phpmailer error "Could not instantiate mail function"

You need to make sure that your from address is a valid email account setup on that server.

Problem with SMTP authentication in PHP using PHPMailer, with Pear Mail works

Exim 4 requires that AUTH command only be sent after the client issued EHLO - attempts to authenticate without EHLO would be rejected. Some mailservers require that EHLO be issued twice. PHPMailer apparently fails to do so. If PHPMailer does not allow you to force EHLO initiation, you really should switch to SwiftMailer 4.

Change the "From:" address in Unix "mail"

On CentOS 5.5, the easiest way I've found to set the default from domain is to modify the hosts file. If your hosts file contains your WAN/public IP address, simply modify the first hostname listed for it. For example, your hosts file may look like:

...
11.22.33.44 localhost default-domain whatever-else.com
...

To make it send from whatever-else.com, simply modify it so that whatever-else.com is listed first, for example:

...
11.22.33.44 whatever-else.com localhost default-domain
...

I can't speak for any other distro (or even version of CentOS) but in my particular case, the above works perfectly.

How to: Install Plugin in Android Studio

if you are on Linux (Ubuntu)... the go to File-> Settings-> Plugin and select plugin from respective location.

If you are on Mac OS... the go to File-> Preferences-> Plugin and select plugin from respective location.

Python Timezone conversion

Time conversion

To convert a time in one timezone to another timezone in Python, you could use datetime.astimezone():

so, below code is to convert the local time to other time zone.

  • datetime.datetime.today() - return current the local time
  • datetime.astimezone() - convert the time zone, but we have to pass the time zone.
  • pytz.timezone('Asia/Kolkata') -passing the time zone to pytz module
  • Strftime - Convert Datetime to string
# Time conversion from local time
import datetime
import pytz
dt_today = datetime.datetime.today()   # Local time
dt_India = dt_today.astimezone(pytz.timezone('Asia/Kolkata')) 
dt_London = dt_today.astimezone(pytz.timezone('Europe/London'))
India = (dt_India.strftime('%m/%d/%Y %H:%M'))
London = (dt_London.strftime('%m/%d/%Y %H:%M'))
print("Indian standard time: "+India+" IST")
print("British Summer Time: "+London+" BST")

list all the time zone

import pytz
for tz in pytz.all_timezones:
    print(tz)

Static way to get 'Context' in Android?

Kotlin way:

Manifest:

<application android:name="MyApplication">

</application>

MyApplication.kt

class MyApplication: Application() {

    override fun onCreate() {
        super.onCreate()
        instance = this
    }

    companion object {
        lateinit var instance: MyApplication
            private set
    }
}

You can then access the property via MyApplication.instance

how to find my angular version in my project?

There are several ways you can do that:

  1. Go into node_modules/@angular/core/package.json and check version field.
  2. If you need to use it in your code, you can import it from the @angular/core:

    import { VERSION } from '@angular/core';

  3. Inspect the rendered DOM - Angular adds the version to the main component element:

    <my-app ng-version="4.1.3">

How to round a floating point number up to a certain decimal place?

Here is a simple function to do this for you:

def precision(num,x):
    return "{0:.xf}".format(round(num))

Here, num is the decimal number. x is the decimal up to where you want to round a floating number.

The advantage over other implementation is that it can fill zeros at the right end of the decimal to make a deciaml number up to x decimal places.

Example 1:

precision(10.2, 9)

will return

10.200000000 (up to 9 decimal points)

Example 2:

precision(10.2231, 2)

will return

10.22 (up to two decimal points)

When should I use semicolons in SQL Server?

When using either a DISABLE or ENABLE TRIGGER statement in a batch that has other statements in it, the statement just before it must end with a semicolon. Otherwise, you'll get a syntax error. I tore my hair out with this one... And afterwards, I stumbled on this MS Connect item about the same thing. It is closed as won't fix.

see here

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

I had this issue as well. In my case, I was trying to get a post-receive Git hook to update a working copy on a server with each push. Tried to follow the instructions in the blog you linked to. Didn't work for me as well and overriding the settings on a per-user basis didn't seem to work either.

What I ended up having to do was disable SSL verification (as the article mentions) for Git as a whole. Not the perfect solution, but it'll work until I can figure out a better one.

I edited the Git config text file (with my favorite line-ending neutral app like Notepad++) located at:

C:\Program Files (x86)\Git\etc\gitconfig

In the [http] block, I added an option to disable sslVerify. It looked like this when I was done:

[http]
    sslVerify = false
    sslCAinfo = /bin/curl-ca-bundle.crt

That did the trick.

NOTE:

  • This disables SSL verification and is not recommended as a long term solution.

  • You can disable this per-repository which still isn't great, but localizes the setting.

  • With the advent of LetsEncrypt.org, it is now fairly simple, automated and free to set up SSL as an alternative to self-signed certs and negates the need to turn off sslVerify.

Creating .pem file for APNS?

Development Phase:

Step 1: Create Certificate .pem from Certificate .p12
openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12

Step 2: Create Key .pem from Key .p12
openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12

Step 3 (Optional): If you want to remove pass phrase asked in second step
openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem

Step 4: Now we have to merge the Key .pem and Certificate .pem to get Development .pem needed for Push Notifications in Development Phase of App.

If 3rd step was performed, run:
cat apns-dev-cert.pem apns-dev-key-noenc.pem > apns-dev.pem

If 3rd step was not performed, run:
cat apns-dev-cert.pem apns-dev-key.pem > apns-dev.pem

Step 5: Check certificate validity and connectivity to APNS

If 3rd step was performed, run:
openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert apns-dev-cert.pem -key apns-dev-key-noenc.pem

If 3rd step was not performed, run:
openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert apns-dev-cert.pem -key apns-dev-key.pem

Production Phase:

Step 1: Create Certificate .pem from Certificate .p12
openssl pkcs12 -clcerts -nokeys -out apns-pro-cert.pem -in apns-pro-cert.p12

Step 2: Create Key .pem from Key .p12
openssl pkcs12 -nocerts -out apns-pro-key.pem -in apns-pro-key.p12

Step 3 (Optional): If you want to remove pass phrase asked in second step
openssl rsa -in apns-pro-key.pem -out apns-pro-key-noenc.pem

Step 4: Now we have to merge the Key .pem and Certificate .pem to get Production .pem needed for Push Notifications in Production Phase of App.

If 3rd step was performed, run:
cat apns-pro-cert.pem apns-pro-key-noenc.pem > apns-pro.pem

If 3rd step was not performed, run:
cat apns-pro-cert.pem apns-pro-key.pem > apns-pro.pem

Step 5: Check certificate validity and connectivity to APNS.

If 3rd step was performed, run:
openssl s_client -connect gateway.push.apple.com:2195 -cert apns-pro-cert.pem -key apns-pro-key-noenc.pem

If 3rd step was not performed, run:
openssl s_client -connect gateway.push.apple.com:2195 -cert apns-pro-cert.pem -key apns-pro-key.pem

How to loop through an array containing objects and access their properties

It's really simple using the forEach method since ES5+. You can directly change each property of each object in your array.

myArray.forEach(function (arrayElem){ 
  arrayElem = newPropertyValue;
});

If you want to access a specific property on each object:

myArray.forEach(function (arrayElem){ 
      arrayElem.nameOfYourProperty = newPropertyValue;
    });

"std::endl" vs "\n"

The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.

The only difference is that std::endl flushes the output buffer, and '\n' doesn't. If you don't want the buffer flushed frequently, use '\n'. If you do (for example, if you want to get all the output, and the program is unstable), use std::endl.

How do I detect whether a Python variable is a function?

A function is just a class with a __call__ method, so you can do

hasattr(obj, '__call__')

For example:

>>> hasattr(x, '__call__')
True

>>> x = 2
>>> hasattr(x, '__call__')
False

That is the "best" way of doing it, but depending on why you need to know if it's callable or note, you could just put it in a try/execpt block:

try:
    x()
except TypeError:
    print "was not callable"

It's arguable if try/except is more Python'y than doing if hasattr(x, '__call__'): x().. I would say hasattr is more accurate, since you wont accidently catch the wrong TypeError, for example:

>>> def x():
...     raise TypeError
... 
>>> hasattr(x, '__call__')
True # Correct
>>> try:
...     x()
... except TypeError:
...     print "x was not callable"
... 
x was not callable # Wrong!

How to update all MySQL table rows at the same time?

UPDATE dummy SET myfield=1 WHERE id>1;

How can I get the application's path in a .NET console application?

you can use this one instead.

System.Environment.CurrentDirectory

Your content must have a ListView whose id attribute is 'android.R.id.list'

You should have one listview in your mainlist.xml file with id as @android:id/list

<ListView
    android:id="@android:id/list"
    android:layout_height="wrap_content"
    android:layout_height="fill_parent"/>

How to show "if" condition on a sequence diagram?

Very simple , using Alt fragment

Lets take an example of sequence diagram for an ATM machine.Let's say here you want

IF card inserted is valid then prompt "Enter Pin"....ELSE prompt "Invalid Pin"

Then here is the sequence diagram for the same

ATM machine sequence diagram

Hope this helps!

Global variables in Java

There are no global variables in Java, but there are global classes with public fields. You can use static import feature of java 5 to make it look almost like global variables.

Is it possible to delete an object's property in PHP?

unset($a->new_property);

This works for array elements, variables, and object attributes.

Example:

$a = new stdClass();

$a->new_property = 'foo';
var_export($a);  // -> stdClass::__set_state(array('new_property' => 'foo'))

unset($a->new_property);
var_export($a);  // -> stdClass::__set_state(array())

I need to convert an int variable to double

Either use casting as others have already said, or multiply one of the int variables by 1.0:

double firstSolution = ((1.0* b1 * a22 - b2 * a12) / (a11 * a22 - a12 * a21));

Request Monitoring in Chrome

You can also just right click on the page in the browser and select "Inspect Element" to bring up the developer tools.

https://developer.chrome.com/devtools

Check if string contains \n Java

If the string was constructed in the same program, I would recommend using this:

String newline = System.getProperty("line.separator");
boolean hasNewline = word.contains(newline);

But if you are specced to use \n, this driver illustrates what to do:

class NewLineTest {
    public static void main(String[] args) {
        String hasNewline = "this has a newline\n.";
        String noNewline = "this doesn't";

        System.out.println(hasNewline.contains("\n"));
        System.out.println(hasNewline.contains("\\n"));
        System.out.println(noNewline.contains("\n"));
        System.out.println(noNewline.contains("\\n"));

    }

}

Resulted in

true
false
false
false

In reponse to your comment:

class NewLineTest {
    public static void main(String[] args) {
        String word = "test\n.";
        System.out.println(word.length());
        System.out.println(word);
        word = word.replace("\n","\n ");
        System.out.println(word.length());
        System.out.println(word);

    }

}

Results in

6
test
.
7
test
 .

Is string in array?

Just use the already built-in Contains() method:

using System.Linq;

//...

string[] array = { "foo", "bar" };
if (array.Contains("foo")) {
    //...
}

How to make modal dialog in WPF?

Window.Show will show the window, and continue execution -- it's a non-blocking call.

Window.ShowDialog will block the calling thread (kinda [1]), and show the dialog. It will also block interaction with the parent/owning window. When the dialog is dismissed (for whatever reason), ShowDialog will return to the caller, and will allow you to access DialogResult (if you want it).

[1] It will keep the dispatcher pumping by pushing a dispatcher frame onto the WPF dispatcher. This will cause the message pump to keep pumping.

Change the bullet color of list

You have to use image

.listStyle {
    list-style: none;
    background: url(bullet.jpg) no-repeat left center;
    padding-left: 40px;
}

Get the current cell in Excel VB

Have you tried:

For one cell:

ActiveCell.Select

For multiple selected cells:

Selection.Range

For example:

Dim rng As Range
Set rng = Range(Selection.Address)

For vs. while in C programming?

If you want a loop to execute while a condition is true, and not for a certain number of iterations, it is much easier for someone else to understand:

while (cond_true)

than something like this:

for (; cond_true ; )

Detect encoding and make everything UTF-8

I know this is an older question, but I figure a useful answer never hurts. I was having issues with my encoding between a desktop application, SQLite, and GET/POST variables. Some would be in UTF-8, some would be in ASCII, and basically everything would get screwed up when foreign characters got involved.

Here is my solution. It scrubs your GET/POST/REQUEST (I omitted cookies, but you could add them if desired) on each page load before processing. It works well in a header. PHP will throw warnings if it can't detect the source encoding automatically, so these warnings are suppressed with @'s.

//Convert everything in our vars to UTF-8 for playing nice with the database...
//Use some auto detection here to help us not double-encode...
//Suppress possible warnings with @'s for when encoding cannot be detected
try
{
    $process = array(&$_GET, &$_POST, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][@mb_convert_encoding($k,'UTF-8','auto')] = $v;
                $process[] = &$process[$key][@mb_convert_encoding($k,'UTF-8','auto')];
            } else {
                $process[$key][@mb_convert_encoding($k,'UTF-8','auto')] = @mb_convert_encoding($v,'UTF-8','auto');
            }
        }
    }
    unset($process);
}
catch(Exception $ex){}

Failed to allocate memory: 8

Have a look at the official issue 33930. There is pointed out, that it may have to do with the start up of OpenGL during the start of the emulator. Others wrote it only crashes when they use WXGA800-skin and suggest to manually set the resolution to 800x1280.

Further there are ZIP-files provided to manually downgrade your android SDK to version 19 and plattform-tools to version 11. This may help as well to temporally fix the issue.

How do I pass multiple parameters into a function in PowerShell?

If you don't know (or care) how many arguments you will be passing to the function, you could also use a very simple approach like;

Code:

function FunctionName()
{
    Write-Host $args
}

That would print out all arguments. For example:

FunctionName a b c 1 2 3

Output

a b c 1 2 3

I find this particularly useful when creating functions that use external commands that could have many different (and optional) parameters, but relies on said command to provide feedback on syntax errors, etc.

Here is a another real-world example (creating a function to the tracert command, which I hate having to remember the truncated name);

Code:

Function traceroute
{
    Start-Process -FilePath "$env:systemroot\system32\tracert.exe" -ArgumentList $args -NoNewWindow
}

How to list processes attached to a shared memory segment in linux?

I don't think you can do this with the standard tools. You can use ipcs -mp to get the process ID of the last process to attach/detach but I'm not aware of how to get all attached processes with ipcs.

With a two-process-attached segment, assuming they both stayed attached, you can possibly figure out from the creator PID cpid and last-attached PID lpid which are the two processes but that won't scale to more than two processes so its usefulness is limited.

The cat /proc/sysvipc/shm method seems similarly limited but I believe there's a way to do it with other parts of the /proc filesystem, as shown below:

When I do a grep on the procfs maps for all processes, I get entries containing lines for the cpid and lpid processes.

For example, I get the following shared memory segment from ipcs -m:

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status      
0x00000000 123456     pax        600        1024       2          dest

and, from ipcs -mp, the cpid is 3956 and the lpid is 9999 for that given shared memory segment (123456).

Then, with the command grep 123456 /proc/*/maps, I see:

/proc/3956/maps: blah blah blah 123456 /SYSV000000 (deleted)
/proc/9999/maps: blah blah blah 123456 /SYSV000000 (deleted)

So there is a way to get the processes that attached to it. I'm pretty certain that the dest status and (deleted) indicator are because the creator has marked the segment for destruction once the final detach occurs, not that it's already been destroyed.

So, by scanning of the /proc/*/maps "files", you should be able to discover which PIDs are currently attached to a given segment.

int to string in MySQL

You could use CONCAT, and the numeric argument of it is converted to its equivalent binary string form.

select t2.* 
from t1 join t2 
on t2.url=CONCAT('site.com/path/%', t1.id, '%/more') where t1.id > 9000

What is the difference between dim and set in vba

According to VBA help on SET statement it sets a reference to an object.so if you change a property the actual object will also changes.

Dim newObj as Object
Set var1=Object1(same type as Object)
Set var2=Object1(same type as Object)
Set var3=Object1(same type as Object)
Set var4=Object1(same type as Object)
Var1.property1=NewPropertyValue

the other Vars properties also changes,so:

Var1.property1=Var2.property1=Var3.property1=Var4.property1=Object1.Property1=NewpropertyValue`

actualy all vars are the same!

JavaScript: changing the value of onclick with or without jQuery

Came up with a quick and dirty fix to this. Just used <select onchange='this.options[this.selectedIndex].onclick();> <option onclick='alert("hello world")' ></option> </select>

Hope this helps

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

Please remove remotely linked jQuery files such as: https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js

Instead, download this file and load it from your local js folder, making the URI:

js/jquery.min.js

Throw keyword in function's signature

To add a bit more value to all the other answer's to this question, one should invest a few minutes in the question: What is the output of the following code?

#include <iostream>
void throw_exception() throw(const char *)
{
    throw 10;
}
void my_unexpected(){
    std::cout << "well - this was unexpected" << std::endl;
}
int main(int argc, char **argv){
    std::set_unexpected(my_unexpected);
    try{
        throw_exception();
    }catch(int x){
        std::cout << "catch int: " << x << std::endl;
    }catch(...){
        std::cout << "catch ..." << std::endl;
    }
}

Answer: As noted here, the program calls std::terminate() and thus none of the exception handlers will get called.

Details: First my_unexpected() function is called, but since it doesn't re-throw a matching exception type for the throw_exception() function prototype, in the end, std::terminate() is called. So the full output looks like this:

user@user:~/tmp$ g++ -o except.test except.test.cpp
user@user:~/tmp$ ./except.test
well - this was unexpected
terminate called after throwing an instance of 'int'
Aborted (core dumped)

OnChange event using React JS for drop down

React Hooks (16.8+):

const Dropdown = ({
  options
}) => {
  const [selectedOption, setSelectedOption] = useState(options[0].value);
  return (
      <select
        value={selectedOption}
        onChange={e => setSelectedOption(e.target.value)}>
        {options.map(o => (
          <option key={o.value} value={o.value}>{o.label}</option>
        ))}
      </select>
  );
};

java.lang.IllegalArgumentException: No converter found for return value of type

In my case, I was returning Boolean in Response Entity and had :

produces = MediaType.TEXT_PLAIN_VALUE,

When i changed it to below

produces = MediaType.APPLICATION_JSON_VALUE

It worked!

Example of what i had.

@PostMapping(value = "/xxx-xxxx",
            produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Boolean> yyyy(

How do I use floating-point division in bash?

You can't. bash only does integers; you must delegate to a tool such as bc.

jQuery input button click event listener

First thing first, button() is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:

$("#filter").click(function(){
    alert('clicked!');
});

Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func) which execute the callback once the DOM is ready.
Usage:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

So even if the order is this it will work:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

<input type="button" id="filter" name="filter" value="Filter" />

DEMO

How do I (or can I) SELECT DISTINCT on multiple columns?

SELECT DISTINCT a,b,c FROM t

is roughly equivalent to:

SELECT a,b,c FROM t GROUP BY a,b,c

It's a good idea to get used to the GROUP BY syntax, as it's more powerful.

For your query, I'd do it like this:

UPDATE sales
SET status='ACTIVE'
WHERE id IN
(
    SELECT id
    FROM sales S
    INNER JOIN
    (
        SELECT saleprice, saledate
        FROM sales
        GROUP BY saleprice, saledate
        HAVING COUNT(*) = 1 
    ) T
    ON S.saleprice=T.saleprice AND s.saledate=T.saledate
 )

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

OpenSSH cannot use PKCS#12 files out of the box. As others suggested, you must extract the private key in PEM format which gets you from the land of OpenSSL to OpenSSH. Other solutions mentioned here don’t work for me. I use OS X 10.9 Mavericks (10.9.3 at the moment) with “prepackaged” utilities (OpenSSL 0.9.8y, OpenSSH 6.2p2).

First, extract a private key in PEM format which will be used directly by OpenSSH:

openssl pkcs12 -in filename.p12 -clcerts -nodes -nocerts | openssl rsa > ~/.ssh/id_rsa

I strongly suggest to encrypt the private key with password:

openssl pkcs12 -in filename.p12 -clcerts -nodes -nocerts | openssl rsa -passout 'pass:Passw0rd!' > ~/.ssh/id_rsa

Obviously, writing a plain-text password on command-line is not safe either, so you should delete the last command from history or just make sure it doesn’t get there. Different shells have different ways. You can prefix your command with space to prevent it from being saved to history in Bash and many other shells. Here is also how to delete the command from history in Bash:

history -d $(history | tail -n 2 | awk 'NR == 1 { print $1 }')

Alternatively, you can use different way to pass a private key password to OpenSSL - consult OpenSSL documentation for pass phrase arguments.

Then, create an OpenSSH public key which can be added to authorized_keys file:

ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub

matching query does not exist Error in Django

You may try this way. just use a function to get your object

def get_object(self, id):
    try:
        return UniversityDetails.objects.get(email__exact=email)
    except UniversityDetails.DoesNotExist:
        return False

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

Corresponding to INSERT (Transact-SQL) (SQL Server 2005) you can't omit INSERT INTO dbo.Blah and have to specify it every time or use another syntax/approach,

Jinja2 template variable if None Object set a default value

To avoid throw a exception while "p" or "p.User" is None, you can use:

{{ (p and p.User and p.User['first_name']) or "default_value" }}

Appending an id to a list if not already present in a string

I agree with other answers that you are doing something weird here. You have a list containing a string with multiple entries that are themselves integers that you are comparing to an integer id.

This is almost surely not what you should be doing. You probably should be taking input and converting it to integers before storing in your list. You could do that with:

input = '350882 348521 350166\r\n'
list.append([int(x) for x in input.split()])

Then your test will pass. If you really are sure you don't want to do what you're currently doing, the following should do what you want, which is to not add the new id that already exists:

list = ['350882 348521 350166\r\n']
id = 348521
if id not in [int(y) for x in list for y in x.split()]:
    list.append(id)
print list

How do you find out which version of GTK+ is installed on Ubuntu?

Because apt-cache policy will list all the matches available, even if not installed, I would suggest using this command for a more manageable shortlist of GTK-related packages installed on your system:

apt list --installed libgtk*

javascript regular expression to not match a word

function test(string) {
    return ! string.match(/abc|def/);
}

How to rename a table column in Oracle 10g

alter table table_name rename column oldColumn to newColumn;

Convert String array to ArrayList

in most cases the List<String> should be enough. No need to create an ArrayList

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

...

String[] words={"ace","boom","crew","dog","eon"};
List<String> l = Arrays.<String>asList(words);

// if List<String> isnt specific enough:
ArrayList<String> al = new ArrayList<String>(l);

jQuery - Click event on <tr> elements with in a table and getting <td> element values

This work for me!

$(document).ready(function() {
    $(document).on("click", "#tableId tbody tr", function() {
        //some think
    });
});

How to get HttpRequestMessage data

I suggest that you should not do it like this. Action methods should be designed to be easily unit-tested. In this case, you should not access data directly from the request, because if you do it like this, when you want to unit test this code you have to construct a HttpRequestMessage.

You should do it like this to let MVC do all the model binding for you:

[HttpPost]
public void Confirmation(YOURDTO yourobj)//assume that you define YOURDTO elsewhere
{
        //your logic to process input parameters.

}

In case you do want to access the request. You just access the Request property of the controller (not through parameters). Like this:

[HttpPost]
public void Confirmation()
{
    var content = Request.Content.ReadAsStringAsync().Result;
}

In MVC, the Request property is actually a wrapper around .NET HttpRequest and inherit from a base class. When you need to unit test, you could also mock this object.

ORA-00979 not a group by expression

Include in the GROUP BY clause all SELECT expressions that are not group function arguments.

Populating a database in a Laravel migration file

I know this is an old post but since it comes up in a google search I thought I'd share some knowledge here. @erin-geyer pointed out that mixing migrations and seeders can create headaches and @justamartin countered that sometimes you want/need data to be populated as part of your deployment.

I'd go one step further and say that sometimes it is desirable to be able to roll out data changes consistently so that you can for example deploy to staging, see that all is well, and then deploy to production with confidence of the same results (and not have to remember to run some manual step).

However, there is still value in separating out the seed and the migration as those are two related but distinct concerns. Our team has compromised by creating migrations which call seeders. This looks like:

public function up()
{
    Artisan::call( 'db:seed', [
        '--class' => 'SomeSeeder',
        '--force' => true ]
    );
}

This allows you to execute a seed one time just like a migration. You can also implement logic that prevents or augments behavior. For example:

public function up()
{
    if ( SomeModel::count() < 10 )
    {
        Artisan::call( 'db:seed', [
            '--class' => 'SomeSeeder',
            '--force' => true ]
        );
    }
}

This would obviously conditionally execute your seeder if there are less than 10 SomeModels. This is useful if you want to include the seeder as a standard seeder that executed when you call artisan db:seed as well as when you migrate so that you don't "double up". You may also create a reverse seeder so that rollbacks works as expected, e.g.

public function down()
{
    Artisan::call( 'db:seed', [
        '--class' => 'ReverseSomeSeeder',
        '--force' => true ]
    );
}

The second parameter --force is required to enable to seeder to run in a production environment.

Responding with a JSON object in Node.js (converting object/array to JSON string)

Per JamieL's answer to another post:

Since Express.js 3x the response object has a json() method which sets all the headers correctly for you.

Example:

res.json({"foo": "bar"});

How to stop execution after a certain time in Java?

you should try the new Java Executor Services. http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

With this you don't need to program the loop the time measuring by yourself.

public class Starter {

    public static void main(final String[] args) {
        final ExecutorService service = Executors.newSingleThreadExecutor();

        try {
            final Future<Object> f = service.submit(() -> {
                // Do you long running calculation here
                Thread.sleep(1337); // Simulate some delay
                return "42";
            });

            System.out.println(f.get(1, TimeUnit.SECONDS));
        } catch (final TimeoutException e) {
            System.err.println("Calculation took to long");
        } catch (final Exception e) {
            throw new RuntimeException(e);
        } finally {
            service.shutdown();
        }
    }
}

Read a text file in R line by line

Here is the solution with a for loop. Importantly, it takes the one call to readLines out of the for loop so that it is not improperly called again and again. Here it is:

fileName <- "up_down.txt"
conn <- file(fileName,open="r")
linn <-readLines(conn)
for (i in 1:length(linn)){
   print(linn[i])
}
close(conn)

Hashmap holding different data types as values for instance Integer, String and Object

Create an object holding following properties with an appropriate name.

  1. message
  2. timestamp
  3. count
  4. version

and use this as a value in your map.

Also consider overriding the equals() and hashCode() method accordingly if you do not want object equality to be used for comparison (e.g. when inserting values into your map).

jQuery - Dynamically Create Button and Attach Event Handler

Calling .html() serializes the element to a string, so all event handlers and other associated data is lost. Here's how I'd do it:

$("#myButton").click(function ()
{
    var test = $('<button/>',
    {
        text: 'Test',
        click: function () { alert('hi'); }
    });

    var parent = $('<tr><td></td></tr>').children().append(test).end();

    $("#addNodeTable tr:last").before(parent);
});

Or,

$("#myButton").click(function ()
{    
    var test = $('<button/>',
    {
        text: 'Test',
        click: function () { alert('hi'); }
    }).wrap('<tr><td></td></tr>').closest('tr');

    $("#addNodeTable tr:last").before(test);
});

If you don't like passing a map of properties to $(), you can instead use

$('<button/>')
    .text('Test')
    .click(function () { alert('hi'); });

// or

$('<button>Test</button>').click(function () { alert('hi'); });

Soft Edges using CSS?

You can use CSS gradient - although there are not consistent across browsers so You would have to code it for every one

Like that: CSS3 Transparency + Gradient

Gradient should be more transparent on top or on top right corner (depending on capabilities)

I have filtered my Excel data and now I want to number the rows. How do I do that?

Add a column for example 'Selected' First. Then Filter your data. Go to the column 'Selected'. Provide any proxy text or number to all rows. like '1' or 'A' - now your hidden Rows are Blank Now, Clear Filter and Use Sorting - two levels Sort by - 'Selected' Ascending - this leaves blank cells at bottom Add Sort Level - 'Any column you Desire' your order

Now, Why dont you drag the autofill yourself.

Oops, I have no reputation here.

python int( ) function

Use float() in place of int() so that your program can handle decimal points. Also, don't use next as it's a built-in Python function, next().

Also you code as posted is missing import sys and the definition for dead

Why std::cout instead of simply cout?

You probably had using namespace std; before in your code you did in class. That explicitly tells the precompiler to look for the symbols in std, which means you don't need to std::. Though it is good practice to std::cout instead of cout so you explicitly invoke std::cout every time. That way if you are using another library that redefines cout, you still have the std::cout behavior instead of some other custom behavior.

Status bar and navigation bar appear over my view's bounds in iOS 7

I had the same issue with my app by iPads (armv7, armv7s, amr64) only by presenting another UIViewController and after dismiss them goes nav bar under status bar... I spend a lot of time to find any solution for that. I'm using storyboard and in InterfaceBuilder for UIViewController which makes terrible i set Presentation from FullScreen -> Current Context and it fix this issue. It works in my app only for iPads => iOS8.0 (testing with iOS8.1) and for iPads with iOS 7.1 not work!! see screenshot

$(document).ready equivalent without jQuery

Three options:

  1. If script is the last tag of the body, the DOM would be ready before script tag executes
  2. When the DOM is ready, "readyState" will change to "complete"
  3. Put everything under 'DOMContentLoaded' event listener

onreadystatechange

  document.onreadystatechange = function () {
     if (document.readyState == "complete") {
     // document is ready. Do your stuff here
   }
 }

Source: MDN

DOMContentLoaded

document.addEventListener('DOMContentLoaded', function() {
   console.log('document is ready. I can sleep now');
});

Concerned about stone age browsers: Go to the jQuery source code and use the ready function. In that case you are not parsing+executing the whole library you're are doing only a very small part of it.

Split a String into an array in Swift?

Most of these answers assume the input contains a space - not whitespace, and a single space at that. If you can safely make that assumption, then the accepted answer (from bennett) is quite elegant and also the method I'll be going with when I can.

When we can't make that assumption, a more robust solution needs to cover the following siutations that most answers here don't consider:

  • tabs/newlines/spaces (whitespace), including recurring characters
  • leading/trailing whitespace
  • Apple/Linux (\n) and Windows (\r\n) newline characters

To cover these cases this solution uses regex to convert all whitespace (including recurring and Windows newline characters) to a single space, trims, then splits by a single space:

Swift 3:

let searchInput = "  First \r\n \n \t\t\tMiddle    Last "
let searchTerms = searchInput 
    .replacingOccurrences(
        of: "\\s+",
        with: " ",
        options: .regularExpression
    )
    .trimmingCharacters(in: .whitespaces)
    .components(separatedBy: " ")

// searchTerms == ["First", "Middle", "Last"]

How to get year and month from a date - PHP

$dateValue = '2012-01-05';
$year = date('Y',strtotime($dateValue));
$month = date('F',strtotime($dateValue));

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

Use SSIS to extract and process the information. That way you will have the processing of the XML files separated from SQL Server. You can also do the SSIS transformations on a separate server if needed. Store the phone numbers in a standard format using VARCHAR. NVARCHAR would be unnecessary since we are talking about numbers and maybe a couple of other chars, like '+', ' ', '(', ')' and '-'.

How do I rename the extension for a bunch of files?

Rename file extensions for all files under current directory and sub directories without any other packages (only use shell script):

  1. Create a shell script rename.sh under current directory with the following code:

    #!/bin/bash
    
    for file in $(find . -name "*$1"); do
      mv "$file" "${file%$1}$2"
    done
    
  2. Run it by ./rename.sh .old .new.

    Eg. ./rename.sh .html .txt

What is the difference between i++ & ++i in a for loop?

The difference is that the post-increment operator i++ returns i as it was before incrementing, and the pre-increment operator ++i returns i as it is after incrementing. If you're asking about a typical for loop:

for (i = 0; i < 10; i++)

or

for (i = 0; i < 10; ++i)

They're exactly the same, since you're not using i++ or ++i as a part of a larger expression.

node.js Error: connect ECONNREFUSED; response from server

I had the same problem on my mac, but in my case, the problem was that I did not run the database (sudo mongod) before; the problem was solved when I first ran the mondo sudod on the console and, once it was done, on another console, the connection to the server ...

error : expected unqualified-id before return in c++

if (chapeau) {

You forgot the ending brace to this if statement, so the subsequent else if is considered a syntax error. You need to add the brace when the if statement body is complete:

if (chapeau) {
    cout << "le Professeur Violet";
}
else if (moustaches) {
    cout << "le Colonel Moutarde";
}
// ...

Can we import XML file into another XML file?

Mads Hansen's solution is good but to succeed in reading the external file in .NET 4 took some time to figure out using hints in the comments about resolvers, ProhibitDTD and so on.

This is how it's done:

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.DtdProcessing = DtdProcessing.Parse;
        XmlUrlResolver resolver = new XmlUrlResolver();
        resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;
        settings.XmlResolver = resolver;
        var reader = XmlReader.Create("logfile.xml", settings);
        XmlDocument doc = new XmlDocument();
        doc.Load(reader);
        foreach (XmlElement element in doc.SelectNodes("//event"))
        {
            var ch = element.ChildNodes;
            var count = ch.Count;
        }

logfile.xml:

<?xml version="1.0"?>
<!DOCTYPE logfile [
<!ENTITY events    
 SYSTEM "events.txt">
]>
<logfile>
&events;
</logfile>

events.txt:

<event>
    <item1>item1</item1>
    <item2>item2</item2>
</event>

git diff between two different files

Specify the paths explicitly:

git diff HEAD:full/path/to/foo full/path/to/bar

Check out the --find-renames option in the git-diff docs.

Credit: twaggs.

Adding form action in html in laravel

{{ Form::open(array('action' => "WelcomeController@log_in")) }}
...
{{ Form::close() }}

Comparing two java.util.Dates to see if they are in the same day

Convert dates to Java 8 java.time.LocalDate as seen here.

LocalDate localDate1 = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate localDate2 = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

// compare dates
assertTrue("Not on the same day", localDate1.equals(localDate2));

border-radius not working

in your div class="social-box" css

use

            float:right 

instead of

             float:left

Docker compose port mapping

It's important to point out that all of the above solutions map the port to every interface on your machine. This is less than desirable if you have a public IP address, or your machine has an IP on a large network. Your application may be exposed to a much wider audience than you'd hoped.

redis:
  build:
    context:
    dockerfile: Dockerfile-redis
    ports:
    - "127.0.0.1:3901:3901"

127.0.0.1 is the ip address that maps to the hostname localhost on your machine. So now your application is only exposed over that interface and since 127.0.0.1 is only accessible via your machine, you're not exposing your containers to the entire world.

The documentation explains this further and can be found here: https://docs.docker.com/compose/compose-file/#ports


Note: If you're using Docker for mac this will make the container listen on 127.0.0.1 on the Docker for Mac VM and will not be accessible from your localhost. If I recall correctly.

How do I trim whitespace?

If you want to trim the whitespace off just the beginning and end of the string, you can do something like this:

some_string = "    Hello,    world!\n    "
new_string = some_string.strip()
# new_string is now "Hello,    world!"

This works a lot like Qt's QString::trimmed() method, in that it removes leading and trailing whitespace, while leaving internal whitespace alone.

But if you'd like something like Qt's QString::simplified() method which not only removes leading and trailing whitespace, but also "squishes" all consecutive internal whitespace to one space character, you can use a combination of .split() and " ".join, like this:

some_string = "\t    Hello,  \n\t  world!\n    "
new_string = " ".join(some_string.split())
# new_string is now "Hello, world!"

In this last example, each sequence of internal whitespace replaced with a single space, while still trimming the whitespace off the start and end of the string.

iterate through a map in javascript

I'd use standard javascript:

for (var m in myMap){
    for (var i=0;i<myMap[m].length;i++){
    ... do something with myMap[m][i] ...
    }
} 

Note the different ways of treating objects and arrays.

Escape Character in SQL Server

You can define your escape character, but you can only use it with a LIKE clause.

Example:

SELECT columns FROM table
WHERE column LIKE '%\%%' ESCAPE '\'

Here it will search for % in whole string and this is how one can use ESCAPE identifier in SQL Server.

Invalid default value for 'dateAdded'

Also do note when specifying DATETIME as DATETIME(3) or like on MySQL 5.7.x, you also have to add the same value for CURRENT_TIMESTAMP(3). If not it will keep throwing 'Invalid default value'.

Spring Boot War deployed to Tomcat

I think you're confused by different paradigms here. First, war files and server deployment -- those things belong to Java Enterprise Edition (Java EE). These concepts have no real place in a spring-boot application, which follows a different model.

Spring-boot is responsible for creating an embedded container and running your services within it directly from standard jar files (although it can do a lot more). I think the intent of this model is to support micro-service development -- where each service has its own container and is completely self contained. You can use your code to generate Java EE apps too, but that would be silly considering that spring-boot is a lot easier (for certain types of application/service).

So, given this information you now have to decide what paradigm you're going to follow, and you need to follow that and only that.

Spring-boot is executable -- you just have to run the main method in the App class which you can do from the command line or using your favourite IDE or maven or gradle (tip: maven is the right answer). This will bring up a tomcat server (by default) and your service will be available within it. Given the configuration you posted above your service should be available at: http://localhost:7777/context/help -- the context is meant to be replaced with your context name, which you haven't shared.

You aren't meant to be creating a war, running tomcat, or deploying anything. None of that is necessary in spring-boot. The packaging in your pom should be jar, not war and the scope of the spring-boot-starter-tomcat should be removed -- it certainly isn't provided.

When you run your main method, the console output should tell you the context that you've registered; use that to get the URL right.

Having said all that, spring-boot has to exist in a JEE world for now (until it is widely adopted). For that reason, the spring people have documented an approach to building a war rather than an executable jar, for deployment to a servlet or JEE container. This allows a lot of the spring-boot tech to be used in environments where there are restrictions against using anything but wars (or ears). However, this is a just a response to the fact that such environments are quite common, and is not seen as a necessary, or even desirable, part of the solution.

'list' object has no attribute 'shape'

import numpy
X = numpy.array(the_big_nested_list_you_had)

It's still not going to do what you want; you have more bugs, like trying to unpack a 3-dimensional shape into two target variables in test.

How to enable directory listing in apache web server

Once I changed Options -Index to Options +Index in my conf file, I removed the welcome page and restarted services.

$ sudo rm -f /etc/httpd/conf.d/welcome.conf
$ sudo service httpd restart

I was able to see directory listings after that.

How to get POSTed JSON in Flask?

First of all, the .json attribute is a property that delegates to the request.get_json() method, which documents why you see None here.

You need to set the request content type to application/json for the .json property and .get_json() method (with no arguments) to work as either will produce None otherwise. See the Flask Request documentation:

This will contain the parsed JSON data if the mimetype indicates JSON (application/json, see is_json()), otherwise it will be None.

You can tell request.get_json() to skip the content type requirement by passing it the force=True keyword argument.

Note that if an exception is raised at this point (possibly resulting in a 400 Bad Request response), your JSON data is invalid. It is in some way malformed; you may want to check it with a JSON validator.

With ng-bind-html-unsafe removed, how do I inject HTML?

You indicated that you're using Angular 1.2.0... as one of the other comments indicated, ng-bind-html-unsafe has been deprecated.

Instead, you'll want to do something like this:

<div ng-bind-html="preview_data.preview.embed.htmlSafe"></div>

In your controller, inject the $sce service, and mark the HTML as "trusted":

myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
  // ...
  $scope.preview_data.preview.embed.htmlSafe = 
     $sce.trustAsHtml(preview_data.preview.embed.html);
}

Note that you'll want to be using 1.2.0-rc3 or newer. (They fixed a bug in rc3 that prevented "watchers" from working properly on trusted HTML.)

Is there an upper bound to BigInteger?

The number is held in an int[] - the maximum size of an array is Integer.MAX_VALUE. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE.

Admittedly, this is implementation dependent, not part of the specification.


In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:

BigInteger must support values in the range -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive) and may support values outside of that range.

Implementation note: BigInteger constructors and operations throw ArithmeticException when the result is out of the supported range of -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive).

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

Using sed, Insert a line above or below the pattern?

Insert a new verse after the given verse in your stanza:

sed -i '/^lorem ipsum dolor sit amet$/ s:$:\nconsectetur adipiscing elit:' FILE

How to extract text from the PDF document?

I know that this topic is quite old, but this need is still alive. I read many documents, forum and script and build a new advanced one which supports compressed and uncompressed pdf :

https://gist.github.com/smalot/6183152

Hope it helps everone

How do you transfer or export SQL Server 2005 data to Excel

You could always use ADO to write the results out to the worksheet cells from a recordset object

Spring Boot - Loading Initial Data

Spring Boot allows you to use a simple script to initialize your database, using Spring Batch.

Still, if you want to use something a bit more elaborated to manage DB versions and so on, Spring Boot integrates well with Flyway.

See also:

C++ sorting and keeping track of indexes

If it's possible, you can build the position array using find function, and then sort the array.

Or maybe you can use a map where the key would be the element, and the values a list of its position in the upcoming arrays (A, B and C)

It depends on later uses of those arrays.

How to remove unused imports from Eclipse

Use ALT + CTRL + O. It will organize all the imports. You can find various other options in the "Code" Menu.

EDIT: Sorry it is CTRL + SHIFT + O

How to remove all options from a dropdown using jQuery / JavaScript

You didn't say on which event.Just use below on your event listener.Or in your page load

$('#models').empty()

Then to repopulate

$.getJSON('@Url.Action("YourAction","YourController")',function(data){
 var dropdown=$('#models');
dropdown.empty();  
$.each(data, function (index, item) {
    dropdown.append(
        $('<option>', {
            value: item.valueField,
            text: item.DisplayField
        }, '</option>'))
      }
     )});

Android center view in FrameLayout doesn't work

Set 'center_horizontal' and 'center_vertical' or just 'center' of the layout_gravity attribute of the widget

    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MovieActivity"
    android:id="@+id/mainContainerMovie"
    >


    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#3a3f51b5"
       />

    <ProgressBar
        android:id="@+id/movieprogressbar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal" />
</FrameLayout>

How to Get the HTTP Post data in C#?

This code will list out all the form variables that are being sent in a POST. This way you can see if you have the proper names of the post values.

string[] keys = Request.Form.AllKeys;
for (int i= 0; i < keys.Length; i++) 
{
   Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}

Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

I had the same problem

I fixed that by using two options

contentType: false
processData: false

Actually I Added these two command to my $.ajax({}) function

Adding headers to requests module

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects

jQuery bind to Paste Event, how to get the content of the paste

This work on all browser to get pasted value. And also to creating common method for all text box.

$("#textareaid").bind("paste", function(e){       
    var pastedData = e.target.value;
    alert(pastedData);
} )

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

To follow up, I just ran into this as well. When I installed Node.js there was an option that said Add to PATH (Available After Restart). Seems like Windows just needs a restart to make things work.

Slack URL to open a channel from browser

Sure you can:

https://<organization>.slack.com/messages/<channel>/

for example: https://tikal.slack.com/messages/general/ (of course that for accessing it, you must be part of the team)

Which ChromeDriver version is compatible with which Chrome Browser version?

For starters, all ChromeDriver versions are not compatible with all versions of Chrome.
Sometimes I wake up, run my script, if it breaks, I update the driver. Then it works. Chrome has quietly updated itself without telling me.

For a starting point of finding which chromedrivers go with which chrome versions this link brings you to the current release notes. You can look at previous release notes for earlier versions.

https://chromedriver.storage.googleapis.com/2.26/notes.txt

----------ChromeDriver v2.26 (2016-12-09)----------

Supports Chrome v53-55

This page will show you the current release https://sites.google.com/a/chromium.org/chromedriver/downloads

Converting a string to an integer on Android

There are five ways to convert The First Way :

String str = " 123" ;
int i = Integer.parse(str); 
output : 123

The second way :

String str = "hello123world";
int i = Integer.parse(str.replaceAll("[\\D]" , "" ) );
output : 123

The Third Way :

String str"123";
int i = new Integer(str);
output "123 

The Fourth Way :

String str"123";
int i = Integer.valueOf(Str);
output "123 

The Fifth Way :

String str"123";
int i = Integer.decode(str);
output "123 

There could be other ways But that's what I remember now

Phone mask with jQuery and Masked Input Plugin

As alternative

    function FormatPhone(tt,e){
  //console.log(e.which);
  var t = $(tt);
  var v1 = t.val();
  var k = e.which;
  if(k!=8 && v1.length===18){
    e.preventDefault();
  }
  var q = String.fromCharCode((96 <= k && k <= 105)? k-48 : k);
  if (((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=8 && e.keyCode!=39) {
 e.preventDefault();
  }
  else{
    setTimeout(function(){
      var v = t.val();
      var l = v.length;
      //console.log(l);
      if(k!=8){
        if(l<4){
          t.val('+7 ');
        }
        else if(l===4){
          if(isNaN(q)){
            t.val('+7 (');
          }
          else{
            t.val('+7 ('+q);
          }
        }
        else if(l===7){
          t.val(v+')');
        }
        else if(l===9){
          t.val(v1+' '+q);
        }
        else if(l===13||l===16){
          t.val(v1+'-'+q);
        }
        else if(l>18){
          v=v.substr(0,18);
          t.val(v);
        }
        }
        else{
          if(l<4){
            t.val('+7 ');
          }
        }
    },100);
  }
}

Deleting Elements in an Array if Element is a Certain value VBA

An array is a structure with a certain size. You can use dynamic arrays in vba that you can shrink or grow using ReDim but you can't remove elements in the middle. It's not clear from your sample how your array functionally works or how you determine the index position (eachHdr) but you basically have 3 options

(A) Write a custom 'delete' function for your array like (untested)

Public Sub DeleteElementAt(Byval index As Integer, Byref prLst as Variant)
       Dim i As Integer

        ' Move all element back one position
        For i = index + 1 To UBound(prLst)
            prLst(i - 1) = prLst(i)
        Next

        ' Shrink the array by one, removing the last one
        ReDim Preserve prLst(Len(prLst) - 1)
End Sub

(B) Simply set a 'dummy' value as the value instead of actually deleting the element

If prLst(eachHdr) = "0" Then        
   prLst(eachHdr) = "n/a"
End If

(C) Stop using an array and change it into a VBA.Collection. A collection is a (unique)key/value pair structure where you can freely add or delete elements from

Dim prLst As New Collection

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

It might be because the project has been broken down into different modules.

@SpringBootApplication
@ComponentScan({"com.delivery.request"})
@EntityScan("com.delivery.domain")
@EnableJpaRepositories("com.delivery.repository")
public class WebServiceApplication extends SpringBootServletInitializer {

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

I got this error message from using an oracle database in a docker despite the fact i had publish port to host option "-p 1521:1521". I was using jdbc url that was using ip address 127.0.0.1, i changed it to the host machine real ip address and everything worked then.

event.preventDefault() function not working in IE

return false in your listener should work in all browsers.

$('orderNowForm').addEvent('submit', function () {
    // your code
    return false;
}

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

Try,

 #!/bin/bash
 pause ()
 {
 REPLY=Y
 while [ "$REPLY" == "Y" ] || [ "$REPLY" != "y" ]
 do
  echo -e "\t\tPress 'y' to continue\t\t\tPress 'n' to quit"
  read -n1 -s
      case "$REPLY" in
      "n")  exit                      ;;
      "N")  echo "case sensitive!!"   ;; 
      "y")  clear                     ;;
      "Y")  echo "case sensitive!!"   ;;
      * )  echo "$REPLY is Invalid Option"     ;;
 esac
 done
 }
 pause
 echo "Hi"

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Please check this: https://jsfiddle.net/wazb1jks/3/

_x000D_
_x000D_
navigator.getUserMedia(mediaConstraints, function(stream) {_x000D_
    window.streamReference = stream;_x000D_
}, onMediaError);
_x000D_
_x000D_
_x000D_

Stop Recording

_x000D_
_x000D_
function stopStream() {_x000D_
    if (!window.streamReference) return;_x000D_
_x000D_
    window.streamReference.getAudioTracks().forEach(function(track) {_x000D_
        track.stop();_x000D_
    });_x000D_
_x000D_
    window.streamReference.getVideoTracks().forEach(function(track) {_x000D_
        track.stop();_x000D_
    });_x000D_
_x000D_
    window.streamReference = null;_x000D_
}
_x000D_
_x000D_
_x000D_

Scanner vs. BufferedReader

In currently latest JDK6 release/build (b27), the Scanner has a smaller buffer (1024 chars) as opposed to the BufferedReader (8192 chars), but it's more than sufficient.

As to the choice, use the Scanner if you want to parse the file, use the BufferedReader if you want to read the file line by line. Also see the introductory text of their aforelinked API documentations.

  • Parsing = interpreting the given input as tokens (parts). It's able to give back you specific parts directly as int, string, decimal, etc. See also all those nextXxx() methods in Scanner class.
  • Reading = dumb streaming. It keeps giving back you all characters, which you in turn have to manually inspect if you'd like to match or compose something useful. But if you don't need to do that anyway, then reading is sufficient.

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

The entity type <type> is not part of the model for the current context

For me it was caused because I renamed the entity class.When I rolled it back it was Ok.

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

Create the certificate chain file with the intermediate and root ca.

cat intermediate/certs/intermediate.cert.pem certs/ca.cert.pem > intermediate/certs/ca-chain.cert.pem

chmod 444 intermediate/certs/ca-chain.cert.pem

Then verfify

openssl verify -CAfile intermediate/certs/ca-chain.cert.pem \
  intermediate/certs/www.example.com.cert.pem

www.example.com.cert.pem: OK Deploy the certific

Scp command syntax for copying a folder from local machine to a remote server

scp -r C:/site user@server_ip:path

path is the place, where site will be copied into the remote server


EDIT: As I said in my comment, try pscp, as you want to use scp using PuTTY.

The other option is WinSCP

Convert a number into a Roman Numeral in javaScript

This solution runs only one loop and has the minimun object to map numerals to roman letters

function RomantoNumeral(r){
  let result = 0,
      keys = {M:1000, D:500, C:100, L:50, C:100, L:50, X:10, V:5, I:1},
      order = Object.keys(keys),
      rom = Array.from(r) 

  rom.forEach((e, i)=>{
    if( i  < rom.length -1 && order.indexOf(e) > order.indexOf(rom[i+1])){
      result -= keys[e]
    } else {
      result +=keys[e]
    }
  })  
  return result
}

RomantoNumeral('MMDCCCXXXVII') #2837

How does database indexing work?

Classic example "Index in Books"

Consider a "Book" of 1000 pages, divided by 10 Chapters, each section with 100 pages.

Simple, huh?

Now, imagine you want to find a particular Chapter that contains a word "Alchemist". Without an index page, you have no other option than scanning through the entire book/Chapters. i.e: 1000 pages.

This analogy is known as "Full Table Scan" in database world.

enter image description here

But with an index page, you know where to go! And more, to lookup any particular Chapter that matters, you just need to look over the index page, again and again, every time. After finding the matching index you can efficiently jump to that chapter by skipping the rest.

But then, in addition to actual 1000 pages, you will need another ~10 pages to show the indices, so totally 1010 pages.

Thus, the index is a separate section that stores values of indexed column + pointer to the indexed row in a sorted order for efficient look-ups.

Things are simple in schools, isn't it? :P

Launch programs whose path contains spaces

Try:-

Dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Run("""c:\Program Files\Mozilla Firefox\firefox.exe""")
Set objShell = Nothing

Note the extra ""s in the string. Since the path to the exe contains spaces it needs to be contained with in quotes. (In this case simply using "firefox.exe" would work).

Also bear in mind that many programs exist in the c:\Program Files (x86) folder on 64 bit versions of Windows.

Google Chrome Printing Page Breaks

I've used the following approach successfully in all major browsers including Chrome:

<!DOCTYPE html>

<html>
  <head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    <title>Paginated HTML</title>
    <style type="text/css" media="print">
      div.page
      {
        page-break-after: always;
        page-break-inside: avoid;
      }
    </style>
  </head>
  <body>
    <div class="page">
      <h1>This is Page 1</h1>
    </div>
    <div class="page">
      <h1>This is Page 2</h1>
    </div>
    <div class="page">
      <h1>This is Page 3</h1>
    </div>
  </body>
</html>

This is a simplified example. In the real code, each page div contains many more elements.

Lock, mutex, semaphore... what's the difference?

Most problems can be solved using (i) just locks, (ii) just semaphores, ..., or (iii) a combination of both! As you may have discovered, they're very similar: both prevent race conditions, both have acquire()/release() operations, both cause zero or more threads to become blocked/suspected... Really, the crucial difference lies solely on how they lock and unlock.

  • A lock (or mutex) has two states (0 or 1). It can be either unlocked or locked. They're often used to ensure only one thread enters a critical section at a time.
  • A semaphore has many states (0, 1, 2, ...). It can be locked (state 0) or unlocked (states 1, 2, 3, ...). One or more semaphores are often used together to ensure that only one thread enters a critical section precisely when the number of units of some resource has/hasn't reached a particular value (either via counting down to that value or counting up to that value).

For both locks/semaphores, trying to call acquire() while the primitive is in state 0 causes the invoking thread to be suspended. For locks - attempts to acquire the lock is in state 1 are successful. For semaphores - attempts to acquire the lock in states {1, 2, 3, ...} are successful.

For locks in state state 0, if same thread that had previously called acquire(), now calls release, then the release is successful. If a different thread tried this -- it is down to the implementation/library as to what happens (usually the attempt ignored or an error is thrown). For semaphores in state 0, any thread can call release and it will be successful (regardless of which thread previous used acquire to put the semaphore in state 0).

From the preceding discussion, we can see that locks have a notion of an owner (the sole thread that can call release is the owner), whereas semaphores do not have an owner (any thread can call release on a semaphore).


What causes a lot of confusion is that, in practice they are many variations of this high-level definition.

Important variations to consider:

  • What should the acquire()/release() be called? -- [Varies massively]
  • Does your lock/semaphore use a "queue" or a "set" to remember the threads waiting?
  • Can your lock/semaphore be shared with threads of other processes?
  • Is your lock "reentrant"? -- [Usually yes].
  • Is your lock "blocking/non-blocking"? -- [Normally non-blocking are used as blocking locks (aka spin-locks) cause busy waiting].
  • How do you ensure the operations are "atomic"?

These depends on your book / lecturer / language / library / environment.
Here's a quick tour noting how some languages answer these details.


C, C++ (pthreads)

  • A mutex is implemented via pthread_mutex_t. By default, they can't be shared with any other processes (PTHREAD_PROCESS_PRIVATE), however mutex's have an attribute called pshared. When set, so the mutex is shared between processes (PTHREAD_PROCESS_SHARED).
  • A lock is the same thing as a mutex.
  • A semaphore is implemented via sem_t. Similar to mutexes, semaphores can be shared between threasds of many processes or kept private to the threads of one single process. This depends on the pshared argument provided to sem_init.

python (threading.py)

  • A lock (threading.RLock) is mostly the same as C/C++ pthread_mutex_ts. Both are both reentrant. This means they may only be unlocked by the same thread that locked it. It is the case that sem_t semaphores, threading.Semaphore semaphores and theading.Lock locks are not reentrant -- for it is the case any thread can perform unlock the lock / down the semaphore.
  • A mutex is the same as a lock (the term is not used often in python).
  • A semaphore (threading.Semaphore) is mostly the same as sem_t. Although with sem_t, a queue of thread ids is used to remember the order in which threads became blocked when attempting to lock it while it is locked. When a thread unlocks a semaphore, the first thread in the queue (if there is one) is chosen to be the new owner. The thread identifier is taken off the queue and the semaphore becomes locked again. However, with threading.Semaphore, a set is used instead of a queue, so the order in which threads became blocked is not stored -- any thread in the set may be chosen to be the next owner.

Java (java.util.concurrent)

  • A lock (java.util.concurrent.ReentrantLock) is mostly the same as C/C++ pthread_mutex_t's, and Python's threading.RLock in that it also implements a reentrant lock. Sharing locks between processes is harder in Java because of the JVM acting as an intermediary. If a thread tries to unlock a lock it doesn't own, an IllegalMonitorStateException is thrown.
  • A mutex is the same as a lock (the term is not used often in Java).
  • A semaphore (java.util.concurrent.Semaphore) is mostly the same as sem_t and threading.Semaphore. The constructor for Java semaphores accept a fairness boolean parameter that control whether to use a set (false) or a queue (true) for storing the waiting threads.

In theory, semaphores are often discussed, but in practice, semaphores aren't used so much. A semaphore only hold the state of one integer, so often it's rather inflexible and many are needed at once -- causing difficulty in understanding code. Also, the fact that any thread can release a semaphore is sometimes undesired. More object-oriented / higher-level synchronization primitives / abstractions such as "condition variables" and "monitors" are used instead.

AppCompat v7 r21 returning error in values.xml?

In my case with Eclipse IDE, I had the same problem and the solution was:
1- Install the latest available API (SDK Platform & Google APIs)
2- Create the project with the following settings:

  • Compile With: use the latest API version available at the time
  • the other values can receive values according at your requirements (look at the meaning of each one in previous comments)

Format bytes to kilobytes, megabytes, gigabytes

Pseudocode:

$base = log($size) / log(1024);
$suffix = array("", "k", "M", "G", "T")[floor($base)];
return pow(1024, $base - floor($base)) . $suffix;

How to differentiate single click event and double click event?

let clickTimes = 0;
let timer = null;
roundBox.click = function (e) {
  clearTimeout(timer);
  timer = setTimeout(() => { // ????
    console.log("single click");
  }, 600);
  clickTimes++;

  if (clickTimes == 2) { // ??
    clearTimeout(timer);
    clickTimes = 0;
    console.log("double click");
    toggleExpanded(id);
  }
}

How to insert a row between two rows in an existing excel with HSSF (Apache POI)

I've implemented this in Kotlin like this:

fun Sheet.buildRow ( rowNum:Int ) : Row {
    val templateRow = this.getRow( rowNum )
    this.shiftRows( rowNum+1, sheet.lastRowNum, 1 )
    val newRow = this.createRow( rowNum+1 )
    templateRow.cellIterator().forEach {
        newRow.createCell( it.columnIndex ).cellStyle = it.cellStyle
    }
    return templateRow
}

It doesn't copy the cell values, just the format. Should be applicable to Java as well.

How may I sort a list alphabetically using jQuery?

improvement based on Jeetendra Chauhan's answer

$('ul.menu').each(function(){
    $(this).children('li').sort((a,b)=>a.innerText.localeCompare(b.innerText)).appendTo(this);
});

why i consider it an improvement:

  1. using each to support running on more than one ul

  2. using children('li') instead of ('ul li') is important because we only want to process direct children and not descendants

  3. using the arrow function (a,b)=> just looks better (IE not supported)

  4. using vanilla innerText instead of $(a).text() for speed improvement

  5. using vanilla localeCompare improves speed in case of equal elements (rare in real life usage)

  6. using appendTo(this) instead of using another selector will make sure that even if the selector catches more than one ul still nothing breaks

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

In my case, it was Blend SDK missed out on TeamCity machine. This caused the error due incorrect way of assembly resolving then.

Using wire or reg with input or output in Verilog

An output reg foo is just shorthand for output foo_wire; reg foo; assign foo_wire = foo. It's handy when you plan to register that output anyway. I don't think input reg is meaningful for module (perhaps task). input wire and output wire are the same as input and output: it's just more explicit.

Easiest way to mask characters in HTML(5) text input

Yes, according to HTML5 drafts you can use the pattern attribute to specify the allowed input using a regular expression. For some types of data, you can use special input fields like <input type=email>. But these features still widely lack support or have qualitatively poor support.

Skipping every other element after the first

Slice notation a[start_index:end_index:step]

return a[::2]

where start_index defaults to 0 and end_index defaults to the len(a).

Java 8 - Best way to transform a list: map or foreach?

Don't worry about any performance differences, they're going to be minimal in this case normally.

Method 2 is preferable because

  1. it doesn't require mutating a collection that exists outside the lambda expression,

  2. it's more readable because the different steps that are performed in the collection pipeline are written sequentially: first a filter operation, then a map operation, then collecting the result (for more info on the benefits of collection pipelines, see Martin Fowler's excellent article),

  3. you can easily change the way values are collected by replacing the Collector that is used. In some cases you may need to write your own Collector, but then the benefit is that you can easily reuse that.

How can I determine whether a specific file is open in Windows?

Use Process Explorer to find the process id. Then use Handle to find out what files are open.

Eg handle -p

I like this approach because you are using utilities from Microsoft itself.

Can't operator == be applied to generic types in C#?

As others have said, it will only work when T is constrained to be a reference type. Without any constraints, you can compare with null, but only null - and that comparison will always be false for non-nullable value types.

Instead of calling Equals, it's better to use an IComparer<T> - and if you have no more information, EqualityComparer<T>.Default is a good choice:

public bool Compare<T>(T x, T y)
{
    return EqualityComparer<T>.Default.Equals(x, y);
}

Aside from anything else, this avoids boxing/casting.

How can I convert my Java program to an .exe file?

javapackager

The Java Packager tool compiles, packages, and prepares Java and JavaFX applications for distribution. The javapackager command is the command-line version.

– Oracle's documentation

The javapackager utility ships with the JDK. It can generate .exe files with the -native exe flag, among many other things.

WinRun4J

WinRun4j is a java launcher for windows. It is an alternative to javaw.exe and provides the following benefits:

  • Uses an INI file for specifying classpath, main class, vm args, program args.
  • Custom executable name that appears in task manager.
  • Additional JVM args for more flexible memory use.
  • Built-in icon replacer for custom icon.
  • [more bullet points follow]

– WinRun4J's webpage

WinRun4J is an open source utility. It has many features.

packr

Packages your JAR, assets and a JVM for distribution on Windows, Linux and Mac OS X, adding a native executable file to make it appear like a native app. Packr is most suitable for GUI applications.

– packr README

packr is another open source tool.

JSmooth

JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself.

– JSmooth's website

JSmooth is open source and has features, but it is very old. The last release was in 2007.

JexePack

JexePack is a command line tool (great for automated scripting) that allows you to package your Java application (class files), optionally along with its resources (like GIF/JPG/TXT/etc), into a single compressed 32-bit Windows EXE, which runs using Sun's Java Runtime Environment. Both console and windowed applications are supported.

– JexePack's website

JexePack is trialware. Payment is required for production use, and exe files created with this tool will display "reminders" without payment. Also, the last release was in 2013.

InstallAnywhere

InstallAnywhere makes it easy for developers to create professional installation software for any platform. With InstallAnywhere, you’ll adapt to industry changes quickly, get to market faster and deliver an engaging customer experience. And know the vulnerability of your project’s OSS components before you ship.

– InstallAnywhere's website

InstallAnywhere is a commercial/enterprise package that generates installers for Java-based programs. It's probably capable of creating .exe files.

Executable JAR files

As an alternative to .exe files, you can create a JAR file that automatically runs when double-clicked, by adding an entry point to the JAR manifest.


For more information

An excellent source of information on this topic is Excelsior's article "Convert Java to EXE – Why, When, When Not and How".

See also the companion article "Best JAR to EXE Conversion Tools, Free and Commercial".

What is the Swift equivalent to Objective-C's "@synchronized"?

Using Bryan McLemore answer, I extended it to support objects that throw in a safe manor with the Swift 2.0 defer ability.

func synchronized( lock:AnyObject, block:() throws -> Void ) rethrows
{
    objc_sync_enter(lock)
    defer {
        objc_sync_exit(lock)
    }

    try block()
}

Fatal error: Call to undefined function: ldap_connect()

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

    extension=php_ldap.dll

  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin Restart Apache. You can now use functions of the LDAP Module!

Dynamically replace img src attribute with jQuery

You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.

http://api.jquery.com/attr/

A better way to approach replacing a series of images source would be to loop through each and check it's source.

Example:

$('img').each(function () {
  var curSrc = $(this).attr('src');
  if ( curSrc === 'http://example.com/smith.gif' ) {
      $(this).attr('src', 'http://example.com/johnson.gif');
  }
  if ( curSrc === 'http://example.com/williams.gif' ) {
      $(this).attr('src', 'http://example.com/brown.gif');
  }
});

Which terminal command to get just IP address and nothing else?

Few answers appear to be using the newer ip command (replacement for ifconfig) so here is one that uses ip addr, grep, and awk to simply print the IPv4 address associated with the wlan0 interface:

ip addr show wlan0|grep inet|grep -v inet6|awk '{print $2}'|awk '{split($0,a,"/"); print a[1]}'

While not the most compact or fancy solution, it is (arguably) easy to understand (see explanation below) and modify for other purposes, such as getting the last 3 octets of the MAC address like this:

ip addr show wlan0|grep link/ether|awk '{print $2}'|awk '{split($0,mac,":"); print mac[4] mac[5] mac[6]}'

Explanation: ip addr show wlan0 outputs information associated with the network interface named wlan0, which should be similar to this:

4: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether dc:a6:32:04:06:ab brd ff:ff:ff:ff:ff:ff
    inet 172.18.18.1/24 brd 172.18.18.255 scope global noprefixroute wlan0
       valid_lft forever preferred_lft forever
    inet6 fe80::d340:5e4b:78e0:90f/64 scope link 
       valid_lft forever preferred_lft forever

Next grep inet filters out the lines that don't contain "inet" (IPv4 and IPv6 configuration) and grep -v inet6 filters out the remaining lines that do contain "inet6", which should result in a single line like this one:

    inet 172.18.18.1/24 brd 172.18.18.255 scope global noprefixroute wlan0

Finally, the first awk extract the "172.18.18.1/24" field and the second removes the network mask shorthand, leaving just the IPv4 address.

Also, I think it's worth mentioning that if you are scripting then there are often many richer and/or more robust tools for obtaining this information, which you might want to use instead. For example, if using Node.js there is ipaddr-linux, if using Ruby there is linux-ip-parser, etc.

See also https://unix.stackexchange.com/questions/119269/how-to-get-ip-address-using-shell-script

How to reload page every 5 seconds?

If you are developing and testing in Firefox, there's a plug-in called "ReloadEvery" is available, which allows you to reload the page at the specified intervals.

Custom toast on Android: a simple example

Code for MainActivity.java file.

package com.android_examples.com.toastbackgroundcolorchange;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {

 Button BT;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 BT = (Button)findViewById(R.id.button1);
 BT.setOnClickListener(new View.OnClickListener() {

 @Override
 public void onClick(View v) {

 Toast ToastMessage = Toast.makeText(getApplicationContext(),"Change Toast Background color",Toast.LENGTH_SHORT);
 View toastView = ToastMessage.getView();
 toastView.setBackgroundResource(R.layout.toast_background_color);
 ToastMessage.show();

 }
 });
 }
}

Code for activity_main.xml layout file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.android_examples.com.toastbackgroundcolorchange.MainActivity" >

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:text="CLICK HERE TO SHOW TOAST MESSAGE WITH DIFFERENT BACKGROUND COLOR INCLUDING BORDER" />

</RelativeLayout>

Code for toast_background_color.xml layout file created in res->layout folder.

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

 <stroke
    android:width="3dp"
    android:color="#ffffff" ></stroke>
<padding android:left="20dp" android:top="20dp"
    android:right="20dp" android:bottom="20dp" />
<corners android:radius="10dp" />
<gradient android:startColor="#ff000f"
    android:endColor="#ff0000"
    android:angle="-90"/>

</shape>

add new element in laravel collection object

If you want to add item to the beginning of the collection you can use prepend:

$item->prepend($product, 'key');

Python Requests throwing SSLError

I was having a similar or the same certification validation problem. I read that OpenSSL versions less than 1.0.2, which requests depends upon sometimes have trouble validating strong certificates (see here). CentOS 7 seems to use 1.0.1e which seems to have the problem.

I wasn't sure how to get around this problem on CentOS, so I decided to allow weaker 1024bit CA certificates.

import certifi # This should be already installed as a dependency of 'requests'
requests.get("https://example.com", verify=certifi.old_where())

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

If you are a windows user the other solutions here probably won't solve your problem.

I use Windows 7 64-Bit + Git-1.7.7.1-preview20111027 and the solution was to copy my keys from C:\users\user\.ssh to C:\Program Files (x86)\Git\.ssh. That's where this git client looks for the keys when pushing to heroku.

I hope this helps.

Debug assertion failed. C++ vector subscript out of range

this type of error usually occur when you try to access data through the index in which data data has not been assign. for example

//assign of data in to array
for(int i=0; i<10; i++){
   arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}

the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.

cell format round and display 2 decimal places

Input: 0 0.1 1000

=FIXED(E5,2)

Output: 0.00 0.10 1,000.00

=TEXT(E5,"0.00")

Output: 0.00 0.10 1000.00

Note: As you can see FIXED add a coma after a thousand, where TEXT does not.

Given a filesystem path, is there a shorter way to extract the filename without its extension?

try

System.IO.Path.GetFileNameWithoutExtension(path); 

demo

string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string result;

result = Path.GetFileNameWithoutExtension(fileName);
Console.WriteLine("GetFileNameWithoutExtension('{0}') returns '{1}'", 
    fileName, result);

result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    path, result);

// This code produces output similar to the following:
//
// GetFileNameWithoutExtension('C:\mydir\myfile.ext') returns 'myfile'
// GetFileName('C:\mydir\') returns ''

https://msdn.microsoft.com/en-gb/library/system.io.path.getfilenamewithoutextension%28v=vs.80%29.aspx

How can I upgrade NumPy?

The error you mentioned happens when you have two versions of NumPy on your system. As you mentioned, the version of NumPy you imported is still not upgraded since you tried to upgrade it through pip (it will upgrade the version existing in '/Library/Python/2.7/site-packages' ).

However Python still loads the packages from '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy' where the pre-installed packages live.

In order to upgrade that version you have to use easy_install. The other way around this problem is using virtualenv and setting up a new environment with all the requirements you need.

How do I register a DLL file on Windows 7 64-bit?

Knowing the error message would be rather valuable. It is meant to provide info, even though it doesn't make any sense to you it does to us. Being forced to guess, I'd say that the DLL is a 32-bit DirectX filter. In which case this should be the proper course of action:

cd c:\windows\syswow64
move ..\system32\dllname.ax .
regsvr32.exe dllname.ax

This must be run at an elevated command prompt so that UAC cannot stop the registry access that's required. Ask more questions about this at superuser.com

How to validate GUID is a GUID

There is no guarantee that a GUID contains alpha characters. FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF is a valid GUID so is 00000000-0000-0000-0000-000000000000 and anything in between.

If you are using .NET 4.0, you can use the answer above for the Guid.Parse and Guid.TryParse. Otherwise, you can do something like this:

public static bool TryParseGuid(string guidString, out Guid guid)
{
    if (guidString == null) throw new ArgumentNullException("guidString");
    try
    {
        guid = new Guid(guidString);
        return true;
    }
    catch (FormatException)
    {
        guid = default(Guid);
        return false;
    }
}

Set icon for Android application

1-Create Your icon in Photoshop Or Coreldraw by size 256*256

note that use PNG file format if you want to have a transparent icon

2-Upload Your icon in https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html

3-Set your setting on this site enter image description here

4-Download the zip file automatically created by the webpage by clicking on download button enter image description here

5-Extract the zip file and copy res folder to you project library enter image description here

note that res folder contain all size icon

6-finally you need to set the manifest to use icon

<application android:icon="@drawable/your_icon" >
.... 
</application>

Given a DateTime object, how do I get an ISO 8601 date in string format?

DateTime.UtcNow.ToString("s")

Returns something like 2008-04-10T06:30:00

UtcNow obviously returns a UTC time so there is no harm in:

string.Concat(DateTime.UtcNow.ToString("s"), "Z")

Is there a conditional ternary operator in VB.NET?

Depends upon the version. The If operator in VB.NET 2008 is a ternary operator (as well as a null coalescence operator). This was just introduced, prior to 2008 this was not available. Here's some more info: Visual Basic If announcement

Example:

Dim foo as String = If(bar = buz, cat, dog)

[EDIT]

Prior to 2008 it was IIf, which worked almost identically to the If operator described Above.

Example:

Dim foo as String = IIf(bar = buz, cat, dog)

Generate a random date between two other dates

Since Python 3 timedelta supports multiplication with floats, so now you can do:

import random
random_date = start + (end - start) * random.random()

given that start and end are of the type datetime.datetime. For example, to generate a random datetime within the next day:

import random
from datetime import datetime, timedelta

start = datetime.now()
end = start + timedelta(days=1)
random_date = start + (end - start) * random.random()

Remove a parameter to the URL with JavaScript

function removeParam(parameter)
{
  var url=document.location.href;
  var urlparts= url.split('?');

 if (urlparts.length>=2)
 {
  var urlBase=urlparts.shift(); 
  var queryString=urlparts.join("?"); 

  var prefix = encodeURIComponent(parameter)+'=';
  var pars = queryString.split(/[&;]/g);
  for (var i= pars.length; i-->0;)               
      if (pars[i].lastIndexOf(prefix, 0)!==-1)   
          pars.splice(i, 1);
  url = urlBase+'?'+pars.join('&');
  window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .

}
return url;
}

This will resolve your problem

Deserialize json object into dynamic object using Json.net

If you just deserialize to dynamic you will get a JObject back. You can get what you want by using an ExpandoObject.

var converter = new ExpandoObjectConverter();    
dynamic message = JsonConvert.DeserializeObject<ExpandoObject>(jsonString, converter);

How do you iterate through every file/directory recursively in standard C++?

Answers of getting all file names recursively with C++11 for Windows and Linux(with experimental/filesystem):
For Windows:

#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <windows.h>
void getFiles_w(string path, vector<string>& files) {
    intptr_t hFile = 0; 
    struct _finddata_t fileinfo;  
    string p; 
    if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) {
        do {
            if ((fileinfo.attrib & _A_SUBDIR)) {
                if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
                    getFiles(p.assign(path).append("/").append(fileinfo.name), files);
            }
            else {
                files.push_back(p.assign(path).append("/").append(fileinfo.name));
            }
        } while (_findnext(hFile, &fileinfo) == 0);
    }
}

For Linux:

#include <experimental/filesystem>
bool getFiles(std::experimental::filesystem::path path, vector<string>& filenames) {
    namespace stdfs = std::experimental::filesystem;
    // http://en.cppreference.com/w/cpp/experimental/fs/directory_iterator
    const stdfs::directory_iterator end{} ;
    
    for (stdfs::directory_iterator iter{path}; iter != end ; ++iter) {
        // http://en.cppreference.com/w/cpp/experimental/fs/is_regular_file 
        if (!stdfs::is_regular_file(*iter)) { // comment out if all names (names of directories tc.) are required 
            if (getFiles(iter->path(), filenames)) 
                return true;
        }
        else {
            filenames.push_back(iter->path().string()) ;
            cout << iter->path().string() << endl;  
        }
    }
    return false;
}

Just remember to link -lstdc++fs when you compile it with g++ in Linux.

How to properly compare two Integers in Java?

== checks for reference equality, however when writing code like:

Integer a = 1;
Integer b = 1;

Java is smart enough to reuse the same immutable for a and b, so this is true: a == b. Curious, I wrote a small example to show where java stops optimizing in this way:

public class BoxingLol {
    public static void main(String[] args) {
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            Integer a = i;
            Integer b = i;
            if (a != b) {
                System.out.println("Done: " + i);
                System.exit(0);
            }
        }
        System.out.println("Done, all values equal");
    }
}

When I compile and run this (on my machine), I get:

Done: 128

Change the mouse pointer using JavaScript

Look at this page: http://www.webcodingtech.com/javascript/change-cursor.php. Looks like you can access cursor off of style. This page shows it being done with the entire page, but I'm sure a child element would work just as well.

document.body.style.cursor = 'wait';

Removing ul indentation with CSS

Remove this from #info:

    margin-left:auto;

Add this for your header:

#info p {
    text-align: center;
}

Do you need the fixed width etc.? I removed the in my opinion not necessary stuff and centered the header with text-align.

Sample
http://jsfiddle.net/Vc8CB/

firefox proxy settings via command line

This is the final compiled solution which worked for me... Tried and tested...

Steps to Change Proxy settings in Mozilla Firefox via cmd in Windows

  1. cd /D "%APPDATA%\Mozilla\Firefox\Profiles"
  2. cd *.default

To Replace Already Present Proxy Settings with User-defined ones

  1. powershell -Command "(gc prefs.js) -replace 'user_pref(\"network.proxy.http\", \"already present IP\")\;', 'user_pref(\"network.proxy.http\", \"your http proxy ip\");' | Set-Content prefs.js"
  2. powershell -Command "(gc prefs.js) -replace 'user_pref(\"network.proxy.http_port\", already present port)\;', 'user_pref(\"network.proxy.http_port\", your http proxy port);' | Set-Content prefs.js"
  3. powershell -Command "(gc prefs.js) -replace 'user_pref(\"network.proxy.share_proxy_settings\", already present value)\;', 'user_pref(\"network.proxy.share_proxy_settings\", true);' | Set-Content prefs.js"
  4. powershell -Command "(gc prefs.js) -replace 'user_pref(\"network.proxy.type\", already present value)\;', 'user_pref(\"network.proxy.type\", 1);' | Set-Content prefs.js"

    0 - No Proxy

    1 - Manual Proxy Configuration

    4 - Auto detect Proxy Settings

    5 - Use System Settings(default)

  5. cd %windir%

To Check Already Present Proxy Settings

  1. cd C:\Users\{username}\AppData\Roaming\Mozilla\Firefox\Profiles\sat2m7dr.default\
  2. find /i "network.proxy" prefs.js

To Start Firefox from CMD using your defined proxy settings

  1. cd C:\Program Files\
  2. cd "Mozilla Firefox"
  3. firefox.exe -ProfileManager
  4. Select default from the list (default-release is selected by default) and click ok.

NOTE: You may not have to run step 14 again. Instead you can directly run firefox.exe

Running python script inside ipython

from within the directory of "my_script.py" you can simply do:

%run ./my_script.py

Random string generation with upper case letters and digits

A simpler, faster but slightly less random way is to use random.sample instead of choosing each letter separately, If n-repetitions are allowed, enlarge your random basis by n times e.g.

import random
import string

char_set = string.ascii_uppercase + string.digits
print ''.join(random.sample(char_set*6, 6))

Note: random.sample prevents character reuse, multiplying the size of the character set makes multiple repetitions possible, but they are still less likely then they are in a pure random choice. If we go for a string of length 6, and we pick 'X' as the first character, in the choice example, the odds of getting 'X' for the second character are the same as the odds of getting 'X' as the first character. In the random.sample implementation, the odds of getting 'X' as any subsequent character are only 6/7 the chance of getting it as the first character

How to add image background to btn-default twitter-bootstrap button?

This works with font awesome:

<button class="btn btn-outline-success">
   <i class="fa fa-print" aria-hidden="true"></i>
   Print
</button>

What is the difference between the float and integer data type when the size is the same?

Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point

Does adding a duplicate value to a HashSet/HashMap replace the previous value

HashMap basically contains Entry which subsequently contains Key(Object) and Value(Object).Internally HashSet are HashMap and HashMap do replace values as some of you already pointed..but does it really replaces the keys???No ..and that is the trick here. HashMap keeps its value as key in the underlying HashMap and value is just a dummy object.So if u try to reinsert same Value in HashMap(Key in underlying Map).It just replaces the dummy value and not the Key(Value for HashSet).

Look at the below code for HashSet Class:

public boolean  [More ...] add(E e) {

   return map.put(e, PRESENT)==null;
}

Here e is the value for HashSet but key for underlying map.and key is never replaced. Hope i am able to clear the confusion.

How to write subquery inside the OUTER JOIN Statement

I think you don't have to use sub query in this scenario.You can directly left outer join the DEPRMNT table .

While using Left Outer Join ,don't use columns in the RHS table of the join in the where condition, you ll get wrong output

How to fix Error: this class is not key value coding-compliant for the key tableView.'

You have your storyboard set up to expect an outlet called tableView but the actual outlet name is myTableView.

If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.

Iterating over and deleting from Hashtable in Java

So you know the key, value pair that you want to delete in advance? It's just much clearer to do this, then:

 table.delete(key);
 for (K key: table.keySet()) {
    // do whatever you need to do with the rest of the keys
 }

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

I finally found a solution. I wasted hours just trying to figure what this issue was. I tried deleting all those files suggested above and it didn't work for me, I tried adding new inbound rules to firewall for myslqd.exe and it didn't work. The thing that is causing this error is MySQL port is misconfigured and the fix was really simple. if you are using Wamp or Xampp go to Main Folder/Bin/mysql/mysql/ and find a file named my.ini

Open my.ini file press CTRL + F and inside it search for PORT and change whatever value of port to - 3306 and save file;

After that go to Wamp icon at the bottom of the taskbar (system tray) and left click choose mysql option and click "test port 3306 used" and see if it gives you any error. you can also click use other port other than whatever is shown there and port 3306.

Goodluck. if it works comment.

enter image description here

Dynamically add item to jQuery Select2 control that uses AJAX

To get dynamic tagging to work with ajax, here's what I did.

Select2 version 3.5

This is easy in version 3.5 because it offers the createSearchChoice hook. It even works for multiple select, as long as multiple: true and tags: true are set.

HTML

<input type="hidden" name="locations" value="Whistler, BC" />

JS

$('input[name="locations"]').select2({
  tags: true,
  multiple: true,
  createSearchChoice: function(term, data) {
    if (!data.length)
      return { id: term, text: term };
    },
  ajax: {
    url: '/api/v1.1/locations',
    dataType: 'json'
  }
});

The idea here is to use select2's createSearchChoice hook which passes you both the term that the user entered and the ajax response (as data). If ajax returns an empty list, then tell select2 to offer the user-entered term as an option.

Demo: https://johnny.netlify.com/select2-examples/version3


Select2 version 4.X

Version 4.X doesn't have a createSearchChoice hook anymore, but here's how I did the same thing.

HTML

  <select name="locations" multiple>
    <option value="Whistler, BC" selected>Whistler, BC</option>
  </select>

JS

$('select[name="locations"]').select2({
  ajax: {
    url: '/api/v1.1/locations',
    dataType: 'json',
    data: function(params) {
      this.data('term', params.term);
      return params;
    },
    processResults: function(data) {
      if (data.length)
        return {
          results: data
        };
      else
        return {
          results: [{ id: this.$element.data('term'), text: this.$element.data('term') }]
        };
    }
  }
});

The ideas is to stash the term that the user typed into jQuery's data store inside select2's data hook. Then in select2's processResults hook, I check if the ajax response is empty. If it is, I grab the stashed term that the user typed and return it as an option to select2.

Demo: https://johnny.netlify.com/select2-examples/version4

Sending emails in Node.js?

Mature, simple to use and has lots of features if simple isn't enought: Nodemailer: https://github.com/andris9/nodemailer (note correct url!)

SSL cert "err_cert_authority_invalid" on mobile chrome only

I guess you should install CA certificate form one if authority canter:

ssl_trusted_certificate ssl/SSL_CA_Bundle.pem;

PHP save image file

No need to create a GD resource, as someone else suggested.

$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($input));

Note: this solution only works if you're setup to allow fopen access to URLs. If the solution above doesn't work, you'll have to use cURL.

windows batch file rename

Use REN Command

Ren is for rename

ren ( where the file is located ) ( the new name )

example

ren C:\Users\&username%\Desktop\aaa.txt bbb.txt

it will change aaa.txt to bbb.txt

Your code will be :

ren (file located)AAA_a001.jpg a001.AAA.jpg

ren (file located)BBB_a002.jpg a002.BBB.jpg

ren (file located)CCC_a003.jpg a003.CCC.jpg

and so on

IT WILL NOT WORK IF THERE IS SPACES!

Hope it helps :D

Data at the root level is invalid

For the record:

"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".

mkdir's "-p" option

Note that -p is an argument to the mkdir command specifically, not the whole of Unix. Every command can have whatever arguments it needs.

In this case it means "parents", meaning mkdir will create a directory and any parents that don't already exist.

How to change the DataTable Column Name?

Try this:

dataTable.Columns["Marks"].ColumnName = "SubjectMarks";

how to include js file in php?

I have never been a fan of closing blocks of PHP to output content to the browser, I prefer to have my output captured so if at some point within my logic I decide I want to change my output (after output has already been sent) I can just delete the current buffer.

But as Pekka said, the main reason you are having issues with your javascript inclusion is because your using href to specify the location of the js file where as you should be using src.

If you have a functions file with your functions inside then add something like:

function js_link($src)
{
    if(file_exists("my/html/root/" . $src))
    {
        //we know it will exists within the HTTP Context
        return sprintf("<script type=\"text/javascript\" src=\"%s\"></script>",$src);
    }
    return "<!-- Unable to load " . $src . "-->";
}

The n in your code without the need for closing your blocks with ?> you can just use:

echo js_link("jquery/1.6/main.js");

Cross-Origin Request Blocked

@Egidius, when creating an XMLHttpRequest, you should use

var xhr = new XMLHttpRequest({mozSystem: true});

What is mozSystem?

mozSystem Boolean: Setting this flag to true allows making cross-site connections without requiring the server to opt-in using CORS. Requires setting mozAnon: true, i.e. this can't be combined with sending cookies or other user credentials. This only works in privileged (reviewed) apps; it does not work on arbitrary webpages loaded in Firefox.

Changes to your Manifest

On your manifest, do not forget to include this line on your permissions:

"permissions": {
       "systemXHR" : {},
}

Chrome - ERR_CACHE_MISS

This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.

writing to serial port from linux command line

If you want to use hex codes, you should add -e option to enable interpretation of backslash escapes by echo (but the result is the same as with echoCtrlRCtrlB). And as wallyk said, you probably want to add -n to prevent the output of a newline:

echo -en '\x12\x02' > /dev/ttyS0

Also make sure that /dev/ttyS0 is the port you want.

PHP header(Location: ...): Force URL change in address bar

use

header("Location: index.php"); //this work in my site

read more on header() at php documentation.

Call a React component method from outside

I use this helper method to render components and return an component instance. Methods can be called on that instance.

static async renderComponentAt(componentClass, props, parentElementId){
         let componentId = props.id;
        if(!componentId){
            throw Error('Component has no id property. Please include id:"...xyz..." to component properties.');
        }

        let parentElement = document.getElementById(parentElementId);

        return await new Promise((resolve, reject) => {
            props.ref = (component)=>{
                resolve(component);
            };
            let element = React.createElement(componentClass, props, null);
            ReactDOM.render(element, parentElement);
        });
    }

How to implement 2D vector array?

I'm not exactly sure what the problem is, as your example code has several errors and doesn't really make it clear what you're trying to do. But here's how you add to a specific row of a 2D vector:

// declare 2D vector
vector< vector<int> > myVector;
// make new row (arbitrary example)
vector<int> myRow(1,5);
myVector.push_back(myRow);
// add element to row
myVector[0].push_back(1);

Does this answer your question? If not, could you try to be more specific as to what you are having trouble with?

Adding a color background and border radius to a Layout

You don't need the separate fill item. In fact, it's invalid. You just have to add a solid block to the shape. The subsequent stroke draws on top of the solid:

<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">

    <corners android:radius="5dp" />
    <solid android:color="@android:color/white" />
    <stroke
        android:width="1dip"
        android:color="@color/bggrey" />
</shape>

You also don't need the layer-list if you only have one shape.

accessing a docker container from another container

Using docker-compose, services are exposed to each other by name by default. Docs.
You could also specify an alias like;

version: '2.1'
services:
  mongo:
    image: mongo:3.2.11
  redis:
    image: redis:3.2.10
  api:
    image: some-image
    depends_on:
      - mongo
      - solr
    links:
      - "mongo:mongo.openconceptlab.org"
      - "solr:solr.openconceptlab.org"
      - "some-service:some-alias"

And then access the service using the specified alias as a host name, e.g mongo.openconceptlab.org for mongo in this case.

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);
});

"Unmappable character for encoding UTF-8" error

The compiler is using the UTF-8 character encoding to read your source file. But the file must have been written by an editor using a different encoding. Open your file in an editor set to the UTF-8 encoding, fix the quote mark, and save it again.

Alternatively, you can find the Unicode point for the character and use a Unicode escape in the source code. For example, the character A can be replaced with the Unicode escape \u0041.

By the way, you don't need to use the begin- and end-line anchors ^ and $ when using the matches() method. The entire sequence must be matched by the regular expression when using the matches() method. The anchors are only useful with the find() method.

Removing duplicates from a list of lists

a_list = [
          [1,2],
          [1,2],
          [2,3],
          [3,4]
]

print (list(map(list,set(map(tuple,a_list)))))

outputs: [[1, 2], [3, 4], [2, 3]]

check if "it's a number" function in Oracle

if condition is null then it is number

IF(rtrim(P_COD_LEGACY, '0123456789') IS NULL) THEN
                return 1;
          ELSE
                return 0;
          END IF;

How to create a zip file in Java

This is how you create a zip file from a source file:

String srcFilename = "C:/myfile.txt";
String zipFile = "C:/myfile.zip";

try {
    byte[] buffer = new byte[1024];
    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);         
    File srcFile = new File(srcFilename);
    FileInputStream fis = new FileInputStream(srcFile);
    zos.putNextEntry(new ZipEntry(srcFile.getName()));          
    int length;
    while ((length = fis.read(buffer)) > 0) {
        zos.write(buffer, 0, length);
    }
    zos.closeEntry();
    fis.close();
    zos.close();            
}
catch (IOException ioe) {
    System.out.println("Error creating zip file" + ioe);
}

How to show data in a table by using psql command line interface?

On windows use the name of the table in quotes: TABLE "user"; or SELECT * FROM "user";

Undefined reference to `sin`

You have compiled your code with references to the correct math.h header file, but when you attempted to link it, you forgot the option to include the math library. As a result, you can compile your .o object files, but not build your executable.

As Paul has already mentioned add "-lm" to link with the math library in the step where you are attempting to generate your executable.

In the comment, linuxD asks:

Why for sin() in <math.h>, do we need -lm option explicitly; but, not for printf() in <stdio.h>?

Because both these functions are implemented as part of the "Single UNIX Specification". This history of this standard is interesting, and is known by many names (IEEE Std 1003.1, X/Open Portability Guide, POSIX, Spec 1170).

This standard, specifically separates out the "Standard C library" routines from the "Standard C Mathematical Library" routines (page 277). The pertinent passage is copied below:

Standard C Library

The Standard C library is automatically searched by cc to resolve external references. This library supports all of the interfaces of the Base System, as defined in Volume 1, except for the Math Routines.

Standard C Mathematical Library

This library supports the Base System math routines, as defined in Volume 1. The cc option -lm is used to search this library.

The reasoning behind this separation was influenced by a number of factors:

  1. The UNIX wars led to increasing divergence from the original AT&T UNIX offering.
  2. The number of UNIX platforms added difficulty in developing software for the operating system.
  3. An attempt to define the lowest common denominator for software developers was launched, called 1988 POSIX.
  4. Software developers programmed against the POSIX standard to provide their software on "POSIX compliant systems" in order to reach more platforms.
  5. UNIX customers demanded "POSIX compliant" UNIX systems to run the software.

The pressures that fed into the decision to put -lm in a different library probably included, but are not limited to:

  1. It seems like a good way to keep the size of libc down, as many applications don't use functions embedded in the math library.
  2. It provides flexibility in math library implementation, where some math libraries rely on larger embedded lookup tables while others may rely on smaller lookup tables (computing solutions).
  3. For truly size constrained applications, it permits reimplementations of the math library in a non-standard way (like pulling out just sin() and putting it in a custom built library.

In any case, it is now part of the standard to not be automatically included as part of the C language, and that's why you must add -lm.

How to convert JSON to string?

Try to Use JSON.stringify

Regards

How to start automatic download of a file in Internet Explorer?

One more :

var a = document.createElement('a');
a.setAttribute('href', dataUri);
a.setAttribute('download', filename);

var aj = $(a);
aj.appendTo('body');
aj[0].click();
aj.remove();

How to use the PI constant in C++

Values like M_PI, M_PI_2, M_PI_4, etc are not standard C++ so a constexpr seems a better solution. Different const expressions can be formulated that calculate the same pi and it concerns me whether they (all) provide me the full accuracy. The C++ standard does not explicitly mention how to calculate pi. Therefore, I tend to fall back to defining pi manually. I would like to share the solution below which supports all kind of fractions of pi in full accuracy.

#include <ratio>
#include <iostream>

template<typename RATIO>
constexpr double dpipart()
{
    long double const pi = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899863;
    return static_cast<double>(pi * RATIO::num / RATIO::den);
}

int main()
{
    std::cout << dpipart<std::ratio<-1, 6>>() << std::endl;
}