Friday, February 12, 2016

R: Count occurrences in vector

If you are having a vector and you want to count frequency of individual member (in other words, occurrences of each element) then you can do as following:

use hist() function:

x <- c(1,3,2,5,4,4,2,2,4,2,4,2,4,6,4,5,2)
 
x
 [1] 1 3 2 5 4 4 2 2 4 2 4 2 4 6 4 5 2
 
hist(x)
or use summary() function:

x <- factor(x)
 
x
 [1] 1 3 2 5 4 4 2 2 4 2 4 2 4 6 4 5 2
Levels: 1 2 3 4 5 6
 
summary(x)
1 2 3 4 5 6 
1 6 1 6 2 1
 
convert vector into factor and then call summary function.
OR

if you are working with characters then hist() won't be useful as it expects numeric elements so use summary() as shown below:
 
x <- c("devharsh","trivedi","R","C#","ASP.NET","R","C#","devharsh","R")
 
x <- factor(x)
 
summary(x)
 ASP.NET       C# devharsh        R  trivedi 
       1        2        2        3        1 

5.5.1 Authentication Error in Gmail

Code for sending email using gmail in C# :

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

MailMessage mail = new MailMessage();
mail.To.Add("dummy@test.com");
mail.From = new MailAddress("dummy-sender@gmail.com");
mail.Subject = "subject";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "foo foo bar";
mail.Priority = MailPriority.High;

SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("dummy-sender@gmail.com", "gmail-password");
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Send(mail);

Error:

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

Solution:

Login to your gmail account from which you are trying to send email and then go to https://www.google.com/settings/security/lesssecureapps

Turn on access for less secure apps and error would be resolved.

Fix _CRT_SECURE_NO_WARNINGS in VC++

Error:

To disable deprecation, use _CRT_SECURE_NO_WARNINGS.

Error    1    error C4996: 'sscanf': This function or variable may be unsafe. Consider using sscanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

Error    1    error C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

Solution:


Go to Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions and add _CRT_SECURE_NO_WARNINGS in the list.

Friday, February 05, 2016

cannot coerce type 'externalptr' to vector of type 'character'

Error:

Error in as.vector(x, "character") :
  cannot coerce type 'externalptr' to vector of type 'character'


Problem Code:

con <- dbConnect(RMySQL::MySQL(), dbname = "test")

sql <-
    paste0(
      "INSERT INTO `devharsh` (`un`, `pw`, `bl`) VALUES ('",TextUN,"', '",TextPW,"', '",0,"')"
    )
  dbGetQuery(con, sql)


Solution:

sql <-
    paste0(
      "INSERT INTO `devharsh` (`un`, `pw`, `bl`) VALUES ('",TextUN$getText(),"', '",TextPW$getText(),"', '",0,"')"
    )


Note:

It was giving error because it was not getting text from textbox that we should get by getText() function.

CPU and Memory Usage in C#

using System;
using System.Management;

namespace WMISample
{
    public class MyWMIQuery
    {
        public static void Main()
        {
            try
            {
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher("root\\CIMV2",
                                                 "SELECT * FROM Win32_PerfFormattedData_Counters_ProcessorInformation WHERE NOT Name='_Total'");
                ManagementObjectSearcher searcher2 =
                    new ManagementObjectSearcher("root\\CIMV2",
                                                 "SELECT * FROM Win32_OperatingSystem");
                for(int c=0; c<15; c++)
                {
                    for (var i = searcher.Get().GetEnumerator(); i.MoveNext();)
                    {
                        string ts = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss.fffffff");
                        ManagementObject queryObj = (ManagementObject)i.Current;
                        Console.WriteLine("Core {0} running at {1} % on {2}", queryObj["Name"], queryObj["PercentProcessorTime"], ts);
                    }
                    for (var i = searcher2.Get().GetEnumerator(); i.MoveNext();)
                    {
                        ManagementObject queryObj = (ManagementObject)i.Current;
                        double free = Double.Parse(queryObj["FreePhysicalMemory"].ToString());
                        double total = Double.Parse(queryObj["TotalVisibleMemorySize"].ToString());
                        Console.WriteLine("Amount used: {0} GB", (total - free)/(1024*1024));
                        Console.WriteLine("Percentage used: {0}%", Math.Round(((total - free) / total * 100), 2));
                    }
                    Console.WriteLine();
                }
                Console.WriteLine("Press any key to continue . . . ");
                Console.ReadKey(true);
            }
            catch (ManagementException e)
            {
                Console.WriteLine("An error occurred while querying for WMI data: " + e.Message);
            }
        }
    }
}