예제 #1
0
        public static void registerUser()
        {
            RegistrationController registration = new RegistrationController();
            bool isValid = false;
            User user    = new User();

            Console.Write("Input login:"******"Login '" + login + "' is already exist");
                Console.Write("Input login:"******"Input login:"******"Input gender:");
            string ss  = Console.ReadLine();
            Sex    sex = (Sex)Enum.Parse(typeof(Sex), ss.ToString().ToUpper());

            Console.Write("Input email:");
            String email = Console.ReadLine();

            while (!registration.isValidEmail(email) && registration.isAlreadyExistEmail(email))
            {
                Console.Clear();
                Console.WriteLine("Invalid e-mail or already exist!");
                Console.WriteLine("Input login:"******"Input gender:" + sex.ToString().ToLower());
                Console.Write("Input email:");
                email = Console.ReadLine();
            }
            Console.Write("Password:"******"Invalid password!");
                Console.WriteLine("Input login:"******"Input gender:" + sex.ToString().ToLower());
                Console.WriteLine("Input email:" + email);
                Console.Write("Password:");
                password = hideCharacter();
                Console.WriteLine();
            }
            user.login            = login;
            user.sex              = sex;
            user.password         = password;
            user.email            = email;
            user.registrationTime = DateTime.Now;
            registration.registerUser(user);
        }
예제 #2
0
 private void buttonGender_Click(object sender, EventArgs e)
 {
     creatureSex         = Utils.nextSex(creatureSex);
     buttonSex.Text      = Utils.sexSymbol(creatureSex);
     checkBoxSex.Checked = true;
     tt.SetToolTip(buttonSex, "Sex: " + creatureSex.ToString());
 }
        /// <summary>
        /// First name in the dative case
        /// </summary>
        private static string FirstNameInDative(string original, Sex sex)
        {
            const char markerOfCompoundName = '-';

            original = original.Trim();

            // compound names are divided into an array and a recursive call converts each word separately
            if (original.Contains(markerOfCompoundName.ToString()))
            {
                var parts          = original.Split(markerOfCompoundName);
                var resultCompound = string.Empty;
                for (var i = 0; i < parts.Length; i++)
                {
                    resultCompound += FirstNameInDative(parts[i], sex);
                    if (i != parts.Length - 1)
                    {
                        resultCompound += markerOfCompoundName;
                    }
                }
                return(resultCompound);
            }
            switch (sex)
            {
            case Sex.Male:
                if (IsWordEndOn(original, "й"))
                {
                    return(ReplaceEnd(original, "ю"));
                }
                else if (IsWordEndOn(original, "ел"))
                {
                    return(ReplaceEnd(original, "лу"));
                }
                else if (IsWordEndOn(original, "ь"))
                {
                    return(ReplaceEnd(original, "ю"));
                }
                else if (IsWordEndOn(original, "я"))
                {
                    return(ReplaceEnd(original, "е"));
                }
                else
                {
                    return(ReplaceEnd(original, "у", 0));
                }

            case Sex.Female:
                if (IsWordEndOn(original, "ь"))
                {
                    return(ReplaceEnd(original, "и"));
                }
                else
                {
                    return(ReplaceEnd(original, "е"));
                }

            default:
                throw new ApplicationException(sex.ToString());
            }
        }
예제 #4
0
파일: Person.cs 프로젝트: sundersb/invox
        public void Write(Lib.XmlExporter xml, Data.IInvoice pool, OrderSection section)
        {
            xml.Writer.WriteStartElement("PERS");

            xml.WriteIfValid("ID_PAC", ID);
            xml.WriteIfValid("FAM", Family);
            xml.WriteIfValid("IM", Name);
            xml.WriteIfValid("OT", Patronymic);
            xml.Writer.WriteElementString("W", Sex.ToString());
            xml.Writer.WriteElementString("DR", BirthDate.AsXml());

            WritePersonIdentityError(xml);

            if (section == OrderSection.D3)
            {
                xml.WriteIfValid("TEL", Phone);
            }

            if (Representative != null)
            {
                Representative.Write(xml, pool);
            }

            // FOMS
            //xml.WriteIfValid("MR", Address);
            xml.WriteIfValid("MR", BirthPlace);

            xml.WriteIfValid("DOCTYPE", DocumentType);

#if FOMS
            xml.WriteIfValid("SOC", SocialPosition);
#endif

            xml.WriteIfValid("DOCSER", DocumentSerial);
            xml.WriteIfValid("DOCNUM", DocumentNumber);
#if FOMS
            if (DocumentDate.HasValue)
            {
                xml.Writer.WriteElementString("DOCDATE", DocumentDate.Value.AsXml());
            }
            xml.WriteIfValid("DOCORG", DocumentOrganization);
#endif

            xml.WriteIfValid("SNILS", Snils);
#if FOMS
            xml.Writer.WriteElementString("OKATOG", ResidenceOkato);
#else
            xml.WriteIfValid("OKATOG", ResidenceOkato);
#endif
            xml.WriteIfValid("OKATOP", PresenceOkato);

#if FOMS
            xml.WriteIfValid("KT", SocialFavour);
#endif

            xml.WriteIfValid("COMENTP", Comment);

            xml.Writer.WriteEndElement();
        }
