javax.mail.AuthenticationFailedException: failed to connect, no password specified?
In addition to RMT's answer. I also had to modify the code a bit.
- Transport.send should be accessed statically
- therefor, transport.connect did not do anything for me, I only needed to set the connection info in the initial Properties object.
here is my sample send() methods. The config object is just a dumb data container.
public boolean send(String to, String from, String subject, String text) {
return send(new String[] {to}, from, subject, text);
}
public boolean send(String[] to, String from, String subject, String text) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", config.host);
props.put("mail.smtp.user", config.username);
props.put("mail.smtp.port", config.port);
props.put("mail.smtp.password", config.password);
Session session = Session.getInstance(props, new SmtpAuthenticator(config));
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress[] addressTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++) {
addressTo[i] = new InternetAddress(to[i]);
}
message.setRecipients(Message.RecipientType.TO, addressTo);
message.setSubject(subject);
message.setText(text);
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
return true;
}
Sending email in .NET through Gmail
Include this,
using System.Net.Mail;
And then,
MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = Convert.ToInt16("587");
client.Credentials = new System.Net.NetworkCredential("[email protected]","password");
client.EnableSsl = true;
client.Send(sendmsg);
What is the behavior difference between return-path, reply-to and from?
I had to add a Return-Path header in emails send by a Redmine instance.
I agree with greatwolf only the sender can determine a correct (non default) Return-Path.
The case is the following :
E-mails are send with the default email address : [email protected]
But we want that the real user initiating the action receives the bounce emails, because he will be the one knowing how to fix wrong recipients emails (and not the application adminstrators that have other cats to whip :-) ).
We use this and it works perfectly well with exim on the application server and zimbra as the final company mail server.
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?
Anderscc has got it correct. Thanks. It worked for me but not 100%.
I had to set
$mail->SMTPDebug = 0;
Setting it to 1, can cause errors especially if you are passing some data as json to next page. Example - Performing verification if mail is sent, using json to pass data through ajax.
I had to lower my gmail account security settings to get rid of errors:
" SMTP connect() failed " and " SMTP ERROR: Password command failed "
Solution:
This problem can be caused by either 'less secure' applications trying to use the email account (this is according to google help, not sure how they judge what is secure and what is not) OR if you are trying to login several time in a row OR if you change countries (for example use VPN, move code to different server or actually try to login from different part of the world).
Links that fix the problem (you must be logged into google account):
Note:
You can go to the following stackoverflow answer link for more detailed reference.
https://stackoverflow.com/a/25175234
How can I send emails through SSL SMTP with the .NET Framework?
Here is an example of how to send email through GMail which also uses SSL/465. Minor tweaking of the code below should work!
using System.Web.Mail;
using System;
public class MailSender
{
public static bool SendEmail(
string pGmailEmail,
string pGmailPassword,
string pTo,
string pSubject,
string pBody,
System.Web.Mail.MailFormat pFormat,
string pAttachmentPath)
{
try
{
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserver",
"smtp.gmail.com");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
"465");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusing",
"2");
//sendusing: cdoSendUsingPort, value 2, for sending the message using
//the network.
//smtpauthenticate: Specifies the mechanism used when authenticating
//to an SMTP
//service over the network. Possible values are:
//- cdoAnonymous, value 0. Do not authenticate.
//- cdoBasic, value 1. Use basic clear-text authentication.
//When using this option you have to provide the user name and password
//through the sendusername and sendpassword fields.
//- cdoNTLM, value 2. The current process security context is used to
// authenticate with the service.
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1");
//Use 0 for anonymous
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusername",
pGmailEmail);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendpassword",
pGmailPassword);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
"true");
myMail.From = pGmailEmail;
myMail.To = pTo;
myMail.Subject = pSubject;
myMail.BodyFormat = pFormat;
myMail.Body = pBody;
if (pAttachmentPath.Trim() != "")
{
MailAttachment MyAttachment =
new MailAttachment(pAttachmentPath);
myMail.Attachments.Add(MyAttachment);
myMail.Priority = System.Web.Mail.MailPriority.High;
}
System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
System.Web.Mail.SmtpMail.Send(myMail);
return true;
}
catch (Exception ex)
{
throw;
}
}
}
Relay access denied on sending mail, Other domain outside of network
If it is giving you relay access denied when you are trying to send an email from outside your network to a domain that your server is not authoritative for then it means your receive connector does not grant you the permissions for sending/relaying. Most likely what you need to do is to authenticate to the server to be granted the permissions for relaying but that does depend upon the configuration of your receive connector. In Exchange 2007/2010/2013 you would need to enable ExchangeUsers permission group as well as an authentication mechanism such as Basic authentication.
Once you're sure your receive connector is configured make sure your email client is configured for authentication as well for the SMTP server. It depends upon your server setup but normally for Exchange you would configure the username by itself, no need for the domain to appended or prefixed to it.
To test things out with authentication via telnet you can go over my post here for directions: https://jefferyland.wordpress.com/2013/05/28/essential-exchange-troubleshooting-send-email-via-telnet/
What's the difference between Sender, From and Return-Path?
So, over SMTP when a message is submitted, the SMTP envelope (sender, recipients, etc.) is different from the actual data of the message.
The Sender
header is used to identify in the message who submitted it. This is usually the same as the From
header, which is who the message is from. However, it can differ in some cases where a mail agent is sending messages on behalf of someone else.
The Return-Path
header is used to indicate to the recipient (or receiving MTA) where non-delivery receipts are to be sent.
For example, take a server that allows users to send mail from a web page. So, [email protected]
types in a message and submits it. The server then sends the message to its recipient with From
set to [email protected]
. The actual SMTP submission uses different credentials, something like [email protected]
. So, the sender
header is set to [email protected]
, to indicate the From
header doesn't indicate who actually submitted the message.
In this case, if the message cannot be sent, it's probably better for the agent to receive the non-delivery report, and so Return-Path
would also be set to [email protected]
so that any delivery reports go to it instead of the sender.
If you are doing just that, a form submission to send e-mail, then this is probably a direct parallel with how you'd set the headers.
Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1
You need to tell it that you are using SSL:
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
In case you miss anything, here is working code:
String d_email = "[email protected]",
d_uname = "Name",
d_password = "urpassword",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "[email protected]",
m_subject = "Indoors Readable File: " + params[0].getName(),
m_text = "This message is from Indoor Positioning App. Required file(s) are attached.";
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SMTPAuthenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
try {
msg.setSubject(m_subject);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
Transport transport = session.getTransport("smtps");
transport.connect(d_host, Integer.valueOf(d_port), d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (AddressException e) {
e.printStackTrace();
return false;
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
Are email addresses case sensitive?
Per @l3x, it depends.
There are clearly two sets of general situations where the correct answer can be different, along with a third which is not as general:
a) You are a user sending private mails:
Very few modern email systems implement case sensitivity, so you are probably fine to ignore case and choose whatever case you feel like using. There is no guarantee that all your mails will be delivered - but so few mails would be negatively affected that you should not worry about it.
b) You are developing mail software:
See RFC5321 2.4 excerpt at the bottom.
When you are developing mail software, you want to be RFC-compliant. You can make your own users' email addresses case insensitive if you want to (and you probably should). But in order to be RFC compliant, you MUST treat outside addresses as case sensitive.
c) Managing business-owned lists of email addresses as an employee:
It is possible that the same email recipient is added to a list more than once - but using different case. In this situation though the addresses are technically different, it might result in a recipient receiving duplicate emails. How you treat this situation is similar to situation a) in that you are probably fine to treat them as duplicates and to remove a duplicate entry. It is better to treat these as special cases however, by sending a "reminder" mail to both addresses to ask them if the case of the email address is accurate.
From a legal standpoint, if you remove a duplicate without acknowledgement/permission from both addresses, you can be held responsible for leaking private information/authentication to an unauthorised address simply because two actually-separate recipients have the same address with different cases.
Excerpt from RFC5321 2.4:
The local-part of a mailbox MUST BE treated as case sensitive.
Therefore, SMTP implementations MUST take care to preserve the case of
mailbox local-parts. In particular, for some hosts, the user "smith"
is different from the user "Smith". However, exploiting the case
sensitivity of mailbox local-parts impedes interoperability and is
discouraged.
How to send email using simple SMTP commands via Gmail?
As no one has mentioned - I would suggest to use great tool for such purpose - swaks
# yum info swaks
Installed Packages
Name : swaks
Arch : noarch
Version : 20130209.0
Release : 3.el6
Size : 287 k
Repo : installed
From repo : epel
Summary : Command-line SMTP transaction tester
URL : http://www.jetmore.org/john/code/swaks
License : GPLv2+
Description : Swiss Army Knife SMTP: A command line SMTP tester. Swaks can test
: various aspects of your SMTP server, including TLS and AUTH.
It has a lot of options and can do almost everything you want.
GMAIL: STARTTLS, SSLv3 (and yes, in 2016 gmail still support sslv3)
$ echo "Hello world" | swaks -4 --server smtp.gmail.com:587 --from [email protected] --to [email protected] -tls --tls-protocol sslv3 --auth PLAIN --auth-user [email protected] --auth-password 7654321 --h-Subject "Test message" --body -
=== Trying smtp.gmail.com:587...
=== Connected to smtp.gmail.com.
<- 220 smtp.gmail.com ESMTP h8sm76342lbd.48 - gsmtp
-> EHLO www.example.net
<- 250-smtp.gmail.com at your service, [193.243.156.26]
<- 250-SIZE 35882577
<- 250-8BITMIME
<- 250-STARTTLS
<- 250-ENHANCEDSTATUSCODES
<- 250-PIPELINING
<- 250-CHUNKING
<- 250 SMTPUTF8
-> STARTTLS
<- 220 2.0.0 Ready to start TLS
=== TLS started with cipher SSLv3:RC4-SHA:128
=== TLS no local certificate set
=== TLS peer DN="/C=US/ST=California/L=Mountain View/O=Google Inc/CN=smtp.gmail.com"
~> EHLO www.example.net
<~ 250-smtp.gmail.com at your service, [193.243.156.26]
<~ 250-SIZE 35882577
<~ 250-8BITMIME
<~ 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
<~ 250-ENHANCEDSTATUSCODES
<~ 250-PIPELINING
<~ 250-CHUNKING
<~ 250 SMTPUTF8
~> AUTH PLAIN AGFhQxsZXguaGhMGdATGV4X2hoYtYWlsLmNvbQBS9TU1MjQ=
<~ 235 2.7.0 Accepted
~> MAIL FROM:<[email protected]>
<~ 250 2.1.0 OK h8sm76342lbd.48 - gsmtp
~> RCPT TO:<[email protected]>
<~ 250 2.1.5 OK h8sm76342lbd.48 - gsmtp
~> DATA
<~ 354 Go ahead h8sm76342lbd.48 - gsmtp
~> Date: Wed, 17 Feb 2016 09:49:03 +0000
~> To: [email protected]
~> From: [email protected]
~> Subject: Test message
~> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
~>
~> Hello world
~>
~>
~> .
<~ 250 2.0.0 OK 1455702544 h8sm76342lbd.48 - gsmtp
~> QUIT
<~ 221 2.0.0 closing connection h8sm76342lbd.48 - gsmtp
=== Connection closed with remote host.
YAHOO: TLS aka SMTPS, tlsv1.2
$ echo "Hello world" | swaks -4 --server smtp.mail.yahoo.com:465 --from [email protected] --to [email protected] --tlsc --tls-protocol tlsv1_2 --auth PLAIN --auth-user [email protected] --auth-password 7654321 --h-Subject "Test message" --body -
=== Trying smtp.mail.yahoo.com:465...
=== Connected to smtp.mail.yahoo.com.
=== TLS started with cipher TLSv1.2:ECDHE-RSA-AES128-GCM-SHA256:128
=== TLS no local certificate set
=== TLS peer DN="/C=US/ST=California/L=Sunnyvale/O=Yahoo Inc./OU=Information Technology/CN=smtp.mail.yahoo.com"
<~ 220 smtp.mail.yahoo.com ESMTP ready
~> EHLO www.example.net
<~ 250-smtp.mail.yahoo.com
<~ 250-PIPELINING
<~ 250-SIZE 41697280
<~ 250-8 BITMIME
<~ 250 AUTH PLAIN LOGIN XOAUTH2 XYMCOOKIE
~> AUTH PLAIN AGFhQxsZXguaGhMGdATGV4X2hoYtYWlsLmNvbQBS9TU1MjQ=
<~ 235 2.0.0 OK
~> MAIL FROM:<[email protected]>
<~ 250 OK , completed
~> RCPT TO:<[email protected]>
<~ 250 OK , completed
~> DATA
<~ 354 Start Mail. End with CRLF.CRLF
~> Date: Wed, 17 Feb 2016 10:08:28 +0000
~> To: [email protected]
~> From: [email protected]
~> Subject: Test message
~> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
~>
~> Hello world
~>
~>
~> .
<~ 250 OK , completed
~> QUIT
<~ 221 Service Closing transmission
=== Connection closed with remote host.
I have been using swaks to send email notifications from nagios via gmail for last 5 years without any problem.
problem with php mail 'From' header
I had the same Issue, I checked the php.net site. And found the right format.
This is my updated code.
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: ' . $fromName . ' <' . $fromEmail .'>' . " \r\n" .
'Reply-To: '. $fromEmail . "\r\n" .
'X-Mailer: PHP/' . phpversion();
The \r\n should be in double quotes(") itself, the single quotes(') will not work.
Using JavaMail with TLS
With Simple Java Mail 5.0.0 (simplejavamail.org) it is very straightforward and the library will take care of all the Session properties for you.
Here's an example using Google's SMTP servers:
Email email = EmailBuilder.startingBlank()
.from("lollypop", "[email protected]")
.to("C.Cane", "[email protected]")
.withSubject("hey")
.withPlainText("We should meet up!")
.withHTMLText("<b>We should meet up!</b>")
.buildEmail();
MailerBuilder.withSMTPServer("smtp.gmail.com", 25, "user", "pass", SMTP_TLS)
.buildMailer()
.sendMail(email);
MailerBuilder.withSMTPServer("smtp.gmail.com", 587, "user", "pass", SMTP_TLS)
.buildMailer()
.sendMail(email);
MailerBuilder.withSMTPServer("smtp.gmail.com", 465, "user", "pass", SMTP_SSL)
.buildMailer()
.sendMail(email);
If you have two-factor login turned on, you need to generate an application specific password from your Google account.
Sending email with PHP from an SMTP server
There are some SMTP servers that work without authentication, but if the server requires authentication, there is no way to circumvent that.
PHP's built-in mail functions are very limited - specifying the SMTP server is possible in WIndows only. On *nix, mail()
will use the OS's binaries.
If you want to send E-Mail to an arbitrary SMTP server on the net, consider using a library like SwiftMailer. That will enable you to use, for example, Google Mail's outgoing servers.
5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error
@Reshma- In case you have not figured it yet, here are below things that I tried and it solved the same issue.
Make sure that NetworkCredentials you set are correct. For example in my case since it was office SMTP, user id had to be used in the NetworkCredential along with domain name and not actual email id.
You need to set "UseDefaultCredentials" to false first and then set Credentials. If you set "UseDefaultCredentials" after that it resets the NetworkCredential to null.
Hope it helps.
Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25
For anyone looking for a full solution, I got this working with the following code based on maximdim's answer:
import javax.mail.*
import javax.mail.internet.*
private class SMTPAuthenticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication('[email protected]', 'test1234');
}
}
def d_email = "[email protected]",
d_uname = "email",
d_password = "password",
d_host = "smtp.gmail.com",
d_port = "465", //465,587
m_to = "[email protected]",
m_subject = "Testing",
m_text = "Hey, this is the testing email."
def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")
def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);
def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))
Transport transport = session.getTransport("smtps");
transport.connect(d_host, 465, d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
What is the difference between ports 465 and 587?
587 vs. 465
These port assignments are specified by the Internet Assigned Numbers Authority (IANA):
- Port 587: [SMTP] Message submission (SMTP-MSA), a service that accepts submission of email from email clients (MUAs). Described in RFC 6409.
- Port 465: URL Rendezvous Directory for SSM (entirely unrelated to email)
Historically, port 465 was initially planned for the SMTPS encryption and authentication “wrapper” over SMTP, but it was quickly deprecated (within months, and over 15 years ago) in favor of STARTTLS over SMTP (RFC 3207). Despite that fact, there are probably many servers that support the deprecated protocol wrapper, primarily to support older clients that implemented SMTPS. Unless you need to support such older clients, SMTPS and its use on port 465 should remain nothing more than an historical footnote.
The hopelessly confusing and imprecise term, SSL, has often been used to indicate the SMTPS wrapper and TLS to indicate the STARTTLS protocol extension.
For completeness: Port 25
- Port 25: Simple Mail Transfer (SMTP-MTA), a service that accepts submission of email from other servers (MTAs or MSAs). Described in RFC 5321.
Sources:
How to check if smtp is working from commandline (Linux)
Syntax for establishing a raw network connection using telnet is this:
telnet {domain_name} {port_number}
So telnet to your smtp server like
telnet smtp.mydomain.com 25
And copy and paste the below
helo client.mydomain.com
mail from:<[email protected]>
rcpt to:<[email protected]>
data
From: [email protected]
Subject: test mail from command line
this is test number 1
sent from linux box
.
quit
Note : Do not forgot the "." at the end which represents the end of the message.
The "quit" line exits ends the session.
Sending email with gmail smtp with codeigniter email library
According to the CI docs (CodeIgniter Email Library)...
If you prefer not to set preferences using the above method, you can
instead put them into a config file. Simply create a new file called
the email.php, add the $config array in that file. Then save the file
at config/email.php and it will be used automatically. You will NOT
need to use the $this->email->initialize() function if you save your
preferences in a config file.
I was able to get this to work by putting all the settings into application/config/email.php.
$config['useragent'] = 'CodeIgniter';
$config['protocol'] = 'smtp';
//$config['mailpath'] = '/usr/sbin/sendmail';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_user'] = '[email protected]';
$config['smtp_pass'] = 'YOURPASSWORDHERE';
$config['smtp_port'] = 465;
$config['smtp_timeout'] = 5;
$config['wordwrap'] = TRUE;
$config['wrapchars'] = 76;
$config['mailtype'] = 'html';
$config['charset'] = 'utf-8';
$config['validate'] = FALSE;
$config['priority'] = 3;
$config['crlf'] = "\r\n";
$config['newline'] = "\r\n";
$config['bcc_batch_mode'] = FALSE;
$config['bcc_batch_size'] = 200;
Then, in one of the controller methods I have something like:
$this->load->library('email'); // Note: no $config param needed
$this->email->from('[email protected]', '[email protected]');
$this->email->to('[email protected]');
$this->email->subject('Test email from CI and Gmail');
$this->email->message('This is a test.');
$this->email->send();
Also, as Cerebro wrote, I had to uncomment out this line in my php.ini file and restart PHP:
extension=php_openssl.dll
Is SMTP based on TCP or UDP?
In theory SMTP can be handled by either TCP, UDP, or some 3rd party protocol.
As defined in RFC 821, RFC 2821, and RFC 5321:
SMTP is independent of the particular transmission subsystem and
requires only a reliable ordered data stream channel.
In addition, the Internet Assigned Numbers Authority has allocated port 25 for both TCP and UDP for use by SMTP.
In practice however, most if not all organizations and applications only choose to implement the TCP protocol. For example, in Microsoft's port listing port 25 is only listed for TCP and not UDP.
The big difference between TCP and UDP that makes TCP ideal here is that TCP checks to make sure that every packet is received and re-sends them if they are not whereas UDP will simply send packets and not check for receipt. This makes UDP ideal for things like streaming video where every single packet isn't as important as keeping a continuous flow of packets from the server to the client.
Considering SMTP, it makes more sense to use TCP over UDP. SMTP is a mail transport protocol, and in mail every single packet is important. If you lose several packets in the middle of the message the recipient might not even receive the message and if they do they might be missing key information. This makes TCP more appropriate because it ensures that every packet is delivered.
How to send an email with Gmail as provider using Python?
I ran into a similar problem and stumbled on this question. I got an SMTP Authentication Error but my user name / pass was correct. Here is what fixed it. I read this:
https://support.google.com/accounts/answer/6010255
In a nutshell, google is not allowing you to log in via smtplib because it has flagged this sort of login as "less secure", so what you have to do is go to this link while you're logged in to your google account, and allow the access:
https://www.google.com/settings/security/lesssecureapps
Once that is set (see my screenshot below), it should work.
Login now works:
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login('[email protected]', 'me_pass')
Response after change:
(235, '2.7.0 Accepted')
Response prior:
smtplib.SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 g66sm2224117qgf.37 - gsmtp')
Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:
https://accounts.google.com/DisplayUnlockCaptcha
Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.
UPDATE: This doesn't seem to work right away you may be stuck for a while getting this error in smptlib:
235 == 'Authentication successful'
503 == 'Error: already authenticated'
The message says to use the browser to sign in:
SMTPAuthenticationError: (534, '5.7.9 Please log in with your web browser and then try again. Learn more at\n5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qo11sm4014232igb.17 - gsmtp')
After enabling 'lesssecureapps', go for a coffee, come back, and try the 'DisplayUnlockCaptcha' link again. From user experience, it may take up to an hour for the change to kick in. Then try the sign-in process again.
How to configure PHP to send e-mail?
Here's the link that gives me the answer and we use gmail:
Install the "fake sendmail for windows". If you are not using XAMPP you can download it here: http://glob.com.au/sendmail/sendmail.zip
Modify the php.ini file to use it (commented out the other lines):
mail function
For Win32 only.
SMTP = smtp.gmail.com
smtp_port = 25
For Win32 only.
sendmail_from = <e-mail username>@gmail.com
For Unix only.
You may supply arguments as well (default: sendmail -t -i
).
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(ignore the "Unix only" bit, since we actually are using sendmail)
You then have to configure the "sendmail.ini" file in the directory where sendmail was installed:
sendmail
smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=<username>
auth_password=<password>
force_sender=<e-mail username>@gmail.com
Mail multipart/alternative vs multipart/mixed
Mixed Subtype
The "mixed" subtype of "multipart" is intended for use when the body
parts are independent and need to be bundled in a particular order.
Any "multipart" subtypes that an implementation does not recognize
must be treated as being of subtype "mixed".
Alternative Subtype
The "multipart/alternative" type is syntactically identical to
"multipart/mixed", but the semantics are different. In particular,
each of the body parts is an "alternative" version of the same
information
Source
php function mail() isn't working
I think you are not configured properly,
if you are using XAMPP then you can easily send mail from localhost.
for example you can configure C:\xampp\php\php.ini
and c:\xampp\sendmail\sendmail.ini
for gmail to send mail.
in C:\xampp\php\php.ini
find extension=php_openssl.dll
and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.
in php.ini file find [mail function]
and change
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(use the above send mail path only and it will work)
Now Open C:\xampp\sendmail\sendmail.ini
. Replace all the existing code in sendmail.ini with following code
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]
Now you have done!! create php file with mail function and send mail from localhost.
Update
First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()
).
You can set the following settings in your PHP.ini:
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
php.ini & SMTP= - how do you pass username & password
- Install Postfix (Sendmail-compatible).
- Edit
/etc/postfix/main.cf
to read:
#Relay config
relayhost = smtp.server.net
smtp_use_tls=yes
smtp_sasl_auth_enable=yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/postfix/cacert.pem
smtp_sasl_security_options = noanonymous
- Create
/etc/postfix/sasl_passwd
, enter:
smtp.server.net username:password
Type # /usr/sbin/postmap sasl_passwd
Then run: service postfix reload
Now PHP will run mail as usual with the sendmail -t -i
command and Postfix will intercept it and relay it to your SMTP server that you provided.
SMTP error 554
Just had this issue with an Outlook client going through a Exchange server to an external address on Windows XP. Clearing the temp files seemed to do the trick.
(WAMP/XAMP) send Mail using SMTP localhost
Method 1 (Preferred) - Using hMailServer
After installation, you need the following configuration to properly send mail from wampserver:
1) When you first open hMailServer Administrator, you need to add a new domain.
2) Click on the "Add Domain ..." button at the Welcome page.
3) Under the domain text field, enter your computer's IP, in this case it should be 127.0.0.1.
4) Click on the Save button.
5) Go to Settings>Protocols>SMTP and select "Delivery of Email" tab
6) Enter "localhost" in the localhost name field.
7) Click on the Save button.
If you need to send mail using a FROM addressee of another computer, you need to allow deliveries from External to External accounts. To do that, follow these steps:
1) Go to Settings>Advanced>IP Ranges and double click on "My Computer" which should have IP address of 127.0.0.1
2) Check the Allow Deliveries from External to External accounts checkbox.
3) Save settings using Save button.
(However, Windows Live/Hotmail has denied all emails coming from dynamic IPs, which most residential computers are using. The workaround is to use Gmail account )
Note to use Gmail users :
1) Go to Settings>Protocols>SMTP and select "Delivery of Email" tab
2) Enter "smtp.gmail.com" in the Remote Host name field.
3) Enter "465" as the port number
4) Check "Server requires authentication"
5) Enter gmail address in the Username
6) Enter gmail password in the password
7) Check "Use SSL"
(Note, From field doesnt function with gmail)
*p.s. For some people it might also be needed to untick everything under require SMTP authentication
in :
- for local : Settings>Advanced>IP Ranges>"My Computer"
- for external : Settings>Advanced>IP Ranges>"Internet"
Method 2 - Using SendMail
You can use SendMail installation.
Method 3 - Using different methods
Use any of these methods.
phpmailer - The following SMTP Error: Data not accepted
I was experiencing this same problem. In my instance the send mail was timing out because my Exchange server was relaying email to a server on the internet. That server had exceeded it's bandwidth quota. Apparently php mailer has some built in timeout and it wasn't long enough to see the actual message.
How to configure SMTP settings in web.config
I don't have enough rep to answer ClintEastwood, and the accepted answer is correct for the Web.config file. Adding this in for code difference.
When your mailSettings are set on Web.config, you don't need to do anything other than new up your SmtpClient and .Send. It finds the connection itself without needing to be referenced. You would change your C# from this:
SmtpClient smtpClient = new SmtpClient("smtp.sender.you", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username", "password");
smtpClient.Credentials = credentials;
smtpClient.Send(msgMail);
To this:
SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(msgMail);
How to send email in ASP.NET C#
If you want to generate your email bodies in razor, you can use Mailzory. Also, you can download the nuget package from here.
// template path
var viewPath = Path.Combine("Views/Emails", "hello.cshtml");
// read the content of template and pass it to the Email constructor
var template = File.ReadAllText(viewPath);
var email = new Email(template);
// set ViewBag properties
email.ViewBag.Name = "Johnny";
email.ViewBag.Content = "Mailzory Is Funny";
// send email
var task = email.SendAsync("[email protected]", "subject");
task.Wait()
Attach a file from MemoryStream to a MailMessage in C#
Here is the sample code.
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);
writer.Write("Hello its my sample file");
writer.Flush();
writer.Dispose();
ms.Position = 0;
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
attach.ContentDisposition.FileName = "myFile.txt";
// I guess you know how to send email with an attachment
// after sending email
ms.Close();
Edit 1
You can specify other file types by System.Net.Mime.MimeTypeNames like System.Net.Mime.MediaTypeNames.Application.Pdf
Based on Mime Type you need to specify correct extension in FileName for instance "myFile.pdf"
How to send email via Django?
My site is hosted on Godaddy
and I have a private email registered on the same.
These are the settings which worked for me:
In settings.py:
EMAIL_HOST = 'mail.domain.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'abcdef'
DEFAULT_FROM_EMAIL = '[email protected]'
SERVER_EMAIL = '[email protected]'
EMAIL_PORT = 25
EMAIL_USE_TLS = False
In shell:
from django.core.mail import EmailMessage
email = EmailMessage('Subject', 'Body', to=['[email protected]'])
email.send()
Then I got "1" as the O/P i.e. Success. And I received the mail too. :)
- What is the meaning of domain.com?
Send inline image in email
sending 2 images vb.net code convert for C# online converter.
Public Function SendEmail(Optional ByVal p_AsHTML As Boolean = False, Optional ByVal p_themEmail As String = "") As Boolean
Dim client As SmtpClient = New SmtpClient ''("FMSERVER.FMINNOVATIONS.COM.AU")
'Dim fromAddress As MailAddress = New MailAddress(Me.FromEmail, "WSMenterprise")
'Dim toAddress As MailAddress
Try
Dim aMessage As New MailMessage()
'(New MailAddress(Me.FromEmail, "WSMenterprise"), New MailAddress(anAdd))
If _fromAddress IsNot Nothing Then
If _fromName IsNot Nothing Then
aMessage.From = New MailAddress(_fromAddress, _fromName)
Else
aMessage.From = New MailAddress(_fromAddress)
End If
End If
For Each anAdd As String In _To
aMessage.To.Add(New MailAddress(anAdd))
Next
For Each cc As String In _CC
aMessage.CC.Add(New MailAddress(cc))
Next
For Each bcc As String In _BCC
aMessage.Bcc.Add(New MailAddress(bcc))
Next
aMessage.Subject = _Subject
aMessage.IsBodyHtml = p_AsHTML
If _EmailLogo Is Nothing Then
aMessage.Body = _Body
Else
If p_themEmail.ToString().ToLower.Contains("dexus") Then
Dim htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), Nothing, "text/html")
Dim logo As New LinkedResource(_EmailLogo)
logo.ContentId = "Dexuslogo1"
Dim logo1 As New LinkedResource(_EmailLogo1)
logo1.ContentId = "Dexuslogo2"
htmlView.LinkedResources.Add(logo)
htmlView.LinkedResources.Add(logo1)
aMessage.AlternateViews.Add(htmlView)
Else
Dim htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), Nothing, "text/html")
Dim logo As New LinkedResource(_EmailLogo)
logo.ContentId = "companylogo"
htmlView.LinkedResources.Add(logo)
aMessage.AlternateViews.Add(htmlView)
End If
End If
For Each anAttach As Attachment In _Attachments
aMessage.Attachments.Add(anAttach)
Next
If _ReplyTo IsNot Nothing Then aMessage.ReplyToList.Add(New MailAddress(_ReplyTo))
client.Host = "smtpi.cbre.com.au"
client.UseDefaultCredentials = True
client.Send(aMessage)
Catch exRecipUnk As SmtpFailedRecipientException
Return False
Catch exSmtp As SmtpException
''exSmtp.StatusCode
Return False
Catch ex As Exception
Return False
End Try
Return True
End Function
If p_Gmap_code = "DE" Then
Dim p_Theme As New Theme("Dexus")
Dim passwordlink As String = ""
Dim DexuslogoImage1 As String = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images\Dexus_Notice_Logo.png")
Dim DexuslogoImage2 As String = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images\DexusTenantNotice.png")
passwordlink = "<a href='" + p_Theme.TenantLoginPage + "?accesstype=email&te=" + a.Encrypt(p_TenantEmail) + "' target='_blank'>here.</a><br/>"
bodys += "<div align='Center'><table border='0' cellpadding='0' cellspacing='0'><tr style='height:50px;'><td width='623px' ></td><td valign='top' width='180'><p align='right'><a href='http://www.dexus.com/'><img border='0' height='50' src=cid:Dexuslogo1 width='174' alt=''/></a></p></td></tr><tr><td colspan='2' width='803' style='height:25px;'></td></tr> <tr><td width='623px'><p align='left' style='font-family:Arial;font-size:14pt;'><strong> Your Dexus Response Password is about to expire</strong></p></td>"
bodys += " <td width='180'><p align='right' style='font-family:Arial;font-size:10pt;'>" + DateTime.Now.ToString("dd/MM/yyyy") + " </p>"
bodys += "</td></tr><tr><td colspan='2' width='803' style='height:30px;'> </td></tr> <tr> <td colspan='2' width='803' style='font-family:Arial;font-size:10pt;'>"
bodys += "<p>" + wishes + " " + p_TenantName.Trim().ToString() + "</p>"
bodys += "</td></tr><tr><td colspan='2' width='803' style='height:25px;'></td> </tr><tr><td colspan='2' width='803' style='font-family:Arial;font-size:10pt;'>"
bodys += "Your Dexus Response password is about to expire in " + p_remaindays.ToString() + " days.<br /><br /> To reset your password and update your details, please click " + passwordlink.ToString() + "<br /><br />Please note that if you do not update your password by " + p_date + ",then your account will be set to inactive and you will not be able to access Dexus Response.</br></br>Please contact Dexus Response if you require assistance in accessing the portal.</p></td>" 'edit
bodys += " </tr><tr><td colspan='2' width='803' style='height:30px;'></td></tr><tr><td colspan='2' width='803'><table align='left' border='0' cellpadding='0' cellspacing='0'><tr><td width='802' style='font-family:Arial;font-size:10pt;'><p><strong>Dexus Response</strong></p></td></tr><tr><td width='802' style='font-family:Arial;font-size:10pt;'><p><a href='mailto:[email protected]'>[email protected]</a> <strong>|</strong> 1300 339 870 <strong>|</strong> <a href='https://response.dexus.com/'>response.dexus.com</a></p></td></tr></table></td></tr><tr><td colspan='2' width='803' style='height:15px;'></td></tr><tr> <td colspan='2' width='803'><p> </p><p><a href='https://response.dexus.com/' border='0' target='_blank'><img border='0' height='133'"
bodys += "src=cid:Dexuslogo2 alt='' width='800' /></a></p></td></tr><tr><td colspan='2' width='803' style='height:10px;'></td></tr><tr><td colspan='2' width='803' style='font-family:Arial;font-size:10pt;'><p><a href='http://www.dexus.com/who-we-are/terms-and-conditions' style=' color:#000000;'>Terms and Conditions</a><strong> | </strong><a href='http://www.dexus.com/who-we-are/privacy-policy' style=' color:#000000;'> Privacy Policy</a></p></td></tr><tr><td colspan='2' width='803' style='height:40px;'></td></tr><tr><td colspan='2' width='803'><p></p></td></tr><tr><td colspan='2' width='803' style='height:10px;'></td></tr><tr></tr><tr><td colspan='2' width='803' style='height:20px;'></td></tr></table></div>"
email = New Common.Email(emailHeading, bodys, p_Theme.EmailFrom, DexuslogoImage1, DexuslogoImage2)
email.ToEmail = p_TenantEmail
email.SendEmail(True, p_Theme.EmailFrom)
How can I make SMTP authenticated in C#
How do you send the message?
The classes in the System.Net.Mail
namespace (which is probably what you should use) has full support for authentication, either specified in Web.config, or using the SmtpClient.Credentials
property.
SMTP server response: 530 5.7.0 Must issue a STARTTLS command first
Blockquote
I then modified the php.ini file to use it (commented out the other lines):
[mail function]
; For Win32 only.
; SMTP = smtp.gmail.com
; smtp_port = 25
; For Win32 only.
; sendmail_from = <e-mail username>@gmail.com
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
Ignore the "For Unix only" comment, as this version of sendmail works for Windows.
You then have to configure the "sendmail.ini" file in the directory where sendmail was installed:
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=<username>
auth_password=<password>
force_sender=<e-mail username>@gmail.com
http://byitcurious.blogspot.com.br/2009/04/solving-must-issue-starttls-command.html
> Blockquote
Run Python script at startup in Ubuntu
Put this in /etc/init
(Use /etc/systemd
in Ubuntu 15.x)
mystartupscript.conf
start on runlevel [2345]
stop on runlevel [!2345]
exec /path/to/script.py
By placing this conf file there you hook into ubuntu's upstart service that runs services on startup.
manual starting/stopping is done with
sudo service mystartupscript start
and
sudo service mystartupscript stop
VB.NET - How to move to next item a For Each Loop?
When I tried Continue For
it Failed, I got a compiler error. While doing this, I discovered 'Resume':
For Each I As Item In Items
If I = x Then
'Move to next item
Resume Next
End If
'Do something
Next
Note: I am using VBA here.
What is Dependency Injection?
Dependency Injection means a way (actually any-way) for one part of code (e.g a class) to have access to dependencies (other parts of code, e.g other classes, it depends upon) in a modular way without them being hardcoded (so they can change or be overriden freely, or even be loaded at another time, as needed)
(and ps , yes it has become an overly-hyped 25$ name for a rather simple, concept), my .25
cents
Two Decimal places using c#
I use
decimal Debitvalue = 1156.547m;
decimal DEBITAMT = Convert.ToDecimal(string.Format("{0:F2}", Debitvalue));
Why is __init__() always called after __new__()?
In most well-known OO languages, an expression like SomeClass(arg1, arg2)
will allocate a new instance, initialise the instance's attributes, and then return it.
In most well-known OO languages, the "initialise the instance's attributes" part can be customised for each class by defining a constructor, which is basically just a block of code that operates on the new instance (using the arguments provided to the constructor expression) to set up whatever initial conditions are desired. In Python, this corresponds to the class' __init__
method.
Python's __new__
is nothing more and nothing less than similar per-class customisation of the "allocate a new instance" part. This of course allows you to do unusual things such as returning an existing instance rather than allocating a new one. So in Python, we shouldn't really think of this part as necessarily involving allocation; all that we require is that __new__
comes up with a suitable instance from somewhere.
But it's still only half of the job, and there's no way for the Python system to know that sometimes you want to run the other half of the job (__init__
) afterwards and sometimes you don't. If you want that behavior, you have to say so explicitly.
Often, you can refactor so you only need __new__
, or so you don't need __new__
, or so that __init__
behaves differently on an already-initialised object. But if you really want to, Python does actually allow you to redefine "the job", so that SomeClass(arg1, arg2)
doesn't necessarily call __new__
followed by __init__
. To do this, you need to create a metaclass, and define its __call__
method.
A metaclass is just the class of a class. And a class' __call__
method controls what happens when you call instances of the class. So a metaclass' __call__
method controls what happens when you call a class; i.e. it allows you to redefine the instance-creation mechanism from start to finish. This is the level at which you can most elegantly implement a completely non-standard instance creation process such as the singleton pattern. In fact, with less than 10 lines of code you can implement a Singleton
metaclass that then doesn't even require you to futz with __new__
at all, and can turn any otherwise-normal class into a singleton by simply adding __metaclass__ = Singleton
!
class Singleton(type):
def __init__(self, *args, **kwargs):
super(Singleton, self).__init__(*args, **kwargs)
self.__instance = None
def __call__(self, *args, **kwargs):
if self.__instance is None:
self.__instance = super(Singleton, self).__call__(*args, **kwargs)
return self.__instance
However this is probably deeper magic than is really warranted for this situation!
How to set ANDROID_HOME path in ubuntu?
In the console just type these :
export ANDROID_HOME=$HOME/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools
If you want to make it permanent just add those lines in the ~/.bashrc file
`ui-router` $stateParams vs. $state.params
There are many differences between these two. But while working practically I have found that using $state.params
better. When you use more and more parameters this might be confusing to maintain in $stateParams
. where if we use multiple params which are not URL param $state
is very useful
.state('shopping-request', {
url: '/shopping-request/{cartId}',
data: {requireLogin: true},
params : {role: null},
views: {
'': {templateUrl: 'views/templates/main.tpl.html', controller: "ShoppingRequestCtrl"},
'body@shopping-request': {templateUrl: 'views/shops/shopping-request.html'},
'footer@shopping-request': {templateUrl: 'views/templates/footer.tpl.html'},
'header@shopping-request': {templateUrl: 'views/templates/header.tpl.html'}
}
})
How are ssl certificates verified?
The client has a pre-seeded store of SSL certificate authorities' public keys. There must be a chain of trust from the certificate for the server up through intermediate authorities up to one of the so-called "root" certificates in order for the server to be trusted.
You can examine and/or alter the list of trusted authorities. Often you do this to add a certificate for a local authority that you know you trust - like the company you work for or the school you attend or what not.
The pre-seeded list can vary depending on which client you use. The big SSL certificate vendors insure that their root certs are in all the major browsers ($$$).
Monkey-in-the-middle attacks are "impossible" unless the attacker has the private key of a trusted root certificate. Since the corresponding certificates are widely deployed, the exposure of such a private key would have serious implications for the security of eCommerce generally. Because of that, those private keys are very, very closely guarded.
numpy get index where value is true
A simple and clean way: use np.argwhere
to group the indices by element, rather than dimension as in np.nonzero(a)
(i.e., np.argwhere
returns a row for each non-zero element).
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.argwhere(a>4)
array([[5],
[6],
[7],
[8],
[9]])
np.argwhere(a)
is the same as np.transpose(np.nonzero(a))
.
Note: You cannot use a(np.argwhere(a>4))
to get the corresponding values in a
. The recommended way is to use a[(a>4).astype(bool)]
or a[(a>4) != 0]
rather than a[np.nonzero(a>4)]
as they handle 0-d arrays correctly. See the documentation for more details. As can be seen in the following example, a[(a>4).astype(bool)]
and a[(a>4) != 0]
can be simplified to a[a>4]
.
Another example:
>>> a = np.array([5,-15,-8,-5,10])
>>> a
array([ 5, -15, -8, -5, 10])
>>> a > 4
array([ True, False, False, False, True])
>>> a[a > 4]
array([ 5, 10])
>>> a = np.add.outer(a,a)
>>> a
array([[ 10, -10, -3, 0, 15],
[-10, -30, -23, -20, -5],
[ -3, -23, -16, -13, 2],
[ 0, -20, -13, -10, 5],
[ 15, -5, 2, 5, 20]])
>>> a = np.argwhere(a>4)
>>> a
array([[0, 0],
[0, 4],
[3, 4],
[4, 0],
[4, 3],
[4, 4]])
>>> [print(i,j) for i,j in a]
0 0
0 4
3 4
4 0
4 3
4 4
How can I "reset" an Arduino board?
- First of all, connect your Arduino device.
- Then go to Device Manager and uninstall the driver.
- Now remove your Arduino device.
- Again connect you Arduino device to your system.
- Now install your driver (which you have uninstalled earlier).
It will free your port for sure.
Convert list of dictionaries to a pandas DataFrame
You can also use pd.DataFrame.from_dict(d)
as :
In [8]: d = [{'points': 50, 'time': '5:00', 'year': 2010},
...: {'points': 25, 'time': '6:00', 'month': "february"},
...: {'points':90, 'time': '9:00', 'month': 'january'},
...: {'points_h1':20, 'month': 'june'}]
In [12]: pd.DataFrame.from_dict(d)
Out[12]:
month points points_h1 time year
0 NaN 50.0 NaN 5:00 2010.0
1 february 25.0 NaN 6:00 NaN
2 january 90.0 NaN 9:00 NaN
3 june NaN 20.0 NaN NaN
How can I protect my .NET assemblies from decompilation?
Do you API?
Instead of trying to protect your one ddl file in one of your products on all of your customers devices, why not create an API service for your precious product features? Let the actual product that is saved on a device consume that API to deliver the product as you want it.
I Think this way you are 100% sure that your code is not decompiled and you set your own limits in your API so that developers / hackers don't consume your API in a way you don't want it.
Sure is some more work, but in the end, you are in control.
How to detect the character encoding of a text file?
If you want to pursue a "simple" solution, you might find this class I put together useful:
http://www.architectshack.com/TextFileEncodingDetector.ashx
It does the BOM detection automatically first, and then tries to differentiate between Unicode encodings without BOM, vs some other default encoding (generally Windows-1252, incorrectly labelled as Encoding.ASCII in .Net).
As noted above, a "heavier" solution involving NCharDet or MLang may be more appropriate, and as I note on the overview page of this class, the best is to provide some form of interactivity with the user if at all possible, because there simply is no 100% detection rate possible!
Snippet in case the site is offline:
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace KlerksSoft
{
public static class TextFileEncodingDetector
{
/*
* Simple class to handle text file encoding woes (in a primarily English-speaking tech
* world).
*
* - This code is fully managed, no shady calls to MLang (the unmanaged codepage
* detection library originally developed for Internet Explorer).
*
* - This class does NOT try to detect arbitrary codepages/charsets, it really only
* aims to differentiate between some of the most common variants of Unicode
* encoding, and a "default" (western / ascii-based) encoding alternative provided
* by the caller.
*
* - As there is no "Reliable" way to distinguish between UTF-8 (without BOM) and
* Windows-1252 (in .Net, also incorrectly called "ASCII") encodings, we use a
* heuristic - so the more of the file we can sample the better the guess. If you
* are going to read the whole file into memory at some point, then best to pass
* in the whole byte byte array directly. Otherwise, decide how to trade off
* reliability against performance / memory usage.
*
* - The UTF-8 detection heuristic only works for western text, as it relies on
* the presence of UTF-8 encoded accented and other characters found in the upper
* ranges of the Latin-1 and (particularly) Windows-1252 codepages.
*
* - For more general detection routines, see existing projects / resources:
* - MLang - Microsoft library originally for IE6, available in Windows XP and later APIs now (I think?)
* - MLang .Net bindings: http://www.codeproject.com/KB/recipes/DetectEncoding.aspx
* - CharDet - Mozilla browser's detection routines
* - Ported to Java then .Net: http://www.conceptdevelopment.net/Localization/NCharDet/
* - Ported straight to .Net: http://code.google.com/p/chardetsharp/source/browse
*
* Copyright Tao Klerks, 2010-2012, [email protected]
* Licensed under the modified BSD license:
*
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
- The name of the author may not be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*
* CHANGELOG:
* - 2012-02-03:
* - Simpler methods, removing the silly "DefaultEncoding" parameter (with "??" operator, saves no typing)
* - More complete methods
* - Optionally return indication of whether BOM was found in "Detect" methods
* - Provide straight-to-string method for byte arrays (GetStringFromByteArray)
*/
const long _defaultHeuristicSampleSize = 0x10000; //completely arbitrary - inappropriate for high numbers of files / high speed requirements
public static Encoding DetectTextFileEncoding(string InputFilename)
{
using (FileStream textfileStream = File.OpenRead(InputFilename))
{
return DetectTextFileEncoding(textfileStream, _defaultHeuristicSampleSize);
}
}
public static Encoding DetectTextFileEncoding(FileStream InputFileStream, long HeuristicSampleSize)
{
bool uselessBool = false;
return DetectTextFileEncoding(InputFileStream, _defaultHeuristicSampleSize, out uselessBool);
}
public static Encoding DetectTextFileEncoding(FileStream InputFileStream, long HeuristicSampleSize, out bool HasBOM)
{
if (InputFileStream == null)
throw new ArgumentNullException("Must provide a valid Filestream!", "InputFileStream");
if (!InputFileStream.CanRead)
throw new ArgumentException("Provided file stream is not readable!", "InputFileStream");
if (!InputFileStream.CanSeek)
throw new ArgumentException("Provided file stream cannot seek!", "InputFileStream");
Encoding encodingFound = null;
long originalPos = InputFileStream.Position;
InputFileStream.Position = 0;
//First read only what we need for BOM detection
byte[] bomBytes = new byte[InputFileStream.Length > 4 ? 4 : InputFileStream.Length];
InputFileStream.Read(bomBytes, 0, bomBytes.Length);
encodingFound = DetectBOMBytes(bomBytes);
if (encodingFound != null)
{
InputFileStream.Position = originalPos;
HasBOM = true;
return encodingFound;
}
//BOM Detection failed, going for heuristics now.
// create sample byte array and populate it
byte[] sampleBytes = new byte[HeuristicSampleSize > InputFileStream.Length ? InputFileStream.Length : HeuristicSampleSize];
Array.Copy(bomBytes, sampleBytes, bomBytes.Length);
if (InputFileStream.Length > bomBytes.Length)
InputFileStream.Read(sampleBytes, bomBytes.Length, sampleBytes.Length - bomBytes.Length);
InputFileStream.Position = originalPos;
//test byte array content
encodingFound = DetectUnicodeInByteSampleByHeuristics(sampleBytes);
HasBOM = false;
return encodingFound;
}
public static Encoding DetectTextByteArrayEncoding(byte[] TextData)
{
bool uselessBool = false;
return DetectTextByteArrayEncoding(TextData, out uselessBool);
}
public static Encoding DetectTextByteArrayEncoding(byte[] TextData, out bool HasBOM)
{
if (TextData == null)
throw new ArgumentNullException("Must provide a valid text data byte array!", "TextData");
Encoding encodingFound = null;
encodingFound = DetectBOMBytes(TextData);
if (encodingFound != null)
{
HasBOM = true;
return encodingFound;
}
else
{
//test byte array content
encodingFound = DetectUnicodeInByteSampleByHeuristics(TextData);
HasBOM = false;
return encodingFound;
}
}
public static string GetStringFromByteArray(byte[] TextData, Encoding DefaultEncoding)
{
return GetStringFromByteArray(TextData, DefaultEncoding, _defaultHeuristicSampleSize);
}
public static string GetStringFromByteArray(byte[] TextData, Encoding DefaultEncoding, long MaxHeuristicSampleSize)
{
if (TextData == null)
throw new ArgumentNullException("Must provide a valid text data byte array!", "TextData");
Encoding encodingFound = null;
encodingFound = DetectBOMBytes(TextData);
if (encodingFound != null)
{
//For some reason, the default encodings don't detect/swallow their own preambles!!
return encodingFound.GetString(TextData, encodingFound.GetPreamble().Length, TextData.Length - encodingFound.GetPreamble().Length);
}
else
{
byte[] heuristicSample = null;
if (TextData.Length > MaxHeuristicSampleSize)
{
heuristicSample = new byte[MaxHeuristicSampleSize];
Array.Copy(TextData, heuristicSample, MaxHeuristicSampleSize);
}
else
{
heuristicSample = TextData;
}
encodingFound = DetectUnicodeInByteSampleByHeuristics(TextData) ?? DefaultEncoding;
return encodingFound.GetString(TextData);
}
}
public static Encoding DetectBOMBytes(byte[] BOMBytes)
{
if (BOMBytes == null)
throw new ArgumentNullException("Must provide a valid BOM byte array!", "BOMBytes");
if (BOMBytes.Length < 2)
return null;
if (BOMBytes[0] == 0xff
&& BOMBytes[1] == 0xfe
&& (BOMBytes.Length < 4
|| BOMBytes[2] != 0
|| BOMBytes[3] != 0
)
)
return Encoding.Unicode;
if (BOMBytes[0] == 0xfe
&& BOMBytes[1] == 0xff
)
return Encoding.BigEndianUnicode;
if (BOMBytes.Length < 3)
return null;
if (BOMBytes[0] == 0xef && BOMBytes[1] == 0xbb && BOMBytes[2] == 0xbf)
return Encoding.UTF8;
if (BOMBytes[0] == 0x2b && BOMBytes[1] == 0x2f && BOMBytes[2] == 0x76)
return Encoding.UTF7;
if (BOMBytes.Length < 4)
return null;
if (BOMBytes[0] == 0xff && BOMBytes[1] == 0xfe && BOMBytes[2] == 0 && BOMBytes[3] == 0)
return Encoding.UTF32;
if (BOMBytes[0] == 0 && BOMBytes[1] == 0 && BOMBytes[2] == 0xfe && BOMBytes[3] == 0xff)
return Encoding.GetEncoding(12001);
return null;
}
public static Encoding DetectUnicodeInByteSampleByHeuristics(byte[] SampleBytes)
{
long oddBinaryNullsInSample = 0;
long evenBinaryNullsInSample = 0;
long suspiciousUTF8SequenceCount = 0;
long suspiciousUTF8BytesTotal = 0;
long likelyUSASCIIBytesInSample = 0;
//Cycle through, keeping count of binary null positions, possible UTF-8
// sequences from upper ranges of Windows-1252, and probable US-ASCII
// character counts.
long currentPos = 0;
int skipUTF8Bytes = 0;
while (currentPos < SampleBytes.Length)
{
//binary null distribution
if (SampleBytes[currentPos] == 0)
{
if (currentPos % 2 == 0)
evenBinaryNullsInSample++;
else
oddBinaryNullsInSample++;
}
//likely US-ASCII characters
if (IsCommonUSASCIIByte(SampleBytes[currentPos]))
likelyUSASCIIBytesInSample++;
//suspicious sequences (look like UTF-8)
if (skipUTF8Bytes == 0)
{
int lengthFound = DetectSuspiciousUTF8SequenceLength(SampleBytes, currentPos);
if (lengthFound > 0)
{
suspiciousUTF8SequenceCount++;
suspiciousUTF8BytesTotal += lengthFound;
skipUTF8Bytes = lengthFound - 1;
}
}
else
{
skipUTF8Bytes--;
}
currentPos++;
}
//1: UTF-16 LE - in english / european environments, this is usually characterized by a
// high proportion of odd binary nulls (starting at 0), with (as this is text) a low
// proportion of even binary nulls.
// The thresholds here used (less than 20% nulls where you expect non-nulls, and more than
// 60% nulls where you do expect nulls) are completely arbitrary.
if (((evenBinaryNullsInSample * 2.0) / SampleBytes.Length) < 0.2
&& ((oddBinaryNullsInSample * 2.0) / SampleBytes.Length) > 0.6
)
return Encoding.Unicode;
//2: UTF-16 BE - in english / european environments, this is usually characterized by a
// high proportion of even binary nulls (starting at 0), with (as this is text) a low
// proportion of odd binary nulls.
// The thresholds here used (less than 20% nulls where you expect non-nulls, and more than
// 60% nulls where you do expect nulls) are completely arbitrary.
if (((oddBinaryNullsInSample * 2.0) / SampleBytes.Length) < 0.2
&& ((evenBinaryNullsInSample * 2.0) / SampleBytes.Length) > 0.6
)
return Encoding.BigEndianUnicode;
//3: UTF-8 - Martin Dürst outlines a method for detecting whether something CAN be UTF-8 content
// using regexp, in his w3c.org unicode FAQ entry:
// http://www.w3.org/International/questions/qa-forms-utf-8
// adapted here for C#.
string potentiallyMangledString = Encoding.ASCII.GetString(SampleBytes);
Regex UTF8Validator = new Regex(@"\A("
+ @"[\x09\x0A\x0D\x20-\x7E]"
+ @"|[\xC2-\xDF][\x80-\xBF]"
+ @"|\xE0[\xA0-\xBF][\x80-\xBF]"
+ @"|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}"
+ @"|\xED[\x80-\x9F][\x80-\xBF]"
+ @"|\xF0[\x90-\xBF][\x80-\xBF]{2}"
+ @"|[\xF1-\xF3][\x80-\xBF]{3}"
+ @"|\xF4[\x80-\x8F][\x80-\xBF]{2}"
+ @")*\z");
if (UTF8Validator.IsMatch(potentiallyMangledString))
{
//Unfortunately, just the fact that it CAN be UTF-8 doesn't tell you much about probabilities.
//If all the characters are in the 0-127 range, no harm done, most western charsets are same as UTF-8 in these ranges.
//If some of the characters were in the upper range (western accented characters), however, they would likely be mangled to 2-byte by the UTF-8 encoding process.
// So, we need to play stats.
// The "Random" likelihood of any pair of randomly generated characters being one
// of these "suspicious" character sequences is:
// 128 / (256 * 256) = 0.2%.
//
// In western text data, that is SIGNIFICANTLY reduced - most text data stays in the <127
// character range, so we assume that more than 1 in 500,000 of these character
// sequences indicates UTF-8. The number 500,000 is completely arbitrary - so sue me.
//
// We can only assume these character sequences will be rare if we ALSO assume that this
// IS in fact western text - in which case the bulk of the UTF-8 encoded data (that is
// not already suspicious sequences) should be plain US-ASCII bytes. This, I
// arbitrarily decided, should be 80% (a random distribution, eg binary data, would yield
// approx 40%, so the chances of hitting this threshold by accident in random data are
// VERY low).
if ((suspiciousUTF8SequenceCount * 500000.0 / SampleBytes.Length >= 1) //suspicious sequences
&& (
//all suspicious, so cannot evaluate proportion of US-Ascii
SampleBytes.Length - suspiciousUTF8BytesTotal == 0
||
likelyUSASCIIBytesInSample * 1.0 / (SampleBytes.Length - suspiciousUTF8BytesTotal) >= 0.8
)
)
return Encoding.UTF8;
}
return null;
}
private static bool IsCommonUSASCIIByte(byte testByte)
{
if (testByte == 0x0A //lf
|| testByte == 0x0D //cr
|| testByte == 0x09 //tab
|| (testByte >= 0x20 && testByte <= 0x2F) //common punctuation
|| (testByte >= 0x30 && testByte <= 0x39) //digits
|| (testByte >= 0x3A && testByte <= 0x40) //common punctuation
|| (testByte >= 0x41 && testByte <= 0x5A) //capital letters
|| (testByte >= 0x5B && testByte <= 0x60) //common punctuation
|| (testByte >= 0x61 && testByte <= 0x7A) //lowercase letters
|| (testByte >= 0x7B && testByte <= 0x7E) //common punctuation
)
return true;
else
return false;
}
private static int DetectSuspiciousUTF8SequenceLength(byte[] SampleBytes, long currentPos)
{
int lengthFound = 0;
if (SampleBytes.Length >= currentPos + 1
&& SampleBytes[currentPos] == 0xC2
)
{
if (SampleBytes[currentPos + 1] == 0x81
|| SampleBytes[currentPos + 1] == 0x8D
|| SampleBytes[currentPos + 1] == 0x8F
)
lengthFound = 2;
else if (SampleBytes[currentPos + 1] == 0x90
|| SampleBytes[currentPos + 1] == 0x9D
)
lengthFound = 2;
else if (SampleBytes[currentPos + 1] >= 0xA0
&& SampleBytes[currentPos + 1] <= 0xBF
)
lengthFound = 2;
}
else if (SampleBytes.Length >= currentPos + 1
&& SampleBytes[currentPos] == 0xC3
)
{
if (SampleBytes[currentPos + 1] >= 0x80
&& SampleBytes[currentPos + 1] <= 0xBF
)
lengthFound = 2;
}
else if (SampleBytes.Length >= currentPos + 1
&& SampleBytes[currentPos] == 0xC5
)
{
if (SampleBytes[currentPos + 1] == 0x92
|| SampleBytes[currentPos + 1] == 0x93
)
lengthFound = 2;
else if (SampleBytes[currentPos + 1] == 0xA0
|| SampleBytes[currentPos + 1] == 0xA1
)
lengthFound = 2;
else if (SampleBytes[currentPos + 1] == 0xB8
|| SampleBytes[currentPos + 1] == 0xBD
|| SampleBytes[currentPos + 1] == 0xBE
)
lengthFound = 2;
}
else if (SampleBytes.Length >= currentPos + 1
&& SampleBytes[currentPos] == 0xC6
)
{
if (SampleBytes[currentPos + 1] == 0x92)
lengthFound = 2;
}
else if (SampleBytes.Length >= currentPos + 1
&& SampleBytes[currentPos] == 0xCB
)
{
if (SampleBytes[currentPos + 1] == 0x86
|| SampleBytes[currentPos + 1] == 0x9C
)
lengthFound = 2;
}
else if (SampleBytes.Length >= currentPos + 2
&& SampleBytes[currentPos] == 0xE2
)
{
if (SampleBytes[currentPos + 1] == 0x80)
{
if (SampleBytes[currentPos + 2] == 0x93
|| SampleBytes[currentPos + 2] == 0x94
)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0x98
|| SampleBytes[currentPos + 2] == 0x99
|| SampleBytes[currentPos + 2] == 0x9A
)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0x9C
|| SampleBytes[currentPos + 2] == 0x9D
|| SampleBytes[currentPos + 2] == 0x9E
)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0xA0
|| SampleBytes[currentPos + 2] == 0xA1
|| SampleBytes[currentPos + 2] == 0xA2
)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0xA6)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0xB0)
lengthFound = 3;
if (SampleBytes[currentPos + 2] == 0xB9
|| SampleBytes[currentPos + 2] == 0xBA
)
lengthFound = 3;
}
else if (SampleBytes[currentPos + 1] == 0x82
&& SampleBytes[currentPos + 2] == 0xAC
)
lengthFound = 3;
else if (SampleBytes[currentPos + 1] == 0x84
&& SampleBytes[currentPos + 2] == 0xA2
)
lengthFound = 3;
}
return lengthFound;
}
}
}
Ant error when trying to build file, can't find tools.jar?
Just set your java_home property with java home (eg:C:\Program Files\Java\jdk1.7.0_25) directory.
Close command prompt and reopen it.
Then error relating to tools.jar will be solved.
For the second one("build.xml not found ") you should have to ensure your command line also at the directory where your build.xml file resides.
How to set an "Accept:" header on Spring RestTemplate request?
You could set an interceptor "ClientHttpRequestInterceptor" in your RestTemplate to avoid setting the header every time you send a request.
public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {
private final String headerName;
private final String headerValue;
public HeaderRequestInterceptor(String headerName, String headerValue) {
this.headerName = headerName;
this.headerValue = headerValue;
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
request.getHeaders().set(headerName, headerValue);
return execution.execute(request, body);
}
}
Then
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add(new HeaderRequestInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(interceptors);
Disable/Enable button in Excel/VBA
I'm using excel 2010 and below VBA code worked fine for a Form Button.
It removes the assigned macro from the button and assign in next command.
To disable:
ActiveSheet.Shapes("Button Name").OnAction = Empty
ActiveSheet.Shapes("Button Name").DrawingObject.Font.ColorIndex = 16
To enable:
ActiveSheet.Shapes("Button Name").OnAction = ActiveWorkbook.Name & "!Macro function Name with _Click"
ActiveSheet.Shapes("Button Name").DrawingObject.Font.ColorIndex = 1
Pls note "ActiveWorkbook.Name" stays as it is. Do not insert workbook name instead of "Name".
How to get random value out of an array?
Get random values from an array.
function random($array)
{
/// Determine array is associative or not
$keys = array_keys($array);
$givenArrIsAssoc = array_keys($keys) !== $keys;
/// if array is not associative then return random element
if(!$givenArrIsAssoc){
return $array[array_rand($array)];
}
/// If array is associative then
$keys = array_rand($array, $number);
$results = [];
foreach ((array) $keys as $key) {
$results[] = $array[$key];
}
return $results;
}
JavaFX Panel inside Panel auto resizing
It is quite simple because you are using the FXMLBuilder.
Just follow these simple steps:
- Open FXML file into FXMLBuilder.
- Select the stack pane.
- Open the Layout tab [left side tab of FXMLBuilder].
- Set the sides value by which you want to compute the pane size during stage resize like TOP, LEFT, RIGHT, BOTTOM.
Importing csv file into R - numeric values read as characters
If you're dealing with large datasets (i.e. datasets with a high number of columns), the solution noted above can be manually cumbersome, and requires you to know which columns are numeric a priori.
Try this instead.
char_data <- read.csv(input_filename, stringsAsFactors = F)
num_data <- data.frame(data.matrix(char_data))
numeric_columns <- sapply(num_data,function(x){mean(as.numeric(is.na(x)))<0.5})
final_data <- data.frame(num_data[,numeric_columns], char_data[,!numeric_columns])
The code does the following:
- Imports your data as character columns.
- Creates an instance of your data as numeric columns.
- Identifies which columns from your data are numeric (assuming columns with less than 50% NAs upon converting your data to numeric are indeed numeric).
- Merging the numeric and character columns into a final dataset.
This essentially automates the import of your .csv file by preserving the data types of the original columns (as character and numeric).
Best way to do nested case statement logic in SQL Server
Wrap all those cases into one.
SELECT
col1,
col2,
col3,
CASE
WHEN condition1 THEN calculation1
WHEN condition2 THEN calculation2
WHEN condition3 THEN calculation3
WHEN condition4 THEN calculation4
WHEN condition5 THEN calculation5
ELSE NULL
END AS 'calculatedcol1',
col4,
col5 -- etc
FROM table
Plot data in descending order as appears in data frame
You want reorder()
. Here is an example with dummy data
set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))
require("ggplot2")
p1 <- ggplot(df, aes(x = Category, y = Count)) +
geom_bar(stat = "identity")
p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
geom_bar(stat = "identity")
require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))
Giving:
Use reorder(Category, Count)
to have Category
ordered from low-high.
How to securely save username/password (local)?
I wanted to encrypt and decrypt the string as a readable string.
Here is a very simple quick example in C# Visual Studio 2019 WinForms based on the answer from @Pradip
.
Right click project > properties > settings > Create a username
and password
setting.
Now you can leverage those settings you just created. Here I save the username
and password
but only encrypt the password
in it's respectable value field in the user.config
file.
Example of the encrypted string in the user.config
file.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<userSettings>
<secure_password_store.Properties.Settings>
<setting name="username" serializeAs="String">
<value>admin</value>
</setting>
<setting name="password" serializeAs="String">
<value>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAQpgaPYIUq064U3o6xXkQOQAAAAACAAAAAAAQZgAAAAEAACAAAABlQQ8OcONYBr9qUhH7NeKF8bZB6uCJa5uKhk97NdH93AAAAAAOgAAAAAIAACAAAAC7yQicDYV5DiNp0fHXVEDZ7IhOXOrsRUbcY0ziYYTlKSAAAACVDQ+ICHWooDDaUywJeUOV9sRg5c8q6/vizdq8WtPVbkAAAADciZskoSw3g6N9EpX/8FOv+FeExZFxsm03i8vYdDHUVmJvX33K03rqiYF2qzpYCaldQnRxFH9wH2ZEHeSRPeiG</value>
</setting>
</secure_password_store.Properties.Settings>
</userSettings>
</configuration>
Full Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace secure_password_store
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Exit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Login_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
Properties.Settings.Default.username = textBox1.Text;
Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
Properties.Settings.Default.Save();
}
else if (checkBox1.Checked == false)
{
Properties.Settings.Default.username = "";
Properties.Settings.Default.password = "";
Properties.Settings.Default.Save();
}
MessageBox.Show("{\"data\": \"some data\"}","Login Message Alert",MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void DecryptString_Click(object sender, EventArgs e)
{
SecureString password = DecryptString(Properties.Settings.Default.password);
string readable = ToInsecureString(password);
textBox4.AppendText(readable + Environment.NewLine);
}
private void Form_Load(object sender, EventArgs e)
{
//textBox1.Text = "UserName";
//textBox2.Text = "Password";
if (Properties.Settings.Default.username != string.Empty)
{
textBox1.Text = Properties.Settings.Default.username;
checkBox1.Checked = true;
SecureString password = DecryptString(Properties.Settings.Default.password);
string readable = ToInsecureString(password);
textBox2.Text = readable;
}
groupBox1.Select();
}
static byte[] entropy = Encoding.Unicode.GetBytes("SaLtY bOy 6970 ePiC");
public static string EncryptString(SecureString input)
{
byte[] encryptedData = ProtectedData.Protect(Encoding.Unicode.GetBytes(ToInsecureString(input)),entropy,DataProtectionScope.CurrentUser);
return Convert.ToBase64String(encryptedData);
}
public static SecureString DecryptString(string encryptedData)
{
try
{
byte[] decryptedData = ProtectedData.Unprotect(Convert.FromBase64String(encryptedData),entropy,DataProtectionScope.CurrentUser);
return ToSecureString(Encoding.Unicode.GetString(decryptedData));
}
catch
{
return new SecureString();
}
}
public static SecureString ToSecureString(string input)
{
SecureString secure = new SecureString();
foreach (char c in input)
{
secure.AppendChar(c);
}
secure.MakeReadOnly();
return secure;
}
public static string ToInsecureString(SecureString input)
{
string returnValue = string.Empty;
IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
try
{
returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
}
finally
{
System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
}
return returnValue;
}
private void EncryptString_Click(object sender, EventArgs e)
{
Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
textBox3.AppendText(Properties.Settings.Default.password.ToString() + Environment.NewLine);
}
}
}
How do I use Safe Area Layout programmatically?
I'm using this instead of add leading and trailing margin constraints to the layoutMarginsGuide:
UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
yourView.translatesAutoresizingMaskIntoConstraints = NO;
[NSLayoutConstraint activateConstraints:@[
[safe.trailingAnchor constraintEqualToAnchor:yourView.trailingAnchor],
[yourView.leadingAnchor constraintEqualToAnchor:safe.leadingAnchor],
[yourView.topAnchor constraintEqualToAnchor:safe.topAnchor],
[safe.bottomAnchor constraintEqualToAnchor:yourView.bottomAnchor]
]];
Please also check the option for lower version of ios 11 from Krunal's answer.
Maven is not working in Java 8 when Javadoc tags are incomplete
Since it depends on the version of your JRE which is used to run the maven command you propably dont want to disable DocLint
per default in your pom.xml
Hence, from command line you can use the switch -Dadditionalparam=-Xdoclint:none
.
Example: mvn clean install -Dadditionalparam=-Xdoclint:none
"cannot be used as a function error"
You are using growthRate both as a variable name and a function name. The variable hides the function, and then you are trying to use the variable as if it was the function - that is not valid.
Rename the local variable.
Serialize an object to string
Serialize and Deserialize (XML/JSON):
public static T XmlDeserialize<T>(this string toDeserialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using(StringReader textReader = new StringReader(toDeserialize))
{
return (T)xmlSerializer.Deserialize(textReader);
}
}
public static string XmlSerialize<T>(this T toSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using(StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
public static T JsonDeserialize<T>(this string toDeserialize)
{
return JsonConvert.DeserializeObject<T>(toDeserialize);
}
public static string JsonSerialize<T>(this T toSerialize)
{
return JsonConvert.SerializeObject(toSerialize);
}
MetadataException when using Entity Framework Entity Connection
I had the same error message, and the problem was also the metadata part of the connection string, but I had to dig a little deeper to solve it and wanted to share this little nugget:
The metadata string is made up of three sections that each look like this:
res://
(assembly)/
(model name).(ext)
Where ext is "csdl", "ssdl", and "msl".
For most people, assembly can probably be "*", which seems to indicate that all loaded assemblies will be searched (I haven't done a huge amount of testing of this).
This part wasn't an issue for me, so I can't comment on whether you need the assembly name or file name (i.e., with or without ".dll"), though I have seen both suggested.
The model name part should be the name and namespace of your .edmx file, relative to your assembly.
So if you have a My.DataAccess assembly and you create DataModels.edmx in a Models folder, its full name is My.DataAccess.Models.DataModels. In this case, you would have "Models.DataModels.(ext)" in your metadata.
If you ever move or rename your .edmx file, you will need to update your metadata string manually (in my experience), and remembering to change the relative namespace will save a few headaches.
Avoid printStackTrace(); use a logger call instead
The main reason is that Proguard would remove Log calls from production. Because by logging or printing StackTrace, it is possible to see them (information inside stack trace or Log) inside the Android phone by for example Logcat Reader application. So that it is a bad practice for security. Also, we do not access them during production, it would better to get removed from production. As ProGuard remove all Log calls not stackTrace, so it is better to use Log in catch blocks and let them removed from Production by Proguard.
ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite
All these answers are fine if you execute one line at a time. However, the original question was to input a sql script that would be executed by a single db execute and all the solutions ( like checking to see if the column is there ahead of time ) would require the executing program either have knowledge of what tables and columns are being altered/added or do pre-processing and parsing of the input script to determine this information. Typically you are not going to run this in realtime or often. So the idea of catching an exception is acceptable and then moving on. Therein lies the problem...how to move on. Luckily the error message gives us all the information we need to do this. The idea is to execute the sql if it exceptions on an alter table call we can find the alter table line in the sql and return the remaining lines and execute until it either succeeds or no more matching alter table lines can be found. Heres some example code where we have sql scripts in an array. We iterate the array executing each script. We call it twice to get the alter table command to fail but the program succeeds because we remove the alter table command from the sql and re-execute the updated code.
#!/bin/sh
# the next line restarts using wish \
exec /opt/usr8.6.3/bin/tclsh8.6 "$0" ${1+"$@"}
foreach pkg {sqlite3 } {
if { [ catch {package require {*}$pkg } err ] != 0 } {
puts stderr "Unable to find package $pkg\n$err\n ... adjust your auto_path!";
}
}
array set sqlArray {
1 {
CREATE TABLE IF NOT EXISTS Notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name text,
note text,
createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
);
CREATE TABLE IF NOT EXISTS Version (
id INTEGER PRIMARY KEY AUTOINCREMENT,
version text,
createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
);
INSERT INTO Version(version) values('1.0');
}
2 {
CREATE TABLE IF NOT EXISTS Tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name text,
tag text,
createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
);
ALTER TABLE Notes ADD COLUMN dump text;
INSERT INTO Version(version) values('2.0');
}
3 {
ALTER TABLE Version ADD COLUMN sql text;
INSERT INTO Version(version) values('3.0');
}
}
# create db command , use in memory database for demonstration purposes
sqlite3 db :memory:
proc createSchema { sqlArray } {
upvar $sqlArray sql
# execute each sql script in order
foreach version [lsort -integer [array names sql ] ] {
set cmd $sql($version)
set ok 0
while { !$ok && [string length $cmd ] } {
try {
db eval $cmd
set ok 1 ; # it succeeded if we get here
} on error { err backtrace } {
if { [regexp {duplicate column name: ([a-zA-Z0-9])} [string trim $err ] match columnname ] } {
puts "Error: $err ... trying again"
set cmd [removeAlterTable $cmd $columnname ]
} else {
throw DBERROR "$err\n$backtrace"
}
}
}
}
}
# return sqltext with alter table command with column name removed
# if no matching alter table line found or result is no lines then
# returns ""
proc removeAlterTable { sqltext columnname } {
set mode skip
set result [list]
foreach line [split $sqltext \n ] {
if { [string first "alter table" [string tolower [string trim $line] ] ] >= 0 } {
if { [string first $columnname $line ] } {
set mode add
continue;
}
}
if { $mode eq "add" } {
lappend result $line
}
}
if { $mode eq "skip" } {
puts stderr "Unable to find matching alter table line"
return ""
} elseif { [llength $result ] } {
return [ join $result \n ]
} else {
return ""
}
}
proc printSchema { } {
db eval { select * from sqlite_master } x {
puts "Table: $x(tbl_name)"
puts "$x(sql)"
puts "-------------"
}
}
createSchema sqlArray
printSchema
# run again to see if we get alter table errors
createSchema sqlArray
printSchema
expected output
Table: Notes
CREATE TABLE Notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name text,
note text,
createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
, dump text)
-------------
Table: sqlite_sequence
CREATE TABLE sqlite_sequence(name,seq)
-------------
Table: Version
CREATE TABLE Version (
id INTEGER PRIMARY KEY AUTOINCREMENT,
version text,
createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
, sql text)
-------------
Table: Tags
CREATE TABLE Tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name text,
tag text,
createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
)
-------------
Error: duplicate column name: dump ... trying again
Error: duplicate column name: sql ... trying again
Table: Notes
CREATE TABLE Notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name text,
note text,
createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
, dump text)
-------------
Table: sqlite_sequence
CREATE TABLE sqlite_sequence(name,seq)
-------------
Table: Version
CREATE TABLE Version (
id INTEGER PRIMARY KEY AUTOINCREMENT,
version text,
createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
, sql text)
-------------
Table: Tags
CREATE TABLE Tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name text,
tag text,
createdDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) ) ,
updatedDate integer(4) DEFAULT ( cast( strftime('%s', 'now') as int ) )
)
-------------
Android Studio error: "Environment variable does not point to a valid JVM installation"
The answer to this question can be found here
goto the AndroidStudio installation folder.
goto bin folder and open studio.bat in text editor
add set JAVA_HOME=C:\Program Files\Java2\jdk1.8.0//your java path after the ECHO line.
goto Start -> All Programmes -> Android Studio ->
right click on Android Studio and click on properties.
You will see the Target something like <installation path>android-studio\bin\studio64.exe
change it to <installation path>android-studio\bin\studio.bat
or..... even this might work
Java_Home path set to its parent folder to C:\Program Files\Java\jdk1.8.0_25
How can I convert an HTML element to a canvas element?
No such thing, sorry.
Though the spec states:
A future version of the 2D context API may provide a way to render fragments of documents, rendered using CSS, straight to the canvas.
Which may be as close as you'll get.
A lot of people want a ctx.drawArbitraryHTML/Element
kind of deal but there's nothing built in like that.
The only exception is Mozilla's exclusive drawWindow
, which draws a snapshot of the contents of a DOM window into the canvas. This feature is only available for code running with Chrome ("local only") privileges. It is not allowed in normal HTML pages. So you can use it for writing FireFox extensions like this one does but that's it.
HTML5 Video tag not working in Safari , iPhone and iPad
I know this is an old post, but the issue still seems to surface under different server environments. None of the above were the solution for me. In my case it came down to web optimization and making use gzip, or rather needing to disable it for videos.
I added this to my htaccess file and it took care it.
SetEnvIfNoCase Request_URI .(?:ogv|ogg|oga|m4v|mp4|m4a|mov|mp3|wav|webma?|webmv)$ no-gzip dont-vary
I was already using these attributes on my tag: controls playsinline
Server returned HTTP response code: 401 for URL: https
Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package
import sun.misc.BASE64Encoder;
import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;
and then,
String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );
public String getAuthantication(String username, String password) {
String auth = new String(Base64.encode(username + ":" + password));
return auth;
}
How can one develop iPhone apps in Java?
I'm answering this question 2 years down the line and I must stress that I did have pretty much the same problem as you did. However I'm so happy that Android has evolved into what it is today.
Having said that, I do regret that I did not learn C/C++ while I could have and I don't want to blame my teachers for it cos where was my brain when the time was right?
I'm sunk in Java today and I'm glad that I did not make the mistake of learning too many languages and being less productive... However I did learn HTML5 which really made things a lot easier, maybe someday, I might get motivated to learn C/C++ . Or if I get an Apple mac at a real throw-away price, I might learn Objective-C :)
To prevent a memory leak, the JDBC Driver has been forcibly unregistered
This is purely driver registration/deregistration issue in mysql`s driver or tomcats webapp-classloader. Copy mysql driver into tomcats lib folder (so its loaded by jvm directly, not by tomcat), and message will be gone. That makes mysql jdbc driver to be unloaded only at JVM shutdown, and noone cares about memory leaks then.
Switch role after connecting to database
If someone still needs it (like I do).
The specified role_name must be a role that the current session user is a member of.
https://www.postgresql.org/docs/10/sql-set-role.html
We need to make the current session user a member of the role:
create role myrole;
set role myrole;
grant myrole to myuser;
set role myrole;
produces:
Role ROLE created.
Error starting at line : 4 in command -
set role myrole
Error report -
ERROR: permission denied to set role "myrole"
Grant succeeded.
Role SET succeeded.
SQL Stored Procedure: If variable is not null, update statement
Yet another approach is ISNULL().
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = ISNULL(@ABC, [ABC]),
[ABCD] = ISNULL(@ABCD, [ABCD])
The difference between ISNULL and COALESCE is the return type. COALESCE can also take more than 2 arguments, and use the first that is not null. I.e.
select COALESCE(null, null, 1, 'two') --returns 1
select COALESCE(null, null, null, 'two') --returns 'two'
Powershell Log Off Remote Session
I've modified Casey's answer to only logoff disconnected sessions by doing the following:
foreach($Server in $Servers) {
try {
query user /server:$Server 2>&1 | select -skip 1 | ? {($_ -split "\s+")[-5] -eq 'Disc'} | % {logoff ($_ -split "\s+")[-6] /server:$Server /V}
}
catch {}
}
Create an empty list in python with certain size
(This was written based on the original version of the question.)
I want to create a empty list (or whatever is the best way) can hold 10 elements.
All lists can hold as many elements as you like, subject only to the limit of available memory. The only "size" of a list that matters is the number of elements currently in it.
but when I run it, the result is []
print display s1
is not valid syntax; based on your description of what you're seeing, I assume you meant display(s1)
and then print s1
. For that to run, you must have previously defined a global s1
to pass into the function.
Calling display
does not modify the list you pass in, as written. Your code says "s1
is a name for whatever thing was passed in to the function; ok, now the first thing we'll do is forget about that thing completely, and let s1
start referring instead to a newly created list
. Now we'll modify that list
". This has no effect on the value you passed in.
There is no reason to pass in a value here. (There is no real reason to create a function, either, but that's beside the point.) You want to "create" something, so that is the output of your function. No information is required to create the thing you describe, so don't pass any information in. To get information out, return
it.
That would give you something like:
def display():
s1 = list();
for i in range(0, 9):
s1[i] = i
return s1
The next problem you will note is that your list will actually have only 9 elements, because the end point is skipped by the range
function. (As side notes, []
works just as well as list()
, the semicolon is unnecessary, s1
is a poor name for the variable, and only one parameter is needed for range
if you're starting from 0
.) So then you end up with
def create_list():
result = list()
for i in range(10):
result[i] = i
return result
However, this is still missing the mark; range
is not some magical keyword that's part of the language the way for
and def
are, but instead it's a function. And guess what that function returns? That's right - a list of those integers. So the entire function collapses to
def create_list():
return range(10)
and now you see why we don't need to write a function ourselves at all; range
is already the function we're looking for. Although, again, there is no need or reason to "pre-size" the list.
Which JRE am I using?
Open a command prompt:
Version: java -version
Location: where java (in Windows)
which java (in Unix, Linux, and Mac)
To set Java home in Windows:
Right click on My computer → Properties → Advanced system settings → Environment Variable → System Variable → New.
Give the name as JAVA_HOME and the value as (e.g.) c:\programfiles\jdk
Select Path and click Edit, and keep it in the beginning as:
%JAVA_HOME%\bin;
...remaining settings goes here
How to do a HTTP HEAD request from the windows command line?
On Linux, I often use curl with the --head parameter. It is available for several operating systems, including Windows.
[edit] related to the answer below, gknw.net is currently down as of February 23 2012. Check curl.haxx.se for updated info.
Empty set literal?
Adding to the crazy ideas: with Python 3 accepting unicode identifiers, you could declare a variable ? = frozenset()
(? is U+03D5) and use it instead.
iPad browser WIDTH & HEIGHT standard
You can try this:
/*iPad landscape oriented styles */
@media only screen and (device-width:768px)and (orientation:landscape){
.yourstyle{
}
}
/*iPad Portrait oriented styles */
@media only screen and (device-width:768px)and (orientation:portrait){
.yourstyle{
}
}
Seeding the random number generator in Javascript
I've implemented a number of good, short and fast Pseudorandom number generator (PRNG) functions in plain JavaScript. All of them can be seeded and provide good quality numbers.
First of all, take care to initialize your PRNGs properly. Most of the generators below have no built-in seed generating procedure (for sake of simplicity), but accept one or more 32-bit values as the initial state of the PRNG. Similar seeds (e.g. a simple seed of 1 and 2) can cause correlations in weaker PRNGs, resulting in the output having similar properties (such as randomly generated levels being similar). To avoid this, it is best practice to initialize PRNGs with a well-distributed seed.
Thankfully, hash functions are very good at generating seeds for PRNGs from short strings. A good hash function will generate very different results even when two strings are similar. Here's an example based on MurmurHash3's mixing function:
function xmur3(str) {
for(var i = 0, h = 1779033703 ^ str.length; i < str.length; i++)
h = Math.imul(h ^ str.charCodeAt(i), 3432918353),
h = h << 13 | h >>> 19;
return function() {
h = Math.imul(h ^ h >>> 16, 2246822507);
h = Math.imul(h ^ h >>> 13, 3266489909);
return (h ^= h >>> 16) >>> 0;
}
}
Each subsequent call to the return function of xmur3
produces a new "random" 32-bit hash value to be used as a seed in a PRNG. Here's how you might use it:
// Create xmur3 state:
var seed = xmur3("apples");
// Output four 32-bit hashes to provide the seed for sfc32.
var rand = sfc32(seed(), seed(), seed(), seed());
// Output one 32-bit hash to provide the seed for mulberry32.
var rand = mulberry32(seed());
// Obtain sequential random numbers like so:
rand();
rand();
Alternatively, simply choose some dummy data to pad the seed with, and advance the generator a few times (12-20 iterations) to mix the initial state thoroughly. This is often seen in reference implementations of PRNGs, but it does limit the number of initial states.
var seed = 1337 ^ 0xDEADBEEF; // 32-bit seed with optional XOR value
// Pad seed with Phi, Pi and E.
// https://en.wikipedia.org/wiki/Nothing-up-my-sleeve_number
var rand = sfc32(0x9E3779B9, 0x243F6A88, 0xB7E15162, seed);
for (var i = 0; i < 15; i++) rand();
The output of these PRNG functions produce a positive 32-bit number (0 to 232-1) which is then converted to a floating-point number between 0-1 (0 inclusive, 1 exclusive) equivalent to Math.random()
, if you want random numbers of a specific range, read this article on MDN. If you only want the raw bits, simply remove the final division operation.
Another thing to note are the limitations of JS. Numbers can only represent whole integers up to 53-bit resolution. And when using bitwise operations, this is reduced to 32. This makes it difficult to implement algorithms written in C or C++, that use 64-bit numbers. Porting 64-bit code requires shims that can drastically reduce performance. So for the sake of simplicity and efficiency, I've only considered algorithms that use 32-bit math, as it is directly compatible with JS.
Now, onward to the the generators. (I maintain the full list with references here)
sfc32 (Simple Fast Counter)
sfc32 is part of the PractRand random number testing suite (which it passes of course). sfc32 has a 128-bit state and is very fast in JS.
function sfc32(a, b, c, d) {
return function() {
a >>>= 0; b >>>= 0; c >>>= 0; d >>>= 0;
var t = (a + b) | 0;
a = b ^ b >>> 9;
b = c + (c << 3) | 0;
c = (c << 21 | c >>> 11);
d = d + 1 | 0;
t = t + d | 0;
c = c + t | 0;
return (t >>> 0) / 4294967296;
}
}
Mulberry32
Mulberry32 is a simple generator with a 32-bit state, but is extremely fast and has good quality (author states it passes all tests of gjrand testing suite and has a full 232 period, but I haven't verified).
function mulberry32(a) {
return function() {
var t = a += 0x6D2B79F5;
t = Math.imul(t ^ t >>> 15, t | 1);
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
return ((t ^ t >>> 14) >>> 0) / 4294967296;
}
}
I would recommend this if you just need a simple but decent PRNG and don't need billions of random numbers (see Birthday problem).
xoshiro128**
As of May 2018, xoshiro128** is the new member of the Xorshift family, by Vigna & Blackman (professor Vigna was also responsible for the Xorshift128+ algorithm powering most Math.random
implementations under the hood). It is the fastest generator that offers a 128-bit state.
function xoshiro128ss(a, b, c, d) {
return function() {
var t = b << 9, r = a * 5; r = (r << 7 | r >>> 25) * 9;
c ^= a; d ^= b;
b ^= c; a ^= d; c ^= t;
d = d << 11 | d >>> 21;
return (r >>> 0) / 4294967296;
}
}
The authors claim it passes randomness tests well (albeit with caveats). Other researchers have pointed out that fails some tests in TestU01 (particularly LinearComp and BinaryRank). In practice, it should not cause issues when floats are used (such as these implementations), but may cause issues if relying on the raw low bits.
JSF (Jenkins' Small Fast)
This is JSF or 'smallprng' by Bob Jenkins (2007), the guy who made ISAAC and SpookyHash. It passes PractRand tests and should be quite fast, although not as fast as SFC.
function jsf32(a, b, c, d) {
return function() {
a |= 0; b |= 0; c |= 0; d |= 0;
var t = a - (b << 27 | b >>> 5) | 0;
a = b ^ (c << 17 | c >>> 15);
b = c + d | 0;
c = d + t | 0;
d = a + t | 0;
return (d >>> 0) / 4294967296;
}
}
LCG (aka Lehmer/Park-Miller RNG or MCG)
LCG is extremely fast and simple, but the quality of its randomness is so low, that improper use can actually cause bugs in your program!
Nonetheless, it is significantly better than some answers suggesting to use Math.sin
or Math.PI
! It's a one-liner though, which is nice :).
var LCG=s=>()=>(2**31-1&(s=Math.imul(48271,s)))/2**31;
This implementation is called the minimal standard RNG as proposed by Park–Miller in 1988 & 1993 and implemented in C++11 as minstd_rand
. Keep in mind that the state is 31-bit (31 bits give 2 billion possible states, 32 bits give double that). This is the very type of PRNG that others are trying to replace!
It will work, but I wouldn't use it unless you really need speed and don't care about randomness quality (what is random anyway?). Great for a game jam or a demo or something. LCGs suffer from seed correlations, so it is best to discard the first result of an LCG. And if you insist on using an LCG, adding an increment value may improve results, but it is probably an exercise in futility when much better options exist.
There seems to be other multipliers offering a 32-bit state (increased state-space):
var LCG=s=>()=>(s=Math.imul(741103597,s)>>>0)/2**32;
var LCG=s=>()=>(s=Math.imul(1597334677,s)>>>0)/2**32;
These LCG values are from: P. L'Ecuyer: A table of Linear Congruential Generators of different sizes and good lattice structure, April 30 1997.
What is the most efficient way to concatenate N arrays?
For people using ES2015 (ES6)
You can now use the Spread Syntax to concatenate arrays:
const arr1 = [0, 1, 2],
arr2 = [3, 4, 5];
const result1 = [...arr1, ...arr2]; // -> [0, 1, 2, 3, 4, 5]
// or...
const result2 = [...arr2, ...arr1]; // -> [3, 4, 5, 0, 1, 2]
Find everything between two XML tags with RegEx
It is not good to use this method but if you really want to split it with regex
<primaryAddress.*>((.|\n)*?)<\/primaryAddress>
the verified answer returns the tags but this just return the value between tags.
Converting byte array to string in javascript
Even if I'm a bit late, I thought it would be interesting for future users to share some one-liners implementations I did using ES6.
One thing that I consider important depending on your environment or/and what you will do with with the data is to preserve the full byte value. For example, (5).toString(2)
will give you 101
, but the complete binary conversion is in reality 00000101
, and that's why you might need to create a leftPad
implementation to fill the string byte with leading zeros. But you may not need it at all, like other answers demonstrated.
If you run the below code snippet, you'll see the first output being the conversion of the abc
string to a byte array and right after that the re-transformation of said array to it's corresponding string.
_x000D_
_x000D_
// For each byte in our array, retrieve the char code value of the binary value_x000D_
const binArrayToString = array => array.map(byte => String.fromCharCode(parseInt(byte, 2))).join('')_x000D_
_x000D_
// Basic left pad implementation to ensure string is on 8 bits_x000D_
const leftPad = str => str.length < 8 ? (Array(8).join('0') + str).slice(-8) : str_x000D_
_x000D_
// For each char of the string, get the int code and convert it to binary. Ensure 8 bits._x000D_
const stringToBinArray = str => str.split('').map(c => leftPad(c.charCodeAt().toString(2)))_x000D_
_x000D_
const array = stringToBinArray('abc')_x000D_
_x000D_
console.log(array)_x000D_
console.log(binArrayToString(array))
_x000D_
_x000D_
_x000D_
Replace string in text file using PHP
Thanks to your comments. I've made a function that give an error message when it happens:
/**
* Replaces a string in a file
*
* @param string $FilePath
* @param string $OldText text to be replaced
* @param string $NewText new text
* @return array $Result status (success | error) & message (file exist, file permissions)
*/
function replace_in_file($FilePath, $OldText, $NewText)
{
$Result = array('status' => 'error', 'message' => '');
if(file_exists($FilePath)===TRUE)
{
if(is_writeable($FilePath))
{
try
{
$FileContent = file_get_contents($FilePath);
$FileContent = str_replace($OldText, $NewText, $FileContent);
if(file_put_contents($FilePath, $FileContent) > 0)
{
$Result["status"] = 'success';
}
else
{
$Result["message"] = 'Error while writing file';
}
}
catch(Exception $e)
{
$Result["message"] = 'Error : '.$e;
}
}
else
{
$Result["message"] = 'File '.$FilePath.' is not writable !';
}
}
else
{
$Result["message"] = 'File '.$FilePath.' does not exist !';
}
return $Result;
}
How to get the latest tag name in current branch in Git?
To get the most recent tag, you can do:
$ git for-each-ref refs/tags --sort=-taggerdate --format='%(refname)' --count=1
Of course, you can change the count argument or the sort field as desired. It appears
that you may have meant to ask a slightly different question, but this does answer the question as I interpret it.
Stop node.js program from command line
You can use fuser to get what you want to be done.
In order to obtain the process ids of the tasks running on a port you can do:
fuser <<target_port>>/tcp
Let's say the port is 8888, the command becomes:
fuser 8888/tcp
And to kill a process that is running on a port, simply add -k switch.
fuser <<target_port>>/tcp -k
Example (port is 8888):
fuser 8888/tcp -k
That's it! It will close the process listening on the port.
I usually do this before running my server application.
What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?
To clarify for anyone who is looking for what is the difference between the 3 on a simpler level. You can expose your service with minimal ClusterIp (within k8s cluster) or larger exposure with NodePort (within cluster external to k8s cluster) or LoadBalancer (external world or whatever you defined in your LB).
ClusterIp exposure < NodePort exposure < LoadBalancer exposure
- ClusterIp
Expose service through k8s cluster with ip/name:port
- NodePort
Expose service through Internal network VM's also external to k8s ip/name:port
- LoadBalancer
Expose service through External world or whatever you defined in your LB.
How to make blinking/flashing text with CSS 3
You are first setting opacity: 1;
and then you are ending it on 0
, so it starts from 0%
and ends on 100%
, so instead just set opacity to 0
at 50%
and the rest will take care of itself.
Demo
_x000D_
_x000D_
.blink_me {_x000D_
animation: blinker 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes blinker {_x000D_
50% {_x000D_
opacity: 0;_x000D_
}_x000D_
}
_x000D_
<div class="blink_me">BLINK ME</div>
_x000D_
_x000D_
_x000D_
Here, I am setting the animation duration to be 1 second
, and then I am setting the timing
to linear
. That means it will be constant throughout. Last, I am using infinite
. That means it will go on and on.
Note: If this doesn't work for you, use browser prefixes like
-webkit
, -moz
and so on as required for animation
and
@keyframes
. You can refer to my detailed code here
As commented, this won't work on older versions of Internet Explorer, and for that you need to use jQuery or JavaScript...
(function blink() {
$('.blink_me').fadeOut(500).fadeIn(500, blink);
})();
Thanks to Alnitak for suggesting a better approach.
Demo (Blinker using jQuery)
How can I get a list of all classes within current module in Python?
If you want to have all the classes, that belong to the current module, you could use this :
import sys, inspect
def print_classes():
is_class_member = lambda member: inspect.isclass(member) and member.__module__ == __name__
clsmembers = inspect.getmembers(sys.modules[__name__], is_class_member)
If you use Nadia's answer and you were importing other classes on your module, that classes will be being imported too.
So that's why member.__module__ == __name__
is being added to the predicate used on is_class_member
. This statement checks that the class really belongs to the module.
A predicate is a function (callable), that returns a boolean value.
Get Table and Index storage size in sql server
with pages as (
SELECT object_id, SUM (reserved_page_count) as reserved_pages, SUM (used_page_count) as used_pages,
SUM (case
when (index_id < 2) then (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
else lob_used_page_count + row_overflow_used_page_count
end) as pages
FROM sys.dm_db_partition_stats
group by object_id
), extra as (
SELECT p.object_id, sum(reserved_page_count) as reserved_pages, sum(used_page_count) as used_pages
FROM sys.dm_db_partition_stats p, sys.internal_tables it
WHERE it.internal_type IN (202,204,211,212,213,214,215,216) AND p.object_id = it.object_id
group by p.object_id
)
SELECT object_schema_name(p.object_id) + '.' + object_name(p.object_id) as TableName, (p.reserved_pages + isnull(e.reserved_pages, 0)) * 8 as reserved_kb,
pages * 8 as data_kb,
(CASE WHEN p.used_pages + isnull(e.used_pages, 0) > pages THEN (p.used_pages + isnull(e.used_pages, 0) - pages) ELSE 0 END) * 8 as index_kb,
(CASE WHEN p.reserved_pages + isnull(e.reserved_pages, 0) > p.used_pages + isnull(e.used_pages, 0) THEN (p.reserved_pages + isnull(e.reserved_pages, 0) - p.used_pages + isnull(e.used_pages, 0)) else 0 end) * 8 as unused_kb
from pages p
left outer join extra e on p.object_id = e.object_id
Takes into account internal tables, such as those used for XML storage.
Edit: If you divide the data_kb
and index_kb
values by 1024.0, you will get the numbers you see in the GUI.
How can I create a border around an Android LinearLayout?
Creat XML called border.xml in drawable folder as below :
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
</item>
<item android:left="5dp" android:right="5dp" android:top="5dp" >
<shape android:shape="rectangle">
<solid android:color="#000000" />
</shape>
</item>
</layer-list>
then add this to linear layout as backgound as this:
android:background="@drawable/border"
How do you pass a function as a parameter in C?
Declaration
A prototype for a function which takes a function parameter looks like the following:
void func ( void (*f)(int) );
This states that the parameter f
will be a pointer to a function which has a void
return type and which takes a single int
parameter. The following function (print
) is an example of a function which could be passed to func
as a parameter because it is the proper type:
void print ( int x ) {
printf("%d\n", x);
}
Function Call
When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:
func(print);
would call func
, passing the print function to it.
Function Body
As with any parameter, func
can now use the parameter's name in the function body to access the value of the parameter. Let's say that func
will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
print(ctr);
}
Since func
's parameter declaration says that f
is the name for a pointer to the desired function, we recall first that if f
is a pointer then *f
is the thing that f
points to (i.e. the function print
in this case). As a result, just replace every occurrence of print in the loop above with *f
:
void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
Source
How do you format a Date/Time in TypeScript?
This worked for me
/**
* Convert Date type to "YYYY/MM/DD" string
* - AKA ISO format?
* - It's logical and sortable :)
* - 20200227
* @param Date eg. new Date()
* https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd
* https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd?page=2&tab=active#tab-top
*/
static DateToYYYYMMDD(Date: Date): string {
let DS: string = Date.getFullYear()
+ '/' + ('0' + (Date.getMonth() + 1)).slice(-2)
+ '/' + ('0' + Date.getDate()).slice(-2)
return DS
}
You can certainly add HH:MM something like this...
static DateToYYYYMMDD_HHMM(Date: Date): string {
let DS: string = Date.getFullYear()
+ '/' + ('0' + (Date.getMonth() + 1)).slice(-2)
+ '/' + ('0' + Date.getDate()).slice(-2)
+ ' ' + ('0' + Date.getHours()).slice(-2)
+ ':' + ('0' + Date.getMinutes()).slice(-2)
return DS
}
Add to integers in a list
You can append to the end of a list:
foo = [1, 2, 3, 4, 5]
foo.append(4)
foo.append([8,7])
print(foo) # [1, 2, 3, 4, 5, 4, [8, 7]]
You can edit items in the list like this:
foo = [1, 2, 3, 4, 5]
foo[3] = foo[3] + 4
print(foo) # [1, 2, 3, 8, 5]
Insert integers into the middle of a list:
x = [2, 5, 10]
x.insert(2, 77)
print(x) # [2, 5, 77, 10]
Where is android studio building my .apk file?
Go to AndroidStudio projects File
- Select the project name,
- Select app
- Select build
- Select Outputs
- Select Apk
You will find APK files of app here, if you have ran the app in AVD or even hardware device
How do you Sort a DataTable given column and direction?
In case you want to sort in more than one direction
public static void sortOutputTable(ref DataTable output)
{
DataView dv = output.DefaultView;
dv.Sort = "specialCode ASC, otherCode DESC";
DataTable sortedDT = dv.ToTable();
output = sortedDT;
}
Pagination on a list using ng-repeat
I know this thread is old now but I am answering it to keep things a bit updated.
With Angular 1.4 and above you can directly use limitTo filter which apart from accepting the limit
parameter also accepts a begin
parameter.
Usage: {{ limitTo_expression | limitTo : limit : begin}}
So now you may not need to use any third party library to achieve something like pagination. I have created a fiddle to illustrate the same.
How to block until an event is fired in c#
If the current method is async then you can use TaskCompletionSource. Create a field that the event handler and the current method can access.
TaskCompletionSource<bool> tcs = null;
private async void Button_Click(object sender, RoutedEventArgs e)
{
tcs = new TaskCompletionSource<bool>();
await tcs.Task;
WelcomeTitle.Text = "Finished work";
}
private void Button_Click2(object sender, RoutedEventArgs e)
{
tcs?.TrySetResult(true);
}
This example uses a form that has a textblock named WelcomeTitle and two buttons. When the first button is clicked it starts the click event but stops at the await line. When the second button is clicked the task is completed and the WelcomeTitle text is updated. If you want to timeout as well then change
await tcs.Task;
to
await Task.WhenAny(tcs.Task, Task.Delay(25000));
if (tcs.Task.IsCompleted)
WelcomeTitle.Text = "Task Completed";
else
WelcomeTitle.Text = "Task Timed Out";
How to persist data in a dockerized postgres database using volumes
You can create a common volume for all Postgres data
docker volume create pgdata
or you can set it to the compose file
version: "3"
services:
db:
image: postgres
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgress
- POSTGRES_DB=postgres
ports:
- "5433:5432"
volumes:
- pgdata:/var/lib/postgresql/data
networks:
- suruse
volumes:
pgdata:
It will create volume name pgdata and mount this volume to container's path.
You can inspect this volume
docker volume inspect pgdata
// output will be
[
{
"Driver": "local",
"Labels": {},
"Mountpoint": "/var/lib/docker/volumes/pgdata/_data",
"Name": "pgdata",
"Options": {},
"Scope": "local"
}
]
No module named setuptools
The question mentions Windows, and the accepted answer also works for Ubuntu, but for those who found this question coming from a Redhat flavor of Linux, this did the trick:
sudo yum install -y python-setuptools
jQuery and TinyMCE: textarea value doesn't submit
@eldar: I had the same issue with 3.6.7 running in 'normal mode'; and neither triggerSave or save() were working.
I changed to the jQuery TinyMCE plugin and without having to do anything else it's working now. I'm assuming somewhere along the line they implemented some kind of auto triggerSave for the jQuery version of TinyMCE.
php mail setup in xampp
My favorite smtp server is hMailServer.
It has a nice windows friendly installer and wizard. Hands down the easiest mail server I've ever setup.
It can proxy through your gmail/yahoo/etc account or send email directly.
Once it is installed, email in xampp just works with no config changes.
Is there any way to set environment variables in Visual Studio Code?
As it does not answer your question but searching vm arguments I stumbled on this page and there seem to be no other. So if you want to pass vm arguments its like so
{
"version": "0.2.0",
"configurations": [
{
"type": "java",
"name": "ddtBatch",
"request": "launch",
"mainClass": "com.something.MyApplication",
"projectName": "MyProject",
"args": "Hello",
"vmArgs": "-Dspring.config.location=./application.properties"
}
]
}
In Python, how do I read the exif data for an image?
I usually use pyexiv2 to set exif information in JPG files, but when I import the library in a script QGIS script crash.
I found a solution using the library exif:
https://pypi.org/project/exif/
It's so easy to use, and with Qgis I don,'t have any problem.
In this code I insert GPS coordinates to a snapshot of screen:
from exif import Image
with open(file_name, 'rb') as image_file:
my_image = Image(image_file)
my_image.make = "Python"
my_image.gps_latitude_ref=exif_lat_ref
my_image.gps_latitude=exif_lat
my_image.gps_longitude_ref= exif_lon_ref
my_image.gps_longitude= exif_lon
with open(file_name, 'wb') as new_image_file:
new_image_file.write(my_image.get_file())
How to show Page Loading div until the page has finished loading?
This will be in synchronisation with an api call, When the api call is triggered, the loader is shown. When the api call is succesful, the loader is removed. This can be used for either page load or during an api call.
$.ajax({
type: 'GET',
url: url,
async: true,
dataType: 'json',
beforeSend: function (xhr) {
$( "<div class='loader' id='searching-loader'></div>").appendTo("#table-playlist-section");
$("html, body").animate( { scrollTop: $(document).height() }, 100);
},
success: function (jsonOptions) {
$('#searching-loader').remove();
.
.
}
});
CSS
.loader {
border: 2px solid #f3f3f3;
border-radius: 50%;
border-top: 2px solid #3498db;
width: 30px;
height: 30px;
margin: auto;
-webkit-animation: spin 2s linear infinite; /* Safari */
animation: spin 2s linear infinite;
margin-top: 35px;
margin-bottom: -35px;
}
/* Safari */
@-webkit-keyframes spin {
0% { -webkit-transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); }
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
Parsing JSON from URL
GSON has a builder that takes a Reader object: fromJson(Reader json, Class classOfT).
This means you can create a Reader from a URL and then pass it to Gson to consume the stream and do the deserialisation.
Only three lines of relevant code.
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;
import com.google.gson.Gson;
public class GsonFetchNetworkJson {
public static void main(String[] ignored) throws Exception {
URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
InputStreamReader reader = new InputStreamReader(url.openStream());
MyDto dto = new Gson().fromJson(reader, MyDto.class);
// using the deserialized object
System.out.println(dto.headers);
System.out.println(dto.args);
System.out.println(dto.origin);
System.out.println(dto.url);
}
private class MyDto {
Map<String, String> headers;
Map<String, String> args;
String origin;
String url;
}
}
If you happen to get a 403 error code with an endpoint which otherwise works fine (e.g. with curl
or other clients) then a possible cause could be that the endpoint expects a User-Agent
header and by default Java URLConnection is not setting it. An easy fix is to add at the top of the file e.g. System.setProperty("http.agent", "Netscape 1.0");
.
Writing to a new file if it doesn't exist, and appending to a file if it does
It's not clear to me exactly where the high-score that you're interested in is stored, but the code below should be what you need to check if the file exists and append to it if desired. I prefer this method to the "try/except".
import os
player = 'bob'
filename = player+'.txt'
if os.path.exists(filename):
append_write = 'a' # append if already exists
else:
append_write = 'w' # make a new file if not
highscore = open(filename,append_write)
highscore.write("Username: " + player + '\n')
highscore.close()
MySQL LEFT JOIN Multiple Conditions
Correct answer is simply:
SELECT a.group_id
FROM a
LEFT JOIN b ON a.group_id=b.group_id and b.user_id = 4
where b.user_id is null
and a.keyword like '%keyword%'
Here we are checking user_id = 4
(your user id from the session). Since we have it in the join criteria, it will return null values for any row in table b that does not match the criteria - ie, any group that that user_id is NOT in.
From there, all we need to do is filter for the null values, and we have all the groups that your user is not in.
demo here
Error: Cannot match any routes. URL Segment: - Angular 2
please modify your router.module.ts as:
const routes: Routes = [
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'two',
component: ClassTwo, children: [
{
path: 'three',
component: ClassThree,
outlet: 'nameThree',
},
{
path: 'four',
component: ClassFour,
outlet: 'nameFour'
},
{
path: '',
redirectTo: 'two',
pathMatch: 'full'
}
]
},];
and in your component1.html
<h3>In One</h3>
<nav>
<a routerLink="/two" class="dash-item">...Go to Two...</a>
<a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
<a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>
<router-outlet></router-outlet> // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
Row Offset in SQL Server
You can use ROW_NUMBER()
function to get what you want:
SELECT *
FROM (SELECT ROW_NUMBER() OVER(ORDER BY id) RowNr, id FROM tbl) t
WHERE RowNr BETWEEN 10 AND 20
Remove all values within one list from another list?
>>> a=range(1,10)
>>> for i in [2,3,7]: a.remove(i)
...
>>> a
[1, 4, 5, 6, 8, 9]
>>> a=range(1,10)
>>> b=map(a.remove,[2,3,7])
>>> a
[1, 4, 5, 6, 8, 9]
Find first element by predicate
Already answered by @AjaxLeung, but in comments and hard to find.
For check only
lst.stream()
.filter(x -> x > 5)
.findFirst()
.isPresent()
is simplified to
lst.stream()
.anyMatch(x -> x > 5)
How do I load external fonts into an HTML document?
Try this
<style>
@font-face {
font-family: Roboto Bold Condensed;
src: url(fonts/Roboto_Condensed/RobotoCondensed-Bold.ttf);
}
@font-face {
font-family:Roboto Condensed;
src: url(fonts/Roboto_Condensed/RobotoCondensed-Regular.tff);
}
div1{
font-family:Roboto Bold Condensed;
}
div2{
font-family:Roboto Condensed;
}
</style>
<div id='div1' >This is Sample text</div>
<div id='div2' >This is Sample text</div>
Short circuit Array.forEach like calling break
This is just something I came up with to solve the problem... I'm pretty sure it fixes the problem that the original asker had:
Array.prototype.each = function(callback){
if(!callback) return false;
for(var i=0; i<this.length; i++){
if(callback(this[i], i) == false) break;
}
};
And then you would call it by using:
var myarray = [1,2,3];
myarray.each(function(item, index){
// do something with the item
// if(item != somecondition) return false;
});
Returning false inside the callback function will cause a break. Let me know if that doesn't actually work.
CSS to select/style first word
Sadly even with the likes of CSS 3 we still do not have the likes of :first-word
:last-word
etc using pure CSS. Thankfully there's almost a JavaScript nowadays for everything which brings me to my recommendation. Using nthEverything and jQuery you can expand from the traditional Pseudo elements.
Currently the valid Pseudos are:
:first-child
:first-of-type
:only-child
:last-child
:last-of-type
:only-of-type
:nth-child
:nth-of-type
:nth-last-child
:nth-last-of-type
And using nth Everything we can expand this to:
::first-letter
::first-line
::first-word
::last-letter
::last-line
::last-word
::nth-letter
::nth-line
::nth-word
::nth-last-letter
::nth-last-line
::nth-last-word
How to convert a string to utf-8 in Python
Might be a bit overkill, but when I work with ascii and unicode in same files, repeating decode can be a pain, this is what I use:
def make_unicode(input):
if type(input) != unicode:
input = input.decode('utf-8')
return input
Returning string from C function
You are allocating your string on the stack, and then returning a pointer to it. When your function returns, any stack allocations become invalid; the pointer now points to a region on the stack that is likely to be overwritten the next time a function is called.
In order to do what you're trying to do, you need to do one of the following:
- Allocate memory on the heap using
malloc
or similar, then return that pointer. The caller will then need to call free
when it is done with the memory.
- Allocate the string on the stack in the calling function (the one that will be using the string), and pass a pointer in to the function to put the string into. During the entire call to the calling function, data on its stack is valid; its only once you return that stack allocated space becomes used by something else.
VSCode: How to Split Editor Vertically
If you're looking for a way to change this through the GUI, at least in the current version 1.10.1 if you hover over the OPEN EDITORS
group in the EXPLORER
pane a button appears that toggles the editor group layout between horizontal and vertical.
Fill formula down till last row in column
Wonderful answer! I needed to fill in the empty cells in a column where there were titles in cells that applied to the empty cells below until the next title cell.
I used your code above to develop the code that is below my example sheet here. I applied this code as a macro ctl/shft/D to rapidly run down the column copying the titles.
--- Example Spreadsheet ------------
Title1 is copied to rows 2 and 3; Title2 is copied to cells below it in rows 5 and 6. After the second run of the Macro the active cell is the Title3 cell.
' **row** **Column1** **Column2**
' 1 Title1 Data 1 for title 1
' 2 Data 2 for title 1
' 3 Data 3 for title 1
' 4 Title2 Data 1 for title 2
' 5 Data 2 for title 2
' 6 Data 3 for title 2
' 7 Title 3 Data 1 for title 3
----- CopyDown code ----------
Sub CopyDown()
Dim Lastrow As String, FirstRow As String, strtCell As Range
'
' CopyDown Macro
' Copies the current cell to any empty cells below it.
'
' Keyboard Shortcut: Ctrl+Shift+D
'
Set strtCell = ActiveCell
FirstRow = strtCell.Address
' Lastrow is address of the *list* of empty cells
Lastrow = Range(Selection, Selection.End(xlDown).Offset(-1, 0)).Address
' MsgBox Lastrow
Range(Lastrow).Formula = strtCell.Formula
Range(Lastrow).End(xlDown).Select
End Sub
What is null in Java?
Null in Java(tm)
In C and C++, "NULL" is a constant defined in a header file, with a value like:
0
or:
0L
or:
((void*)0)
depending on the compiler and memory model options. NULL is not, strictly speaking, part of C/C++ itself.
In Java(tm), "null" is not a keyword, but a special literal of the null type. It can be cast to any reference type, but not to any primitive type such as int or boolean. The null literal doesn't necessarily have value zero. And it is impossible to cast to the null type or declare a variable of this type.
MongoDB - admin user not authorized
I had this problem because of the hostname in my MongoDB Compass was pointing to admin instead for my project. Fixed by adding the /projectname after the hostname :)
Try this:
- Choose your project in the MongoDB atlas website
- Connect/Connect with MongoDB Compass
- Download Compass/Choose your OS
- I used Compass 1.12 or later
- Copy the connection string under the Compass 1.12 or later.
- Open MongoDB Compass/Connect(top left)/Connect To
- Connection String detected/Yes/
- Append your project name after the hostname: cluster9-foodie.mongodb.net/projectname
- Connect & Tested the API with POSTMAN.
- Succeed.
Use the same connection string in your code too:
- Before:
- mongodb+srv://projectname:password@cluster9-foodie.mongodb.net/admin
- After:
- mongodb+srv://projectname:password@cluster9-foodie.mongodb.net/projectname
Good luck.
Intercept and override HTTP requests from WebView
As far as I know, shouldOverrideUrlLoading is not called for images but rather for hyperlinks... I think the appropriate method is
@Override
public void onLoadResource(WebView view, String url)
This method is called for every resource (image, styleesheet, script) that's loaded by the webview, but since it's a void, I haven't found a way to change that url and replace it so that it loads a local resource ...
Pass array to MySQL stored routine
I'm not sure if this is fully answering the question (it isn't), but it's the solution I came up with for my similar problem. Here I try to just use LOCATE() just once per delimiter.
-- *****************************************************************************
-- test_PVreplace
DROP FUNCTION IF EXISTS test_PVreplace;
delimiter //
CREATE FUNCTION test_PVreplace (
str TEXT, -- String to do search'n'replace on
pv TEXT -- Parameter/value pairs 'p1=v1|p2=v2|p3=v3'
)
RETURNS TEXT
-- Replace specific tags with specific values.
sproc:BEGIN
DECLARE idx INT;
DECLARE idx0 INT DEFAULT 1; -- 1-origined, not 0-origined
DECLARE len INT;
DECLARE sPV TEXT;
DECLARE iPV INT;
DECLARE sP TEXT;
DECLARE sV TEXT;
-- P/V string *must* end with a delimiter.
IF (RIGHT (pv, 1) <> '|') THEN
SET pv = CONCAT (pv, '|');
END IF;
-- Find all the P/V pairs.
SELECT LOCATE ('|', pv, idx0) INTO idx;
WHILE (idx > 0) DO
SET len = idx - idx0;
SELECT SUBSTRING(pv, idx0, len) INTO sPV;
-- Found a P/V pair. Break it up.
SELECT LOCATE ('=', sPV) INTO iPV;
IF (iPV = 0) THEN
SET sP = sPV;
SET sV = '';
ELSE
SELECT SUBSTRING(sPV, 1, iPV-1) INTO sP;
SELECT SUBSTRING(sPV, iPV+1) INTO sV;
END IF;
-- Do the substitution(s).
SELECT REPLACE (str, sP, sV) INTO str;
-- Do next P/V pair.
SET idx0 = idx + 1;
SELECT LOCATE ('|', pv, idx0) INTO idx;
END WHILE;
RETURN (str);
END//
delimiter ;
SELECT test_PVreplace ('%one% %two% %three%', '%one%=1|%two%=2|%three%=3');
SELECT test_PVreplace ('%one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '%one%=I|%two%=II|%three%=III');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', '');
SELECT test_PVreplace ('%one% %two% %three% - %one% %two% %three%', NULL);
SELECT test_PVreplace ('%one% %two% %three%', '%one%=%two%|%two%=%three%|%three%=III');
How to get elements with multiple classes
As @filoxo said, you can use document.querySelectorAll
.
If you know that there is only one element with the class you are looking for, or you are interested only in the first one, you can use:
document.querySelector('.class1.class2');
BTW, while .class1.class2
indicates an element with both classes, .class1 .class2
(notice the whitespace) indicates an hierarchy - and element with class class2
which is inside en element with class class1
:
<div class='class1'>
<div>
<div class='class2'>
:
:
And if you want to force retrieving a direct child, use >
sign (.class1 > .class2
):
<div class='class1'>
<div class='class2'>
:
:
For entire information about selectors:
https://www.w3schools.com/jquery/jquery_ref_selectors.asp
PHP filesize MB/KB conversion
I think this is a better approach. Simple and straight forward.
public function sizeFilter( $bytes )
{
$label = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB' );
for( $i = 0; $bytes >= 1024 && $i < ( count( $label ) -1 ); $bytes /= 1024, $i++ );
return( round( $bytes, 2 ) . " " . $label[$i] );
}
How to download fetch response in react as file
I needed to just download a file onClick but I needed to run some logic to either fetch or compute the actual url where the file existed. I also did not want to use any anti-react imperative patterns like setting a ref and manually clicking it when I had the resource url. The declarative pattern I used was
onClick = () => {
// do something to compute or go fetch
// the url we need from the server
const url = goComputeOrFetchURL();
// window.location forces the browser to prompt the user if they want to download it
window.location = url
}
render() {
return (
<Button onClick={ this.onClick } />
);
}
jquery ajax get responsetext from http url
As Karim said, cross domain ajax doesn't work unless the server allows for it. In this case Google does not, BUT, there is a simple trick to get around this in many cases. Just have your local server pass the content retrieved through HTTP or HTTPS.
For example, if you were using PHP, you could:
Create the file web_root/ajax_responders/google.php with:
<?php
echo file_get_contents('http://www.google.de');
?>
And then alter your code to connect to that instead of to Google's domain directly in the javascript:
var response = $.ajax({ type: "GET",
url: "/ajax_responders/google.php",
async: false
}).responseText;
alert(response);
add onclick function to a submit button
html:
<form method="post" name="form1" id="form1">
<input id="submit" name="submit" type="submit" value="Submit" onclick="eatFood();" />
</form>
Javascript:
to submit the form using javascript
function eatFood() {
document.getElementById('form1').submit();
}
to show onclick message
function eatFood() {
alert('Form has been submitted');
}
How to add a progress bar to a shell script?
This is a psychedelic progressbar for bash scripting by nExace. It can be called from command line as './progressbar x y' where 'x' is a time in seconds and 'y' is a message associated with that portion of the progress.
The inner progressbar() function itself is good standalone as well if you want other portions of your script to control the progressbar. For instance, sending 'progressbar 10 "Creating directory tree";' will display:
[####### ] (10%) Creating directory tree
Of course it will be nicely psychedelic though...
#!/bin/bash
if [ "$#" -eq 0 ]; then echo "x is \"time in seconds\" and z is \"message\""; echo "Usage: progressbar x z"; exit; fi
progressbar() {
local loca=$1; local loca2=$2;
declare -a bgcolors; declare -a fgcolors;
for i in {40..46} {100..106}; do
bgcolors+=("$i")
done
for i in {30..36} {90..96}; do
fgcolors+=("$i")
done
local u=$(( 50 - loca ));
local y; local t;
local z; z=$(printf '%*s' "$u");
local w=$(( loca * 2 ));
local bouncer=".oO°Oo.";
for ((i=0;i<loca;i++)); do
t="${bouncer:((i%${#bouncer})):1}"
bgcolor="\\E[${bgcolors[RANDOM % 14]}m \\033[m"
y+="$bgcolor";
done
fgcolor="\\E[${fgcolors[RANDOM % 14]}m"
echo -ne " $fgcolor$t$y$z$fgcolor$t \\E[96m(\\E[36m$w%\\E[96m)\\E[92m $fgcolor$loca2\\033[m\r"
};
timeprogress() {
local loca="$1"; local loca2="$2";
loca=$(bc -l <<< scale=2\;"$loca/50")
for i in {1..50}; do
progressbar "$i" "$loca2";
sleep "$loca";
done
printf "\n"
};
timeprogress "$1" "$2"
How to determine if object is in array
This function is to check for a unique field.
Arg 1: the array with selected data
Arg 2: key to check
Arg 3: value that must be "validated"
function objectUnique( array, field, value )
{
var unique = true;
array.forEach(function ( entry )
{
if ( entry[field] == value )
{
unique = false;
}
});
return unique;
}
Can I rollback a transaction I've already committed? (data loss)
No, you can't undo, rollback or reverse a commit.
STOP THE DATABASE!
(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE
or similar, not an rm -rf /data/directory
scenario).
If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate
so that no checkpoint is run on shutdown.
You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.
If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.
Urgent mitigation
Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base
, pg_clog
, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog
etc. No part is unimportant.
Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.
Ways some data could've survived
If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT
or UPDATE
. Thus, the old versions of the UPDATE
d rows might still be lying around, present but inaccessible.
Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter
and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl
in immediate
mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.
Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.
Recovery
You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.
I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOAST
ed data so it's of limited utility. Give it a try, if you're lucky it might work.
See: pg_dirtyread on GitHub.
I've removed what I'd written in this section as it's obsoleted by that tool.
See also PostgreSQL row storage fundamentals
Prevention
See my blog entry Preventing PostgreSQL database corruption.
On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED
for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.
Angular.js: set element height on page load
My solution if your ng-grid depend of element parent(div, layout) :
directive
myapp.directive('sizeelement', function ($window) {
return{
scope:true,
priority: 0,
link: function (scope, element) {
scope.$watch(function(){return $(element).height(); }, function(newValue, oldValue) {
scope.height=$(element).height();
});
}}
})
sample html
<div class="portlet box grey" style="height: 100%" sizeelement>
<div class="portlet-title">
<h4><i class="icon-list"></i>Articles</h4>
</div>
<div class="portlet-body" style="height:{{height-34}}px">
<div class="gridStyle" ng-grid="gridOrderLine" ="min-height: 250px;"></div>
</div>
</div>
height-34 : 34 is fix height of my title div, you can fix other height.
It is easy directive but it work fine.
Parse JSON in TSQL
I seem to have a huge masochistic streak in that I've written a JSON parser. It converts a JSON document into a SQL Adjacency list table, which is easy to use to update your data tables. Actually, I've done worse, in that I've done code to do the reverse process, which is to go from a hierarchy table to a JSON string
The article and code is here: Consuming Json strings in SQL server.
Select * from parseJSON('{
"Person":
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"Address":
{
"streetAddress":"21 2nd Street",
"city":"New York",
"state":"NY",
"postalCode":"10021"
},
"PhoneNumbers":
{
"home":"212 555-1234",
"fax":"646 555-4567"
}
}
}
')
To get:
Remove specific rows from a data frame
X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
Variable1 Variable2
1 11 2
2 14 3
3 12 1
4 15 4
> X[X$Variable1!=11 & X$Variable1!=12, ]
Variable1 Variable2
2 14 3
4 15 4
> X[ ! X$Variable1 %in% c(11,12), ]
Variable1 Variable2
2 14 3
4 15 4
You can functionalize this however you like.
Select value from list of tuples where condition
If you have named tuples you can do this:
results = [t.age for t in mylist if t.person_id == 10]
Otherwise use indexes:
results = [t[1] for t in mylist if t[0] == 10]
Or use tuple unpacking as per Nate's answer. Note that you don't have to give a meaningful name to every item you unpack. You can do (person_id, age, _, _, _, _)
to unpack a six item tuple.
Use a LIKE statement on SQL Server XML Datatype
Yet another option is to cast the XML as nvarchar, and then search for the given string as if the XML vas a nvarchar field.
SELECT *
FROM Table
WHERE CAST(Column as nvarchar(max)) LIKE '%TEST%'
I love this solution as it is clean, easy to remember, hard to mess up, and can be used as a part of a where clause.
EDIT: As Cliff mentions it, you could use:
...nvarchar if there's characters that don't convert to varchar
How to install Flask on Windows?
Assuming you are a PyCharm User, its pretty easy to install Flask
This will help users without shell pip access also.
- Open Settings(Ctrl+Alt+s) >>
- Goto Project Interpreter>>
- Double click pip>> Search for flask
- Select and click Install Package ( Check Install to site users if intending to use Flask for this project alone
Done!!!
Cases in which flask is not shown in pip:
Open Manage Repository>>
Add(+) >> Add this following url
https://www.palletsprojects.com/p/flask/
Now back to pip, it will show related packages of flask,
- select flask>>
- install package>>
Voila!!!
How to redirect to an external URL in Angular2?
If you've been using the OnDestry lifecycle hook, you might be interested in using something like this before calling window.location.href=...
this.router.ngOnDestroy();
window.location.href = 'http://www.cnn.com/';
that will trigger the OnDestry callback in your component that you might like.
Ohh, and also:
import { Router } from '@angular/router';
is where you find the router.
---EDIT---
Sadly, I might have been wrong in the example above. At least it's not working as exepected in my production code right now - so, until I have time to investigate further, I solve it like this (since my app really need the hook when possible)
this.router.navigate(["/"]).then(result=>{window.location.href = 'http://www.cnn.com/';});
Basically routing to any (dummy) route to force the hook, and then navigate as requested.
How do I get the current timezone name in Postgres 9.3?
This may or may not help you address your problem, OP, but to get the timezone of the current server relative to UTC (UT1, technically), do:
SELECT EXTRACT(TIMEZONE FROM now())/3600.0;
The above works by extracting the UT1-relative offset in minutes, and then converting it to hours using the factor of 3600 secs/hour.
Example:
SET SESSION timezone TO 'Asia/Kabul';
SELECT EXTRACT(TIMEZONE FROM now())/3600.0;
-- output: 4.5 (as of the writing of this post)
(docs).
jquery validate check at least one checkbox
This is how I have dealt with it in the past:
$().ready(function() {
$("#contact").validate({
submitHandler: function(form) {
// see if selectone is even being used
var boxes = $('.selectone:checkbox');
if(boxes.length > 0) {
if( $('.selectone:checkbox:checked').length < 1) {
alert('Please select at least one checkbox');
boxes[0].focus();
return false;
}
}
form.submit();
}
});
});
Open Cygwin at a specific folder
In the answer that uses the registry, I found that on Windows 2008 R2 SP1, you need to drop the Background out of the path. Further, since the chere and xhere are not part of cygwin64, here is a solution that works for both, combining the registry and the Send To solutions. Replace 'E:\cygwin64' with your install location:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash]
@="Open Cygwin Here"
[HKEY_CLASSES_ROOT\Directory\shell\cygwin_bash\command]
@="E:\\cygwin64\\bin\\mintty.exe -i /Cygwin-Terminal.ico --exec /bin/bash.exe --login -c \"cd '%1' ; exec bash -rcfile ~/.bashrc\""
How connect Postgres to localhost server using pgAdmin on Ubuntu?
It helps me:
1.
Open the file pg_hba.conf
sudo nano /etc/postgresql/9.x/main/pg_hba.conf
and change this line:
Database administrative login by Unix domain socket
local all postgres md5
to
Database administrative login by Unix domain socket
local all postgres trust
Restart the server
sudo service postgresql restart
Login into psql and set password
psql -U postgres
ALTER USER postgres with password 'new password';
- Again open the file
pg_hba.conf
and change this line:
Database administrative login by Unix domain socket
local all postgres trust
to
Database administrative login by Unix domain socket
local all postgres md5
- Restart the server
sudo service postgresql restart
It works.
Helpful links
1:
PostgreSQL (from ubuntu.com)
Resize UIImage and change the size of UIImageView
I think what you want is a different content mode
. Try using UIViewContentModeScaleToFill
. This will scale the content to fit the size of ur UIImageView by changing the aspect ratio of the content if necessary.
Have a look to the content mode
section on the official doc to get a better idea of the different content mode available (it is illustrated with images).
Select 50 items from list at random to write to file
If the list is in random order, you can just take the first 50.
Otherwise, use
import random
random.sample(the_list, 50)
random.sample
help text:
sample(self, population, k) method of random.Random instance
Chooses k unique random elements from a population sequence.
Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).
Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample.
To choose a sample in a range of integers, use xrange as an argument.
This is especially fast and space efficient for sampling from a
large population: sample(xrange(10000000), 60)
How do I define and use an ENUM in Objective-C?
Your typedef
needs to be in the header file (or some other file that's #import
ed into your header), because otherwise the compiler won't know what size to make the PlayerState
ivar. Other than that, it looks ok to me.
Getting a directory name from a filename
In C++17 there exists a class std::filesystem::path
using the method parent_path
.
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
for(fs::path p : {"/var/tmp/example.txt", "/", "/var/tmp/."})
std::cout << "The parent path of " << p
<< " is " << p.parent_path() << '\n';
}
Possible output:
The parent path of "/var/tmp/example.txt" is "/var/tmp"
The parent path of "/" is ""
The parent path of "/var/tmp/." is "/var/tmp"
mySQL select IN range
You can't, but you can use BETWEEN
SELECT job FROM mytable WHERE id BETWEEN 10 AND 15
Note that BETWEEN
is inclusive, and will include items with both id 10 and 15.
If you do not want inclusion, you'll have to fall back to using the >
and <
operators.
SELECT job FROM mytable WHERE id > 10 AND id < 15
Why doesn't indexOf work on an array IE8?
The problem
IE<=8 simply doesn't have an indexOf()
method for arrays.
The solution
If you need indexOf
in IE<=8, you should consider using the following polyfill, which is recommended at the MDN :
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
var len = o.length >>> 0;
if (len === 0) {
return -1;
}
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
if (n >= len) {
return -1;
}
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in o && o[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
Minified :
Array.prototype.indexOf||(Array.prototype.indexOf=function(r,t){var n;if(null==this)throw new TypeError('"this" is null or not defined');var e=Object(this),i=e.length>>>0;if(0===i)return-1;var a=+t||0;if(Math.abs(a)===1/0&&(a=0),a>=i)return-1;for(n=Math.max(a>=0?a:i-Math.abs(a),0);i>n;){if(n in e&&e[n]===r)return n;n++}return-1});
PowerShell try/catch/finally
-ErrorAction Stop
is changing things for you. Try adding this and see what you get:
Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception"
$error[0]
}
How to select a single field for all documents in a MongoDB collection?
Use the Query like this in the shell:
1. Use database_name
e.g: use database_name
2. Which returns only assets particular field information when matched , _id:0
specifies not to display ID in the result
db.collection_name.find( { "Search_Field": "value" },
{ "Field_to_display": 1,_id:0 } )
Update div with jQuery ajax response html
You are setting the html of #showresults
of whatever data
is, and then replacing it with itself, which doesn't make much sense ?
I'm guessing you where really trying to find #showresults
in the returned data, and then update the #showresults
element in the DOM with the html from the one from the ajax call :
$('#submitform').click(function () {
$.ajax({
url: "getinfo.asp",
data: {
txtsearch: $('#appendedInputButton').val()
},
type: "GET",
dataType: "html",
success: function (data) {
var result = $('<div />').append(data).find('#showresults').html();
$('#showresults').html(result);
},
error: function (xhr, status) {
alert("Sorry, there was a problem!");
},
complete: function (xhr, status) {
//$('#showresults').slideDown('slow')
}
});
});
What are the performance characteristics of sqlite with very large database files?
We are using DBS of 50 GB+ on our platform. no complains works great.
Make sure you are doing everything right! Are you using predefined statements ?
*SQLITE 3.7.3
- Transactions
- Pre made statements
Apply these settings (right after you create the DB)
PRAGMA main.page_size = 4096;
PRAGMA main.cache_size=10000;
PRAGMA main.locking_mode=EXCLUSIVE;
PRAGMA main.synchronous=NORMAL;
PRAGMA main.journal_mode=WAL;
PRAGMA main.cache_size=5000;
Hope this will help others, works great here
IE7 Z-Index Layering Issues
I solved it by using the developer tools for IE7 (its a toolbar) and adding a negative z-index to the container of the div that will be below that the other div.
Error while inserting date - Incorrect date value:
This is the date format:
The DATE type is used for values with a date part but no time part.
MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The
supported range is '1000-01-01' to '9999-12-31'.
Why do you insert '07-25-2012' format when MySQL format is '2012-07-25'?. Actually you get this error if the sql_mode is traditional/strict mode
else it just enters 0000-00-00 and gives a warning: 1265 - Data truncated for column 'col1' at row 1
.
Webdriver and proxy server for firefox
The WebDriver API has been changed. The current snippet for setting the proxy is
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.http", "localhost");
profile.setPreference("network.proxy.http_port", "3128");
WebDriver driver = new FirefoxDriver(profile);
VBA Check if variable is empty
I had a similar issue with an integer that could be legitimately assigned 0 in Access VBA. None of the above solutions worked for me.
At first I just used a boolean var and IF statement:
Dim i as integer, bol as boolean
If bol = false then
i = ValueIWantToAssign
bol = True
End If
In my case, my integer variable assignment was within a for loop and another IF statement, so I ended up using "Exit For" instead as it was more concise.
Like so:
Dim i as integer
ForLoopStart
If ConditionIsMet Then
i = ValueIWantToAssign
Exit For
End If
ForLoopEnd
What's a simple way to get a text input popup dialog box on an iPhone
To make sure you get the call backs after the user enters text, set the delegate inside the configuration handler. textField.delegate = self
Swift 3 & 4 (iOS 10 - 11):
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
alert.addTextField(configurationHandler: {(textField: UITextField!) in
textField.placeholder = "Enter text:"
textField.isSecureTextEntry = true // for password input
})
self.present(alert, animated: true, completion: nil)
In Swift (iOS 8-10):
override func viewDidAppear(animated: Bool) {
var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
textField.placeholder = "Enter text:"
textField.secureTextEntry = true
})
self.presentViewController(alert, animated: true, completion: nil)
}
In Objective-C (iOS 8):
- (void) viewDidLoad
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"Click" style:UIAlertActionStyleDefault handler:nil]];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"Enter text:";
textField.secureTextEntry = YES;
}];
[self presentViewController:alert animated:YES completion:nil];
}
FOR iOS 5-7:
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"INPUT BELOW" delegate:self cancelButtonTitle:@"Hide" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
NOTE: Below doesn't work with iOS 7 (iOS 4 - 6 Works)
Just to add another version.
- (void)viewDidLoad{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Preset Saving..." message:@"Describe the Preset\n\n\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
UITextField *textField = [[UITextField alloc] init];
[textField setBackgroundColor:[UIColor whiteColor]];
textField.delegate = self;
textField.borderStyle = UITextBorderStyleLine;
textField.frame = CGRectMake(15, 75, 255, 30);
textField.placeholder = @"Preset Name";
textField.keyboardAppearance = UIKeyboardAppearanceAlert;
[textField becomeFirstResponder];
[alert addSubview:textField];
}
then I call [alert show];
when I want it.
The method that goes along
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
NSString* detailString = textField.text;
NSLog(@"String is: %@", detailString); //Put it on the debugger
if ([textField.text length] <= 0 || buttonIndex == 0){
return; //If cancel or 0 length string the string doesn't matter
}
if (buttonIndex == 1) {
...
}
}
How to count certain elements in array?
Really, why would you need map
or filter
for this?
reduce
was "born" for these kind of operations:
[1, 2, 3, 5, 2, 8, 9, 2].reduce( (count,2)=>count+(item==val), 0);
that's it! (if item==val
in each iteration, then 1 will be added to the accumulator count
, as true
will resolve to 1
).
As a function:
function countInArray(arr, val) {
return arr.reduce((count,item)=>count+(item==val),0)
}
Or, go ahead and extend your arrays:
Array.prototype.count = function(val) {
return this.reduce((count,item)=>count+(item==val),0)
}
What is /dev/null 2>&1?
Let me explain a bit by bit.
0,1,2
0: standard input
1: standard output
2: standard error
>>
>>
in command >> /dev/null 2>&1
appends the command output to /dev/null
.
command >> /dev/null 2>&1
- After command:
command
=> 1 output on the terminal screen
=> 2 output on the terminal screen
- After redirect:
command >> /dev/null
=> 1 output to /dev/null
=> 2 output on the terminal screen
- After
/dev/null 2>&1
command >> /dev/null 2>&1
=> 1 output to /dev/null
=> 2 output is redirected to 1 which is now to /dev/null
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
How do I remove the old history from a git repository?
Just create a graft of the parent of your new root commit to no parent (or to an empty commit, e.g. the real root commit of your repository). E.g. echo "<NEW-ROOT-SHA1>" > .git/info/grafts
After creating the graft, it takes effect right away; you should be able to look at git log
and see that the unwanted old commits have gone away:
$ echo 4a46bc886318679d8b15e05aea40b83ff6c3bd47 > .git/info/grafts
$ git log --decorate | tail --lines=11
commit cb3da2d4d8c3378919844b29e815bfd5fdc0210c
Author: Your Name <[email protected]>
Date: Fri May 24 14:04:10 2013 +0200
Another message
commit 4a46bc886318679d8b15e05aea40b83ff6c3bd47 (grafted)
Author: Your Name <[email protected]>
Date: Thu May 23 22:27:48 2013 +0200
Some message
If all looks as intended, you can just do a simple git filter-branch -- --all
to make it permanent.
BEWARE: after doing the filter-branch step, all commit ids will have changed, so anybody using the old repo must never merge with anyone using the new repo.
What are the differences between 'call-template' and 'apply-templates' in XSL?
xsl:apply-templates
is usually (but not necessarily) used to process all or a subset of children of the current node with all applicable templates. This supports the recursiveness of XSLT application which is matching the (possible) recursiveness of the processed XML.
xsl:call-template
on the other hand is much more like a normal function call. You execute exactly one (named) template, usually with one or more parameters.
So I use xsl:apply-templates
if I want to intercept the processing of an interesting node and (usually) inject something into the output stream. A typical (simplified) example would be
<xsl:template match="foo">
<bar>
<xsl:apply-templates/>
</bar>
</xsl:template>
whereas with xsl:call-template
I typically solve problems like adding the text of some subnodes together, transforming select nodesets into text or other nodesets and the like - anything you would write a specialized, reusable function for.
Edit:
As an additional remark to your specific question text:
<xsl:call-template name="nodes"/>
This calls a template which is named 'nodes':
<xsl:template name="nodes">...</xsl:template>
This is a different semantic than:
<xsl:apply-templates select="nodes"/>
...which applies all templates to all children of your current XML node whose name is 'nodes'.
How to access at request attributes in JSP?
Just noting this here in case anyone else has a similar issue.
If you're directing a request directly to a JSP, using Apache Tomcat web.xml configuration, then ${requestScope.attr}
doesn't seem to work, instead ${param.attr}
contains the request attribute attr
.
TypeScript or JavaScript type casting
In typescript it is possible to do an instanceof
check in an if statement and you will have access to the same variable with the Typed
properties.
So let's say MarkerSymbolInfo
has a property on it called marker
. You can do the following:
if (symbolInfo instanceof MarkerSymbol) {
// access .marker here
const marker = symbolInfo.marker
}
It's a nice little trick to get the instance of a variable using the same variable without needing to reassign it to a different variable name.
Check out these two resources for more information:
TypeScript instanceof &
JavaScript instanceof
How to compare dates in c#
If you have your dates in DateTime variables, they don't have a format.
You can use the Date
property to return a DateTime value with the time portion set to midnight. So, if you have:
DateTime dt1 = DateTime.Parse("07/12/2011");
DateTime dt2 = DateTime.Now;
if(dt1.Date > dt2.Date)
{
//It's a later date
}
else
{
//It's an earlier or equal date
}
how to query child objects in mongodb
Assuming your "states" collection is like:
{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }
The query to find states with null cities would be:
db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});
It is a common mistake to query for nulls as:
db.states.find({"cities.name" : null});
because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.
MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query
As Ponies says in a comment, you cannot mix OLAP functions with aggregate functions.
Perhaps it's easier to get the last completion date for each employee, and join that to a dataset containing the last completion date for each of the three targeted courses.
This is an untested idea that should hopefully put you down the right path:
SELECT employee_number,
course_code,
MAX(course_completion_date) AS max_date,
lcc.LAST_COURSE_COMPLETED
FROM employee_course_completion ecc
LEFT JOIN (
SELECT employee_number,
MAX(course_completion_date) AS LAST_COURSE_COMPLETED
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
) lcc
ON lcc.employee_number = ecc.employee_number
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code, lcc.LAST_COURSE_COMPLETED
Change event on select with knockout binding, how can I know if it is a real change?
I use this custom binding (based on this fiddle by RP Niemeyer, see his answer to this question), which makes sure the numeric value is properly converted from string to number (as suggested by the solution of Michael Best):
Javascript:
ko.bindingHandlers.valueAsNumber = {
init: function (element, valueAccessor, allBindingsAccessor) {
var observable = valueAccessor(),
interceptor = ko.computed({
read: function () {
var val = ko.utils.unwrapObservable(observable);
return (observable() ? observable().toString() : observable());
},
write: function (newValue) {
observable(newValue ? parseInt(newValue, 10) : newValue);
},
owner: this
});
ko.applyBindingsToNode(element, { value: interceptor });
}
};
Example HTML:
<select data-bind="valueAsNumber: level, event:{ change: $parent.permissionChanged }">
<option value="0"></option>
<option value="1">R</option>
<option value="2">RW</option>
</select>
How to reload/refresh an element(image) in jQuery
I simply do this in html:
<script>
$(document).load(function () {
d = new Date();
$('#<%= imgpreview.ClientID %>').attr('src','');
});
</script>
And reload the image in code behind like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
image.Src = "/image.jpg"; //url caming from database
}
}
How to use apply a custom drawable to RadioButton?
full solution here:
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
</RadioGroup>
selector XML
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/orange_btn_selected" android:state_checked="true"/>
<item android:drawable="@drawable/orange_btn_unselected" android:state_checked="false"/>
</selector>
Oracle - What TNS Names file am I using?
Codeslave asks "Shouldn't it always be "$ORACLE_ HOME/network/admin/tnsnames.ora"? The answer is no, it isn't. Consider these two invocations of tnsping on the same machine:
C:\Documents and Settings\me>D:\Oracle\10.2.0_DB\BIN\tnsping orcl
TNS Ping Utility for 32-bit Windows: Version 10.2.0.4.0 - Production on 09-OCT-2
008 14:30:12
Copyright (c) 1997, 2007, Oracle. All rights reserved.
Used parameter files:
D:\Oracle\10.2.0_DB\network\admin\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = xxxx
)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = ORCL)))
OK (40 msec)
C:\Documents and Settings\me>tnsping orcl
TNS Ping Utility for 32-bit Windows: Version 10.2.0.1.0 - Production on 09-OCT-2
008 14:30:21
Copyright (c) 1997, 2005, Oracle. All rights reserved.
Used parameter files:
D:\oracle\10.2.0_Client\network\admin\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)
(HOST = XXXX)(PORT = 1521))) (CONNECT_DATA = (SERVICE_NAME = ORCL)))
OK (20 msec)
C:\Documents and Settings\me>
Note the two different parameter file locations, that are dependent on which tnsping executable you're running (and perhaps where it's being run from). For tnsnames-based oracle networking, using the TNS_ADMIN variable is the only way to ensure you're getting a consistent tnsnames.ora file. (NOTE: Windows-centric answer)
Is an entity body allowed for an HTTP DELETE request?
In case anyone is running into this issue testing, No it is not universally supported.
I am currently testing with Sahi Pro and it is very apparent a http DELETE call strips any provided body data (a large list of id's to delete in bulk as per endpoint design).
I have been in contact with them several times as well as sent in three separate packages of scrips, images, logs for them to review and they still have not confirmed this. A failed patch, and a missed conference calls by their support later and I still haven't gotten a solid answer.
I am certain Sahi does not support this, and I would imagine many other tools follow suite.