예제 #5
0
        public void GeneratePDF()
        {
            Object lockObject;

            lock (LockingIds)
            {
                if (!LockingIds.TryGetValue(ID, out lockObject))
                {
                    lockObject     = "";
                    LockingIds[ID] = lockObject;
                }
            }
            try
            {
                lock (lockObject)
                {
                    string pdfPath = PDFPath;
                    if (File.Exists(pdfPath))
                    {
                        return;
                    }

                    DirectoryInfo di = new DirectoryInfo(Path.GetDirectoryName(pdfPath));
                    if (!di.Exists)
                    {
                        di.Create();
                    }

                    using (FileStream fs = new FileStream(pdfPath, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        Document document = new Document();
                        try
                        {
                            PdfWriter writer = PdfWriter.GetInstance(document, fs);
                            document.Open();
                            document.Add(new Paragraph(string.Format("ID : {0}", ID)));
                            document.Add(new Paragraph(string.Format("Name : {0}", Name)));
                            document.Add(new Paragraph(string.Format("Age : {0} years", Age)));
                            document.Add(new Paragraph(string.Format("Sex : {0}", Sex.ToString())));
                            document.Add(new Paragraph(string.Format("Height : {0} cms", Height)));
                            document.Add(new Paragraph(string.Format("Weight: {0} kgs", Weight)));
                            document.Add(new Paragraph(string.Format("Nationality : {0}", Nationality)));
                        }
                        finally
                        {
                            document.Close();
                        }
                    }
                }
            }
            finally
            {
                lock (LockingIds)
                {
                    LockingIds.Remove(ID);//Todo : must only be deleted by last caller, else the locking algorithm will break.
                }
            }
        }
예제 #6
0
파일: Person.cs 프로젝트: sundersb/invox
        public void Write(XmlExporter xml, Data.IInvoice pool)
        {
            xml.WriteIfValid("FAM_P", Family);
            xml.WriteIfValid("IM_P", Name);
            xml.WriteIfValid("OT_P", Patronymic);
            xml.Writer.WriteElementString("W_P", Sex.ToString());
            xml.Writer.WriteElementString("DR_P", BirthDate.AsXml());

            WritePersonIdentityError(xml);
        }
예제 #7
0
 public override int GetHashCode()
 {
     string[] KeyFields = new string[] {
         Name ?? "null",
         StartYear.ToString(),
         EndYear ?? "null",
         Sex.ToString()
     };
     return(KeyFields.GetHashCode());
 }
예제 #8
0
 public Employee(string employeeId, string employeeName, int age, DateTime entryDate, Sex sex, Department department, int salary, IEnumerable <string> hobby)
 {
     this.EmployeeId   = employeeId;
     this.EmployeeName = employeeName;
     this.Age          = age;
     this.EntryDate    = entryDate;
     this.Sex          = sex.ToString();
     this.Department   = department.ToString();
     this.Salary       = salary;
     this.Hobby        = hobby;
 }
예제 #9
0
        public BoundryHelper(Sex sex)
        {
            // 取得欄位
            var field = typeof(Sex).GetField(sex.ToString());

            // 取得該欄位指定屬性
            var attribute = Attribute.GetCustomAttribute(field, typeof(SexBoundaryAttribute));

            Min = ((SexBoundaryAttribute)attribute).Min;
            Max = ((SexBoundaryAttribute)attribute).Max;
        }
예제 #10
0
        /// <summary>
        /// Возвращает пол сотрудника на русском языке
        /// </summary>
        /// <param name="sex">Перечисление пола сотрудника</param>
        /// <returns></returns>
        public static string GetSexResource(Sex sex)
        {
            var type       = sex.GetType();
            var memberInfo = type.GetMember(sex.ToString());

            //Проверяем существует ли такой элемент в перечислении
            if (memberInfo == null || memberInfo.Length <= 0)
            {
                return(sex.ToString());
            }

            var attributes = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

            //Проверяем существует ли атрибут описания
            if (attributes == null || attributes.Length <= 0)
            {
                return(sex.ToString());
            }

            return(((DescriptionAttribute)attributes[0]).Description);
        }
예제 #11
0
        public virtual Dictionary <string, string> ToRow()
        {
            var user = new Dictionary <string, string>();

            user.Add("Id", Id.ToString());
            user.Add("First name", FirstName);
            user.Add("Last name", LastName);
            user.Add("Email", Email);
            user.Add("Sex", Sex.ToString());
            user.Add("Date of birth", DateOfBirth.ToShortDateString());

            return(user);
        }
예제 #12
0
        public void Show()
        {
            Console.WriteLine($@"
Name           - {Name}
Surname        - {Surname}
Age            - {Age}
Category       - {Category.ToString()}
City           - {City.ToString()}
Sex            - {Sex.ToString()}
Education      - {Education.ToString()}
Experience     - {Experience.ToString()}
Minimum Salary - {MinSalarey}
Phone Number   - {pNumber}");
        }
        /// <summary>
        /// Middle name in the dative case
        /// </summary>
        private static string MiddleNameInDative(string original, Sex sex)
        {
            original = original.Trim();
            switch (sex)
            {
            case Sex.Male:
                return(ReplaceEnd(original, "у", 0));

            case Sex.Female:
                return(ReplaceEnd(original, "е"));

            default:
                throw new ApplicationException(sex.ToString());
            }
        }
예제 #14
0
        public void hienthi()
        {
            listView4.Items.Clear();
            DataTable dtb = DNV.Load_NV();

            i = 0;
            foreach (DataRow row in dtb.Rows)
            {
                if (row[2].ToString() == "1")
                {
                    Sex = "Nam";
                }
                else if (row[2].ToString() == "2")
                {
                    Sex = "Nữ";
                }
                else
                {
                    Sex = "Khác";
                }

                if (row[6].ToString() == "1")
                {
                    PhongBan = "Quản lý";
                }
                else if (row[6].ToString() == "2")
                {
                    PhongBan = "Kỹ Thuật";
                }
                else
                {
                    PhongBan = "Kế Toán";
                }

                var date = DateTime.Parse(row[3].ToString());

                listView4.Items.Add((i + 1).ToString());
                listView4.Items[i].SubItems.Add(row[0].ToString());
                listView4.Items[i].SubItems.Add(row[1].ToString());
                listView4.Items[i].SubItems.Add(Sex.ToString());
                listView4.Items[i].SubItems.Add(date.ToString("dd/MM/yyyy"));
                listView4.Items[i].SubItems.Add(row[4].ToString());
                listView4.Items[i].SubItems.Add(row[5].ToString());
                listView4.Items[i].SubItems.Add(PhongBan.ToString());
                listView4.Items[i].SubItems.Add(row[7].ToString());
                i++;
            }
        }
예제 #15
0
        public static void Demo7()
        {
            Sex sex = Sex.Female;

            // 将一个字符串转换成枚举
            Sexs sex1 = (Sexs)Enum.Parse(typeof(Sexs), "男");

            Console.WriteLine(sex1);
            Console.ReadKey();

            // 枚举转字符串
            string sex2 = sex.ToString();

            Console.WriteLine(sex2);
            Console.ReadKey();
        }
예제 #16
0
        public JSONWrappers.SubjectInfo ToJSON()
        {
            JSONWrappers.SubjectInfo jsonInfo = new JSONWrappers.SubjectInfo
            {
                FirstName  = FirstName,
                LastName   = LastName,
                Patronymic = Patronymic,
                Address    = Address,
                Job        = Job,
                Diseases   = Diseases,
                Phone      = Phone,
                Sex        = Sex.ToString("G"),
                BirthDate  = BirthDate.ToString("dd.MM.yyyy")
            };

            return(jsonInfo);
        }
 public override bool IsContains(string text)
 {
     text = text.ToUpper();
     if (SubordinateTeachers.ToString().Contains(text) ||
         TextbooksPublished.ToString().Contains(text) ||
         AmountOfGrantsReceived.ToString().Contains(text) ||
         Name.ToUpper().Contains(text) ||
         Age.ToString().Contains(text) ||
         Sex.ToString().Contains(text))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
예제 #18
0
 public override bool IsContains(string text)
 {
     text = text.ToUpper();
     if (WorkExperience.ToString().Contains(text) ||
         ScientificPapersCount.ToString().Contains(text) ||
         EducatesStudents.ToString().Contains(text) ||
         Name.ToUpper().Contains(text) ||
         Age.ToString().Contains(text) ||
         Sex.ToString().Contains(text))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
예제 #19
0
 public override bool IsContains(string text)
 {
     text = text.ToUpper();
     if (AverageRating.ToString().Contains(text) ||
         CourseNumber.ToString().Contains(text) ||
         Commerce.ToString().Contains(text) ||
         Name.ToUpper().Contains(text) ||
         Age.ToString().Contains(text) ||
         Sex.ToString().Contains(text))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
예제 #20
0
      private void FilterPossibleNameListsBySex(IEnumerable <string> nameFiles, Sex sex)
      {
          _firstNames = new List <string>();
          _lastNames  = new List <string>();

          foreach (var nameFile in nameFiles)
          {
              if (nameFile.Contains(sex.ToString().ToLower()))
              {
                  _firstNames.AddRange(_nameFiles[nameFile].text.Split("\r\n"[0]).ToList());
              }
              if (nameFile.Contains("last"))
              {
                  _lastNames.AddRange(_nameFiles[nameFile].text.Split("\r\n"[0]).ToList());
              }
          }
      }
예제 #21
0
        static void Main(string[] args)
        {
            Sex sex1 = Sex.Man;
            Sex sex2 = Sex.WoMan;

            //获取枚举的value
            Console.WriteLine((int)sex1); //0
            Console.WriteLine((int)sex2); //1

            //获取枚举的name (下面三种方式都可以)
            Console.WriteLine(sex1.ToString());                    //Man
            Console.WriteLine(Enum.GetName(typeof(Sex), sex1));    //Man
            Console.WriteLine(Enum.GetName(sex2.GetType(), sex2)); //WoMan

            //枚举中一般使用Description特性值用于页面显
            Console.WriteLine(sex1.GetDescription());
            Console.ReadLine();
        }
예제 #22
0
        public void Conditions_IsMet_NamedCharacterSexCondition(Sex sex)
        {
            var storyWithForestGuardian = new Story();
            var forestGuardian          = new Character
            {
                Sex = sex
            };

            storyWithForestGuardian.Characters.Add(forestGuardian);
            const string tag = "forestguardian";

            storyWithForestGuardian.NamedCharacters.Add(tag, forestGuardian);
            string forestGuardianSexCondition = $"character:{tag}:{sex.ToString().ToLower()}";

            bool storyHasForestGuardianWithMatchingSex = Condition.IsMet(storyWithForestGuardian, forestGuardianSexCondition);

            Assert.IsTrue(storyHasForestGuardianWithMatchingSex);
        }
    protected void txt_IDCode_TextChanged(object sender, EventArgs e)
    {
        DateTime     BirthDay; int Sex;
        TextBox      txt_birthday = UC_DetailView1.FindControl("PM_Promotor_Birthday") != null ? (TextBox)UC_DetailView1.FindControl("PM_Promotor_Birthday") : null;
        DropDownList ddl_sex      = UC_DetailView1.FindControl("PM_Promotor_Sex") != null ? (DropDownList)UC_DetailView1.FindControl("PM_Promotor_Sex") : null;

        if (Tools.DoVerifyIDCode(((TextBox)sender).Text, out BirthDay, out Sex) && ((TextBox)sender).Text.Trim().Length == 18)
        {
            if (txt_birthday != null)
            {
                txt_birthday.Text = BirthDay.ToString("yyyy-MM-dd");
            }
            if (ddl_sex != null)
            {
                ddl_sex.SelectedValue = Sex.ToString();
            }


            if (DateTime.Now < BirthDay.AddYears(16) || DateTime.Now > BirthDay.AddYears(50))
            {
                int year = DateTime.Now.Year - BirthDay.Year;
                if (BirthDay.AddYears(year) > DateTime.Now)
                {
                    year++;
                }
                MessageBox.Show(this, "对不起,该导购年龄不符合规则(16~49岁),该人员年龄:" + year);
                return;
            }
        }
        else
        {
            MessageBox.Show(this, "身份证号码错误!");
            ((TextBox)sender).Text = "";
            if (txt_birthday != null)
            {
                txt_birthday.Text = "";
            }
            if (ddl_sex != null)
            {
                ddl_sex.SelectedValue = "0";
            }
            return;
        }
    }
예제 #24
0
        public Record GetRecord()
        {
            if (!GuiTools.HasBlankControls(this, typeof(TextBox)))
            {
                var r = new Record
                {
                    _firstname = FirstName,
                    _lastname  = LastName,
                    _sex       = Sex.ToString(),
                    _age       = new Age(BirthDate).Years
                };

                return(r);
            }
            else
            {
                MessageBox.Show(@"Please fill the necessary informations.Thanks");
            }
            return(null);
        }
예제 #25
0
        public override void DoTest()
        {
            //获取枚举字符串
            Sex time = Sex.Man;

            #region 枚举转化
            string strA   = "Man";
            Sex    myEnum = (Sex)Enum.Parse(typeof(Sex), strA); //字符串转换为枚举

            int i = Convert.ToInt32(Sex.Man);                   //获取枚举的值

            Sex sex = (Sex)i;                                   //整数转换为枚举值
            #endregion

            Console.WriteLine(time.ToString());//输出:Man
            Console.WriteLine("-------------------------------");
            //Enum.Parse()方法。
            Sex time2 = (Sex)Enum.Parse(typeof(Sex), "Man", true);
            Console.WriteLine((int)time2);//输出:1
            Console.WriteLine("-------------------------------");

            #region 得到枚举的某一值对应的名称
            //两种方法都能实现,但是当其值越界(不是枚举所列出的值),就有一定的区别了。大家可以根据自己的需求不同,选择合适的方法。
            Console.WriteLine(((Sex)1).ToString());          //输出:Man,如果越界返回原值
            Console.WriteLine(Enum.GetName(typeof(Sex), 1)); //输出:Man,如果越界返回空字符串
            #endregion
            Console.WriteLine("-------------------------------");
            //枚举所有的名称
            foreach (string temp in Enum.GetNames(typeof(Sex)))
            {
                Console.WriteLine(temp.ToString()); //Man Women Seek
            }
            //得到枚举的所有的值
            foreach (var item in Enum.GetValues(typeof(Sex)))
            {
                Console.WriteLine(item.ToString()); //Man Women Seek
            }
            Console.WriteLine("-------------------------------");
            //Sex.Man.
            Console.ReadKey();
        }
예제 #26
0
    /// <summary>
    /// Erstellt eine <see cref="string"/>-Repräsentation des <see cref="Gender"/>-Objekts.
    /// (Nur zum Debugging.)
    /// </summary>
    /// <returns>Eine <see cref="string"/>-Repräsentation des <see cref="Gender"/>-Objekts.</returns>
    public override string ToString()
    {
        string s = "";

        if (Sex.HasValue)
        {
            s += Sex.ToString();
        }

        if (GenderIdentity != null)
        {
            if (s.Length != 0)
            {
                s += "; ";
            }

            s += GenderIdentity;
        }

        return(s);
    }
예제 #27
0
        static void Main(string[] args)
        {
            int a = (int)Sex.女;

            Console.WriteLine("将枚举转换为整数:" + a);

            string b = Sex.女.ToString();

            Console.WriteLine("将枚举转换为字符串:" + b);

            Sex c = (Sex)Enum.Parse(typeof(Sex), "女");

            Console.WriteLine("将字符串转换为枚举:" + c.ToString());

            Sex c1 = (Sex)Enum.Parse(typeof(Sex), "女");

            Console.WriteLine("将字符串转换为枚举:" + (int)c1);

            Sex d = (Sex)1;

            Console.WriteLine("将整数转换为枚举:" + d.ToString());

            string s = Enum.GetName(typeof(Sex), 1);

            Console.WriteLine("Enum.GetName方法:(参数 1)" + s);

            foreach (Sex sex in Enum.GetValues(typeof(Sex)))
            {
                Console.WriteLine("循环枚举value " + sex.ToString() + "=" + (int)sex);
            }

            foreach (var sex in Enum.GetNames(typeof(Sex)))
            {
                Console.WriteLine("循环枚举name " + sex);
            }

            var str = Enum.Format(typeof(Sex), 0, "d");

            Console.WriteLine(str);

            str = Enum.GetUnderlyingType(typeof(Sex)).ToString();
            Console.WriteLine(str);

            //判断 名称或者value 是否存在于枚举中
            var isornot = Enum.IsDefined(typeof(Sex), "Green");

            Console.WriteLine(isornot);

            var enm = Enum.Parse(typeof(Sex), "1");

            Console.WriteLine(enm);

            var str1 = Enum.ToObject(typeof(Sex), 2);

            Console.WriteLine(str1);

            int intVa = (int)Sex.男;

            Console.WriteLine(intVa);

            var intVa2 = Sex.女.ToString("D");

            Console.WriteLine(intVa2);

            Console.ReadKey();
        }
예제 #28
0
        // todo not used, remove?
        //private static Rectangle letterRect(Bitmap source, int hStart, int hEnd)
        //{
        //    int startWhite = -1, endWhite = -1;
        //    for (int j = 0; j < source.Height; j++)
        //    {
        //        for (int i = hStart; i < hEnd; i++)
        //        {
        //            if (startWhite == -1 && source.GetPixel(i, j).R == 255)
        //            {
        //                startWhite = j;
        //            }

        //            if (endWhite == -1 && source.GetPixel(i, (source.Height - j) - 1).R == 255)
        //            {
        //                endWhite = (source.Height - j);
        //            }
        //            if (startWhite != -1 && endWhite != -1)
        //                return new Rectangle(hStart, startWhite, hEnd - hStart, endWhite - startWhite);
        //        }
        //    }


        //    return Rectangle.Empty;
        //}

        public double[] DoOcr(out string OCRText, out string dinoName, out string species, out string ownerName, out string tribeName, out Sex sex, string useImageFilePath = "", bool changeForegroundWindow = true)
        {
            string finishedText = "";

            dinoName  = "";
            species   = "";
            ownerName = "";
            tribeName = "";
            sex       = Sex.Unknown;
            double[] finalValues = new double[1] {
                0
            };
            if (ocrConfig == null)
            {
                OCRText = "Error: no ocr configured";
                return(finalValues);
            }

            Bitmap screenshotbmp;

            _ocrControl.debugPanel.Controls.Clear();
            _ocrControl.ClearLists();

            if (System.IO.File.Exists(useImageFilePath))
            {
                screenshotbmp = (Bitmap)Image.FromFile(useImageFilePath);
            }
            else
            {
                // grab screenshot from ark
                screenshotbmp = Win32API.GetScreenshotOfProcess(screenCaptureApplicationName, waitBeforeScreenCapture, true);
            }
            if (screenshotbmp == null)
            {
                OCRText = "Error: no image for OCR. Is ARK running?";
                return(finalValues);
            }

            if (!CheckResolutionSupportedByOcr(screenshotbmp))
            {
                OCRText = "Error while calibrating: The game-resolution is not supported by the currently loaded OCR-configuration.\n"
                          + $"The tested image has a resolution of {screenshotbmp.Width.ToString()} × {screenshotbmp.Height.ToString()} px,\n"
                          + $"the resolution of the loaded ocr-config is {ocrConfig.resolutionWidth} × {ocrConfig.resolutionHeight} px.\n\n"
                          + "Load a ocr-config file with the resolution of the game to make it work.";
                return(finalValues);
            }

            // TODO resize image according to resize-factor. used for large screenshots
            if (ocrConfig.resize != 1 && ocrConfig.resize > 0)
            {
                Bitmap resized = new Bitmap((int)(ocrConfig.resize * ocrConfig.resolutionWidth), (int)(ocrConfig.resize * ocrConfig.resolutionHeight));
                using (var graphics = Graphics.FromImage(resized))
                {
                    graphics.CompositingMode    = CompositingMode.SourceCopy;
                    graphics.CompositingQuality = CompositingQuality.HighQuality;
                    graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                    graphics.SmoothingMode      = SmoothingMode.HighQuality;
                    graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;

                    using (var wrapMode = new ImageAttributes())
                    {
                        wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                        graphics.DrawImage(screenshotbmp, new Rectangle(0, 0, 1920, 1080), 0, 0, screenshotbmp.Width, screenshotbmp.Height, GraphicsUnit.Pixel, wrapMode);
                    }

                    screenshotbmp?.Dispose();
                    screenshotbmp = resized;
                }
            }

            if (enableOutput && _ocrControl != null)
            {
                _ocrControl.AddBitmapToDebug(screenshotbmp);
                _ocrControl.SetScreenshot(screenshotbmp);
            }

            finalValues    = new double[ocrConfig.labelRectangles.Count];
            finalValues[8] = -1; // set imprinting to -1 to mark it as unknown and to set a difference to a creature with 0% imprinting.

            if (changeForegroundWindow)
            {
                Win32API.SetForegroundWindow(Application.OpenForms[0].Handle);
            }


            bool wild = false; // todo: set to true and find out if the creature is wild in the first loop
            int  stI  = -1;

            for (int lbI = 0; lbI < ocrConfig.labelNames.Count; lbI++)
            {
                stI++;
                if (lbI == 8)
                {
                    stI = 8;
                }
                string statName = ocrConfig.labelNames[stI];

                Rectangle rec = ocrConfig.labelRectangles[lbI];

                // wild creatures don't have the xp-bar, all stats are moved one row up
                if (wild && stI < 9)
                {
                    rec.Offset(0, ocrConfig.labelRectangles[0].Top - ocrConfig.labelRectangles[1].Top);
                }

                Bitmap testbmp = SubImage(screenshotbmp, rec.X, rec.Y, rec.Width, rec.Height);
                //AddBitmapToDebug(testbmp);

                string statOCR = "";

                if (statName == "NameSpecies")
                {
                    statOCR = readImage(testbmp, true, false);
                }
                else if (statName == "Level")
                {
                    statOCR = readImage(testbmp, true, true);
                }
                else if (statName == "Tribe" || statName == "Owner")
                {
                    statOCR = readImage(testbmp, true, false);
                }
                else
                {
                    statOCR = readImage(testbmp, true, true); // statvalues are only numbers
                }
                if (statOCR == "" &&
                    (statName == "Health" || statName == "Imprinting" || statName == "Tribe" || statName == "Owner"))
                {
                    if (wild && statName == "Health")
                    {
                        stI--;
                        wild = false;
                    }
                    continue; // these can be missing, it's fine
                }


                //_lastLetterPositions[statName] = new Point(rec.X + lastLetterPosition(removePixelsUnderThreshold(GetGreyScale(testbmp), whiteThreshold)), rec.Y); // TODO remove?

                finishedText += (finishedText.Length == 0 ? "" : "\r\n") + statName + ":\t" + statOCR;

                // parse the OCR String

                Regex r;
                r       = new Regex(@"^[_\/\\]*(.*?)[_\/\\]*$"); // trim. often the background is misinterpreted as underscores or slash/backslash
                statOCR = r.Replace(statOCR, "$1");

                if (statName == "NameSpecies")
                {
                    r = new Regex(@".*?([♂♀])?[_.,-\/\\]*([^♂♀]+?)(?:[\(\[]([^\[\(\]\)]+)[\)\]]$|$)");
                }
                else if (statName == "Owner" || statName == "Tribe")
                {
                    r = new Regex(@"(.*)");
                }
                else if (statName == "Level")
                {
                    r = new Regex(@".*\D(\d+)");
                }
                else
                {
                    r = new Regex(@"(?:[\d.,%\/]*\/)?(\d+[\.,']?\d?)(%)?"); // only the second numbers is interesting after the current weight is not shown anymore

                    //if (onlyNumbers)
                    //r = new Regex(@"((\d*[\.,']?\d?\d?)\/)?(\d*[\.,']?\d?\d?)");
                    //else
                    // r = new Regex(@"([a-zA-Z]*)[:;]((\d*[\.,']?\d?\d?)\/)?(\d*[\.,']?\d?\d?)");
                }

                MatchCollection mc = r.Matches(statOCR);

                if (mc.Count == 0)
                {
                    if (statName == "NameSpecies" || statName == "Owner" || statName == "Tribe")
                    {
                        continue;
                    }
                    //if (statName == "Torpor")
                    //{
                    //    // probably it's a wild creature
                    //    // todo
                    //}
                    //else
                    //{
                    finishedText    += "error reading stat " + statName;
                    finalValues[stI] = 0;
                    continue;
                    //}
                }

                if (statName == "NameSpecies" || statName == "Owner" || statName == "Tribe")
                {
                    if (statName == "NameSpecies" && mc[0].Groups.Count > 0)
                    {
                        if (mc[0].Groups[1].Value == "♀")
                        {
                            sex = Sex.Female;
                        }
                        else if (mc[0].Groups[1].Value == "♂")
                        {
                            sex = Sex.Male;
                        }
                        dinoName = mc[0].Groups[2].Value;
                        species  = mc[0].Groups[3].Value;
                        if (species.Length == 0)
                        {
                            species = dinoName;
                        }

                        // remove non-letter chars
                        r       = new Regex("[^a-zA-Z]");
                        species = r.Replace(species, "");
                        // replace capital I with lower l (common misrecognition)
                        r       = new Regex("(?<=[a-z])I(?=[a-z])");
                        species = r.Replace(species, "l");
                        // readd spaces before capital letters
                        r       = new Regex("(?<=[a-z])(?=[A-Z])");
                        species = r.Replace(species, " ");

                        finishedText += "\t→ " + sex.ToString() + ", " + species;
                    }
                    else if (statName == "Owner" && mc[0].Groups.Count > 0)
                    {
                        ownerName     = mc[0].Groups[0].Value;
                        finishedText += "\t→ " + ownerName;
                    }
                    else if (statName == "Tribe" && mc[0].Groups.Count > 0)
                    {
                        tribeName     = mc[0].Groups[0].Value.Replace("Tobe", "Tribe").Replace("Tdbe", "Tribe").Replace("Tribeof", "Tribe of ");
                        finishedText += "\t→ " + tribeName;
                    }
                    continue;
                }

                if (mc[0].Groups.Count > 2 && mc[0].Groups[2].Value == "%" && statName == "Weight")
                {
                    // first stat with a '%' is damage, if oxygen is missing, shift all stats by one
                    finalValues[4] = finalValues[3]; // shift food to weight
                    finalValues[3] = finalValues[2]; // shift oxygen to food
                    finalValues[2] = 0;              // set oxygen (which wasn't there) to 0
                    stI++;
                }

                double.TryParse(mc[0].Groups[1].Value.Replace('\'', '.').Replace(',', '.').Replace('O', '0'), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.GetCultureInfo("en-US"), out double v); // common substitutions: comma and apostrophe to dot,

                finishedText += $"\t→ {v}";

                // TODO: test here that the read stat name corresponds to the stat supposed to be read
                finalValues[stI] = v;
            }

            OCRText = finishedText;

            // TODO reorder stats to match 12-stats-order

            return(finalValues);

            /*
             * Bitmap grab = Win32Stuff.GetSreenshotOfProcess(screenCaptureApplicationName);
             * AddBitmapToDebug(grab);
             *
             * //grab.Save("E:\\Temp\\Calibration8.png", ImageFormat.Png);
             * if (changeForegroundWindow)
             *  Win32Stuff.SetForegroundWindow(Application.OpenForms[0].Handle);
             */
        }
 public static void SetSex(Sex sex)
 {
     UserPreferences.SetString("sex", sex.ToString());
 }
예제 #30
0
 public void SetSex(Sex newSex)
 {
     Sex = newSex.ToString("G");
 }
예제 #31
0
        public async Task <IActionResult> GetClient(string du, Sex sex, [FromBody] MapOptions mapOptions)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var cuix = String.Empty;

            try
            {
                cuix = await _clientServices.GetCuix(du, sex.ToString());

                _logger.LogInformation("Cuix OK.");
            }
            catch (Exception e)
            {
                _logger.LogError(e.ToString());
                return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError, "Error getting CUIX"));
            }

            try
            {
                var dataPadron = await _clientServices.GetClientAfip(cuix);

                _logger.LogInformation("Afip services OK.");

                if (dataPadron == null)
                {
                    return(NotFound());
                }


                await _clientServices.GetClientNV(dataPadron);

                if (!String.IsNullOrEmpty(dataPadron.HostId))
                {
                    var addressNV = await _clientServices.GetAddressNV(dataPadron.HostId);

                    dataPadron.Addresses.Add(addressNV);
                }

                try
                {
                    var normalizedAddresses = new List <Address>();

                    foreach (var item in dataPadron.Addresses)
                    {
                        mapOptions.Address = item;

                        var result = await _clientServices.NormalizeAddress(mapOptions);

                        if (result != null)
                        {
                            normalizedAddresses.Add(result);
                            _logger.LogInformation("Normalize Address OK.");
                        }
                        else
                        {
                            _logger.LogInformation("Address not found.");
                        }
                    }

                    if (normalizedAddresses.Count > 0)
                    {
                        dataPadron.Addresses = normalizedAddresses;
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError(e.ToString());
                    _logger.LogTrace("Error normalizing address.");
                }

                return(new ObjectResult(dataPadron));
            }
            catch (Exception e)
            {
                _logger.LogError(e.ToString());
                return(StatusCode((int)System.Net.HttpStatusCode.InternalServerError, "Error al consultar los datos padron."));
            }
        }
예제 #32
0
 protected Animal(string nameInput, byte ageInput, Sex inputSex)
 {
     name = nameInput;
     Age = ageInput;
     sex = inputSex.ToString();
 }