示例#1
0
        /// <summary>
        /// crée une liste de 5 patients
        /// </summary>
        /// <returns>la liste de patients</returns>
        public List<Dbo.Patient> CreateListPatient()
        {
            Observation obs = new Observation();
            List<Dbo.Patient> res = new List<Dbo.Patient>();

            Dbo.Patient patient1 = new Dbo.Patient()
            {
                Firstname = "laurence",
                Name = "marshall",
                Id = 1,
                Birthday = new DateTime(1986, 06, 30),
                Observations = obs.CreateListObservation()
            };

            Dbo.Patient patient2 = new Dbo.Patient()
            {
                Firstname = "laure",
                Name = "sagem",
                Id = 2,
                Birthday = new DateTime(1950, 06, 30),
                Observations = obs.CreateListObservation()
            };

            Dbo.Patient patient3 = new Dbo.Patient()
            {
                Firstname = "phillip",
                Name = "logy",
                Id = 3,
                Birthday = new DateTime(1970, 10, 25),
                Observations = obs.CreateListObservation()
            };

            Dbo.Patient patient4 = new Dbo.Patient()
            {
                Firstname = "sebastien",
                Name = "risette",
                Id = 4,
                Birthday = new DateTime(1965, 05, 01),
                Observations = obs.CreateListObservation()
            };

            Dbo.Patient patient5 = new Dbo.Patient()
            {
                Firstname = "thomas",
                Name = "gallente",
                Id = 5,
                Birthday = new DateTime(1932, 12, 25),
                Observations = obs.CreateListObservation()
            };

            res.Add(patient1);
            res.Add(patient2);
            res.Add(patient3);
            res.Add(patient4);
            res.Add(patient5);

            return res;
        }
示例#2
0
        public static void MergeFiles(Repository repo)
        {
            var f1 = repo.StorageWrapper.Data.MineableDataResultsDirectory + Extractor.UniqueEmailAddressesFilename;
            var f2 = repo.StorageWrapper.Data.MineableDataDirectory + Extractor.LinkedInFilename;
            var f3 = repo.StorageWrapper.Data.MineableDataDirectory + Extractor.IgnoreListFilename;

            if (!File.Exists(f1))
            {
                Console.WriteLine("Unable to locate " + f1);
                return;
            }

            if (!File.Exists(f2))
            {
                Console.WriteLine("Unable to locate " + f2);
                return;
            }

            if (!File.Exists(f3))
            {
                Console.WriteLine("Unable to locate " + f3);
                return;
            }

            var mozilla = File.ReadLines(f1).ToList();
            var linkedIn = File.ReadLines(f2).ToList();
            var ignore = File.ReadLines(f3).ToList();
            var final = new List<string>();

            foreach (var line in mozilla.Where(line => !final.Contains(line.ToLower())).Where(line => ignore.All(ignorePart => !line.ToLower().Contains(ignorePart.ToLower()))))
            {
                final.Add(line.ToLower());
            }
            foreach (var line in linkedIn.Where(line => !final.Contains(line.ToLower())).Where(line => ignore.All(ignorePart => !line.ToLower().Contains(ignorePart.ToLower()))))
            {
                final.Add(line.ToLower());
            }

            final.Sort();

            File.WriteAllLines(repo.StorageWrapper.Data.MineableDataResultsDirectory + Extractor.ConvergedEmailAddressesFilename, final);

            var domains = final.Where(x => x.Contains('@')).Select(x => x.Split('@')[1]).Distinct().ToList();

            domains.Sort();

            File.WriteAllLines(repo.StorageWrapper.Data.MineableDataResultsDirectory + Extractor.UniqueDomainsFilename, domains);

            if (UIRetriever.GetBool(String.Format("View {0}?", Extractor.ConvergedEmailAddressesFilename)))
            {
                FileVisualiser.Show(repo.StorageWrapper.Data.MineableDataResultsDirectory + Extractor.ConvergedEmailAddressesFilename);
            }

            if (UIRetriever.GetBool(String.Format("View {0}?", repo.StorageWrapper.Data.MineableDataResultsDirectory)))
            {
                DirectoryVisualiser.ShowFile(repo.StorageWrapper.Data.MineableDataResultsDirectory + Extractor.ConvergedEmailAddressesFilename);
            }
        }
        public List<SensiumResultPhrase> GetInteressingPhrases(string inputText)
        {
            List<SensiumResultPhrase> returnedPhrases = new List<SensiumResultPhrase>();

            using (var client = new WebClient())
            {
                try
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                    client.Headers[HttpRequestHeader.Accept] = "application/json";

                    string toupload = "{" +
                                        "\"apiKey\": \"c105f2f6-ca21-4ddb-ab36-480cf438b6f3\"," +
                                        "\"text\": \"" + inputText + "\"," +
                                        "\"extractors\": [ \"Summary\", \"Entities\" ]" +
                                      "}";

                    var response = client.UploadData("https://api.sensium.io/v1/extract", Encoding.UTF8.GetBytes(toupload));

                    var responseString = Encoding.UTF8.GetString(response);
                    dynamic obj = JsonConvert.DeserializeObject(responseString);

                    //keyphrases extraction here
                    foreach (var ph in obj.summary.keyPhrases)
                    {
                        if (!Utilities.Helper.SensiumResultListContainsText(returnedPhrases, ph.text.ToString()))
                        {
                            SensiumResultPhrase phrase = new SensiumResultPhrase();
                            phrase.Text = ph.text.ToString();
                            phrase.Score = Double.Parse(ph.score.ToString());
                            phrase.Type = "phrase";

                            returnedPhrases.Add(phrase);
                        }
                    }

                    //Named entity extraction here
                    foreach (var ent in obj.entities)
                    {
                        SensiumResultPhrase phrase = new SensiumResultPhrase();
                        phrase.Text = ent.normalized.ToString();
                        phrase.Score = 1;

                        returnedPhrases.Add(phrase);
                    }

                }
                catch (WebException ex)
                {
                   //s var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();

                  //  Logger.LogError(resp);

                }

                return returnedPhrases;
            }
        }
        private IEnumerable<Game> GenerateFakeCollectionOfGames()
        {
            var games = new List<Game>();
            var fakeGame = new Game(new GameField(5, 5));
            fakeGame.Id = "FakeId";

            games.Add(fakeGame);
            games.Add(new Game(new GameField(10, 10)));
            games.Add(new Game(new GameField(15, 15)));

            return games;
        }
        public void AfterImport(IList added, IList updated)
        {
            if (GlobalSettings.runAfterImport)
            {
                var activities = new List<IActivity>();

                foreach (object record in added)
                {
                    if (record is IActivity)
                    {
                        activities.Add(record as IActivity);
                    }
                }

                foreach (object record in updated)
                {
                    if (record is IActivity)
                    {
                        activities.Add(record as IActivity);
                    }
                }

                GlobalSettings.LoadSettings();

                if (GlobalSettings.calculateFutureAfterImport)
                {
                    DateTime oldestActivity = DateTime.MaxValue;

                    foreach (IActivity activity in activities)
                    {
                        if (activity.StartTime < oldestActivity)
                        {
                            oldestActivity = activity.StartTime;
                        }
                    }

                    foreach (IActivity activity in CalculatedFields.GetLogBook().Activities)
                    {
                        if (activity.StartTime >= oldestActivity)
                        {
                            if (!activities.Contains(activity))
                            {
                                activities.Add(activity);
                            }
                        }
                    }
                }

                Evaluator.Calculate(activities, null, false);
            }
        }
示例#6
0
        public Session(Timer timer, IEnumerable<string> portStrings)
        {
            List<string> textPortStrings = new List<string>();
            List<string> yarpPortStrings = new List<string>();
            List<string> rosPortStrings = new List<string>();

            foreach (string portString in portStrings)
            {
                if (portString.Length < 2) throw new InvalidOperationException("\"" + portString + "\" is not a valid port string");

                switch (portString.Substring(0, 2))
                {
                    case "t:": textPortStrings.Add(portString.Substring(2)); break;
                    case "y:": yarpPortStrings.Add(portString.Substring(2)); break;
                    case "r:": rosPortStrings.Add(portString.Substring(2)); break;
                    default: throw new InvalidOperationException("\"" + portString + "\" is not a valid port string");
                }
            }

            if (yarpPortStrings.Any()) this.yarpNetwork = new YarpNetwork();
            if (rosPortStrings.Any()) this.rosNetwork = new RosNetwork();

            List<Receiver> receivers = new List<Receiver>();
            foreach (string portString in textPortStrings)
            {
                string name = portString.Split(':').First();
                Port port = name == "-" ? new TextReaderPort() : new TextReaderPort(name);
                receivers.Add(new Receiver(port, timer, portString));
            }
            foreach (string portString in yarpPortStrings)
            {
                string name = portString.Split(':').First();
                Port port = new YarpReaderPort(name, yarpNetwork);
                receivers.Add(new Receiver(port, timer, portString));
            }
            foreach (string portString in rosPortStrings)
            {
                string name = portString.Split(':').First();
                Port port = new RosPort(name, rosNetwork);
                receivers.Add(new Receiver(port, timer, portString));
            }
            this.receivers = receivers;

            if (receivers.Count(receiver => receiver.HasTimer) > 1) throw new ArgumentException("More than one timer stream was found.");

            this.capture = new Capture
            (
                from receiver in receivers
                select new PortData(receiver.PortName, receiver.PortStreams)
            );
        }
示例#7
0
        public Logik()
        {
            Database = new DatabaseAdgang();
            DAQdata = new IndhentDAQData();
            NulpunktObjekt = new Nulpunktsjustering();
            KalibreringObjekt = new Kalibrering();
            FilterObj = new Filter();
            AnalyseKlasse = new Analyse();

            updateUI = new Thread(() => updateListe());

            UILISTE = new List<double>();
            observers = new List<IObserver>();
            FiltreretListe = new List<double>();
            databasetal = new List<double>();
            minKø = new Queue<double>(100);

            beregnetNværdi = 0.0;
            counter = 0;
            kalibreringKoef = KalibreringObjekt.Kalibrer();

            DAQdata.Attach(this);

            for (int i = 0; i < 299; i++)
            {
                UILISTE.Add(0);
            }
        }
示例#8
0
        public static List<station> FilterByPeriod(this IEnumerable<station> stats, int? period)
        {
            var now = Helper.CurrentDate;
            var result = new List<station>();

            foreach (var st in stats)
            {
                DateTime? max = st.LastObservDate;

                var period_ = period.GetValueOrDefault(-1);

                bool incl = false;
                if (period_ == 1 && max >= now) incl = true;
                if (period_ == 7 && max >= now.AddDays(-7) && max < now) incl = true;
                if (period_ == 30 && max >= now.AddDays(-30) && max < now.AddDays(-7)) incl = true;
                if (period_ == 60 && max < now.AddDays(-30)) incl = true;

                if (period_ == -1 || incl)
                {
                    //st.LastObservTName = obstname;
                    result.Add(st);
                }
            }
            return result;
        }
        internal static IRepository<Contract> DummyContractsRepository()
        {
            var repo = new Mock<IRepository<Contract>>();

            var contracts = new List<Contract>();

            for (int i = 0; i < NumberOfTestObjects; i++)
            {
                contracts.Add(new Contract
                {
                    ClientId = (i % 2 == 0 ? i : 3).ToString(),
                    HitmanId = (i % 2 == 0 ? i : 3).ToString() + "hitman",
                    Deadline = DateTime.Now,
                    Status = ConnectionStatus.Pending,
                    Id = i
                });
            }

            repo.Setup(r => r.GetById(It.Is<int>(x => x == 4))).Returns(() =>
            {
                return contracts.Where(c => c.Id == 4).FirstOrDefault();
            });

            repo.Setup(r => r.All()).Returns(() =>
            {
                return contracts.AsQueryable();
            });

            return repo.Object;
        }
示例#10
0
        private void ReadExcelData(OleDbConnection conn, string sheetName)
        {
            Console.WriteLine("Reading data...");
            var excelDbCommand = new OleDbCommand(@"SELECT * FROM [" + sheetName + "]", conn);
            using (var oleDbDataAdapter = new OleDbDataAdapter(excelDbCommand))
            {
                DataSet ds = new DataSet();
                oleDbDataAdapter.Fill(ds);
                var locations = new List<Location>();
                using (var reader = ds.CreateDataReader())
                {
                    while (reader.Read())
                    {
                        var loc = new Location();
                        loc.Name = reader["City"].ToString();
                        locations.Add(loc);
                    }
                }

                var db = new MagicalCreatureDbContext();
                foreach (var loc in locations)
                {
                    db.Locations.Add(loc);
                }

                db.SaveChanges();
            }
        }
 private void btnGenerar_Click(object sender, EventArgs e)
 {
     if (cmbEdificios.CheckedItems.Count > 0)
     {
         bool todo = true;
         if (cmbEdificios.CheckedItems.Count < cmbEdificios.Items.Count)
         {
             todo = false;
             MessageBox.Show("Solo se generaran las liquidaciones, no el CSV ni informe de emision", "Sistema");
         }
         DateTime periodo = DateTime.Parse("1/" + this.periodo.Value.Month + "/" + this.periodo.Value.Year);
         List<edificio> edificios = new List<edificio>();
         foreach(edificio ed in cmbEdificios.CheckedItems)
         {
             edificios.Add(ed);
         }
         LoadingForm loading = new LoadingForm();
         (new Thread(() => loading.ShowDialog())).Start();
         Business.ControladorInformes.generarAllLiquidaciones(edificios, todo,periodo, vto1.Value, vto2.Value, txtTextoAlPie.Text, Properties.Resources.emergencias, Properties.Resources.qr, Properties.Resources.tijera);
         Invoke(new Action(() => loading.Close()));
         if (MessageBox.Show("Desea abrir la carpeta con los archivos generados?", "Sistema", MessageBoxButtons.YesNo) == DialogResult.Yes)
             //System.Diagnostics.Process.Start(@"Liquidaciones\" + edi.direccion + periodo.Month + "-" + periodo.Year + ".pdf");
             System.Diagnostics.Process.Start("Liquidaciones\\" + periodo.Month + " del " + periodo.Year);
         this.Close();
     }
     else
         MessageBox.Show("Seleccione al menos un edificio", "Sistema");
 }
示例#12
0
        private void btnCobrar_Click(object sender, EventArgs e)
        {
            List<CatalogoDeudores.DetalleDeuda> detalles = new List<CatalogoDeudores.DetalleDeuda>();

            foreach (DataGridViewRow r in dgvLista.Rows)
            {
                if (r.Cells["Seleccion"].Value != null)
                {
                    CatalogoDeudores.DetalleDeuda d = ((CatalogoDeudores.DetalleDeuda)r.DataBoundItem);
                    Business.ControladorExpensas.registrarPago(d);
                    detalles.Add(d);
                }
            }

            if (detalles.Count > 0)
            {
                if (MessageBox.Show("Desea imprimir comprobante?", "Sistema", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    unidad u = (unidad)cmbUnidad.SelectedItem;
                    titular t = u.titular;

                    System.Diagnostics.Process.Start(Business.ControladorExpensas.emitirRecibo(Properties.Resources.qr, detalles, u, t));
                }
            }

            cmbUnidad_SelectedIndexChanged(sender, e);
            lblImporte.Text = lblRecargo.Text = lblTotalAPagar.Text = "0,00";
        }
        public Publications Get(int id)
        {
            var list = context.Web.Lists.GetByTitle(Title);
            var query = new CamlQuery() { ViewXml = "<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Integer'>" + id + "</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>" };
            var items = list.GetItems(query);
            context.Load(items);
            context.ExecuteQuery();

            if (items.Count > 0)
            {
                string[] lines = items[0]["_x0422__x044d__x0433__x0438_"].ToString().Split(',');

                var tags = new List<Tag>();

                foreach (var line in lines)
                {
                    tags.Add(mapTag(line));
                }

                return new Publications()
                {
                    Title = items[0]["Title"].ToString(),
                    Article = items[0]["_x0421__x0442__x0430__x0442__x04"].ToString(),
                    PublicationDate = ((DateTime)items[0]["_x0414__x0430__x0442__x0430__x00"]).AddDays(1),
                    Source = items[0]["_x0418__x0441__x0442__x043e__x04"].ToString(),
                    Subtitle = items[0]["_x041f__x043e__x0434__x0437__x04"].ToString(),
                    Tags = tags
                };
            }
            else
            {
                return null;
            }
        }
示例#14
0
        // GET: Matching
        public ActionResult Index()
        {
            //Check if user is logged in
            if (!PageAuthorization.Authorize()) return RedirectToAction("Login", "Users");

            //User user = new User();
            //user.Id = 72;
            var user = (User)Session["logged_in_user_obj"];

            var client = new SMARestClient("MeetUpService.svc");
            var meetupContent = client.Get<List<MeetUp>>("meetups/").ToList();
            List<MeetUp> received = new List<MeetUp>();
            List<MeetUp> sent = new List<MeetUp>();

            foreach (var item in meetupContent)
            {
                if (item.Guide.Id == user.Id)
                {
                    received.Add(item);
                }
            }

            foreach (var item in meetupContent)
            {
                if (item.Traveler.Id == user.Id)
                {
                    sent.Add(item);
                }
            }

            ViewBag.ReceivedRequest = received;
            ViewBag.SentRequest= sent;
            return View();
        }
        public IEnumerable<UserResponseModel> GetUsers()
        {
            var users = this.data.Users.All().ToList();
            var listOfUsers = new List<UserResponseModel>();

            foreach (var user in users)
            {
                string userName = user.UserName;

                var ratings = this.data.Ratings.All()
                .Where(r => r.User.UserName == userName)
                .ToList();

                var sumOfAllRatings = 0;
                foreach (var rating in ratings)
                {
                    sumOfAllRatings += rating.Value;
                }

                int ratingsCount = ratings.Count();
                double averageRating = sumOfAllRatings * 1.0 / ratingsCount;

                var newResponseUser = new UserResponseModel()
                {
                    UserName = userName,
                    Rating = ratingsCount == 0 ? 0 : averageRating
                };
                listOfUsers.Add(newResponseUser);
            }

            return listOfUsers;
        }
        public List<FeedItem> ReadFeedItems(Uri uri)
        {
            var feedItems = new List<Data.IFeedItem>();
            SyndicationFeed syndicationFeed;
            using (var xmlReader = XmlReader.Create(uri.AbsoluteUri))
            {
                syndicationFeed = SyndicationFeed.Load(xmlReader);
                xmlReader.Close();
            }

            foreach (var item in syndicationFeed.Items)
            {
                var feedItem = new FeedItem();
                var id = Guid.NewGuid();
                feedItem.Id = Guid.TryParse(item.Id, out id) ? new Guid(item.Id) : id;
                feedItem.Title = item.Title.Text;
                feedItem.Mp3Url = item.Links[0].Uri;
                feedItem.PublishDate = item.PublishDate.DateTime;

                feedItems.Add(feedItem);
            }

            var ret = new List<FeedItem>();
            feedItems.ForEach(x => ret.Add(new FeedItem() { Id = x.Id, Mp3Url = x.Mp3Url, PublishDate = x.PublishDate, Title = x.Title }));
            return ret;
        }
示例#17
0
 /// <summary>
 /// Validates the field values of this object. Override this method to enable
 /// validation of field values.
 /// </summary>
 /// <param name="validationResults">The validation results, add additional results to this list.</param>
 protected override void ValidateFields(List<IFieldValidationResult> validationResults)
 {
     if (string.IsNullOrWhiteSpace(Name))
     {
         validationResults.Add(FieldValidationResult.CreateError(NameProperty, "Name of room is required"));
     }
 }
        public Feed ReadFeed(Uri uri)
        {
            Feed feed = null;
            var feedItems = new List<FeedItem>();
            Category category = null;

            SyndicationFeed syndicationFeed;
            using (var xmlReader = XmlReader.Create(uri.AbsoluteUri))
            {
                syndicationFeed = SyndicationFeed.Load(xmlReader);
                xmlReader.Close();
            }

            if (syndicationFeed == null) return null;
            foreach (var item in syndicationFeed.Items)
            {
                var feedItem = new FeedItem();
                Guid id;

                feedItem.Id = Guid.TryParse(item.Id, out id) ? id : new Guid();
                feedItem.Title = item.Title.Text;
                feedItem.Mp3Url = item.Links.Count > 1 ? item.Links[1].Uri : item.Links[0].Uri;
                feedItem.PublishDate = item.PublishDate.DateTime;
                feedItem.Description = StripHTML(item.Summary.Text);
                feedItem.IsUsed = false;
                feedItems.Add(feedItem);
            }

            var items = new List<Data.IFeedItem>();
            feedItems.ForEach(x => items.Add(x));
            feed = new Feed(Guid.NewGuid(), syndicationFeed.Title.Text, items, uri, category,0);

            return feed;
        }
 /// <summary>
 /// Validates the field values of this object. Override this method to enable
 /// validation of field values.
 /// </summary>
 /// <param name="validationResults">The validation results, add additional results to this list.</param>
 protected override void ValidateFields(List<IFieldValidationResult> validationResults)
 {
     if (string.IsNullOrWhiteSpace(ApiKey))
     {
         validationResults.Add(FieldValidationResult.CreateError(ApiKeyProperty, "Api key is required"));
     }
 }
        /// <summary>
        /// Devuelve las personas.
        /// </summary>
        /// <returns>Las personas.</returns>
        public static List<Persona> GetPersonasAsList()
        {
            _dataServer.IniciarTransaccion();

            try
            {
                List<Persona> result = new List<Persona>();
                const string Query = "SELECT Id, Nombre, Apellido FROM PERSONAS";
                SqlDataReader dataReader = _dataServer.GetDataReader(Query);

                while (dataReader.Read())
                {
                    Persona persona = new Persona
                                          {
                                              Id = (int) dataReader["Id"],
                                              Nombre = (string) dataReader["Nombre"],
                                              Apellido = (string) dataReader["Apellido"]
                                          };
                    result.Add(persona);
                }

                dataReader.Close();
                return result;
            }
            finally
            {
                _dataServer.TerminarTrasaccion();
            }
        }
示例#21
0
 public static List<Staff> getAllStaff()
 {
     List<Staff> StaffsList = new List<Staff>();
     //Connect to SQL Server
     SqlConnection conn = new SqlConnection("Data Source=(local); Database=WebDevelopmentDB; Integrated Security=SSPI");
     //Select all columns for a given StaffID as well as their password hash
     SqlCommand cmd = new SqlCommand("SELECT dbo.Staff.GivenName, dbo.Staff.Surname, dbo.Staff.Email, dbo.Staff.PhoneNumber1, dbo.Staff.PhoneNumber2, dbo.Staff.Role, dbo.Accounts.PassHash FROM dbo.Staff INNER JOIN dbo.Accounts ON dbo.Staff.StaffID = dbo.Accounts.AccID)", conn);
     SqlDataReader rdr = cmd.ExecuteReader();
     while (rdr.Read()) {
         StaffsList.Add(new Staff{
         GivenName = rdr[0].ToString(),
         Surname = rdr[1].ToString(),
         Address = rdr[2].ToString(),
         Email = rdr[3].ToString(),
         Phone1 = rdr[4].ToString(),
         Phone2 = rdr[5].ToString(),
         Role = rdr[6].ToString(),
         PassHash = rdr[7].ToString()});
     }
     //Close the reader and the SQL connection
     if (rdr != null) {
         rdr.Close();
     }
     conn.Close();
     return StaffsList;
 }
示例#22
0
 public static List<Class> getClass(string tutor)
 {
     List<Class> classList = new List<Class>();
     //Connect to SQL Server
     SqlConnection conn = new SqlConnection("Data Source=PANDORASBOX\\PANDORASBOX; Database=WebDevelopmentDB; Integrated Security=SSPI");
     conn.Open();
     ClassRoster roster = new ClassRoster(int.Parse(tutor));
     //Select all columns for a given StaffID as well as their password hash
     for (int i = 0; i <= roster.Roster.GetLength(0); i++) {
         SqlCommand cmd = new SqlCommand("SELECT ClassCode, Day, Time, Semester, TutorID FROM dbo.ClassList WHERE (ClassCode = " + roster.Roster[i, 0] + ")", conn);
         SqlDataReader rdr = cmd.ExecuteReader();
         while (rdr.Read()) {
             classList.Add(new Class {
                 ClassCode = rdr[0].ToString(),
                 Day = rdr[1].ToString(),
                 Time = rdr[2].ToString(),
                 Semester = rdr[3].ToString(),
                 TutorID = rdr[4].ToString()
             });
         }
         //Close the reader and the SQL connection
         if (rdr != null) {
             rdr.Close();
         }
         conn.Close();
     }
     return classList;
 }
示例#23
0
        public static List<ExpensasEdificio> getAllExpensas(List<edificio> edificios, DateTime periodo, DateTime vto1, DateTime vto2)
        {
            try
            {
                List<ExpensasEdificio> expensas = new List<ExpensasEdificio>();
                admEntities db = Datos.getDB();

                //var edificios = db.edificio.ToList();
                int MaxNroFactura = 0;
                List<string> nroFactura = db.Database.SqlQuery<String>(@"select nro_factura from expensas").ToList();
                foreach (var s in nroFactura)
                {
                    int temp = int.Parse(s);
                    if (temp > MaxNroFactura)
                        MaxNroFactura = temp;
                }

                int correlativo = MaxNroFactura + 1;

                DateTime asd = DateTime.Parse("1 /" + periodo.Month + "/" + periodo.Year);
                List<expensas> expensasExistentes = db.expensas.Where(x => x.fecha == asd).ToList();

                foreach (var e in edificios)
                {
                    expensas.Add(getExpensasEdificio(e, periodo, vto1, vto2, ref correlativo, db, expensasExistentes));
                }
                return expensas;
            }
            catch (Exception e)
            {
                Logger.Log.write(e.InnerException == null ? e.Message : e.InnerException.Message);
                throw e;
            }
        }
        public static Game Build()
        {
            var hidingSpots = new List<HidingSpot>();

            var rnd = new Random();
            var indexOfHidingSpot = rnd.Next(9);

            for (var idx = 0; idx < 9; idx++)
            {
                hidingSpots.Add(new HidingSpot
                {
                    Id = idx,
                    HasBeenChecked = false,
                    HasTreasure = idx == indexOfHidingSpot
                });
            }

            _game = new Game
            {
                Id = 1,
                TurnsRemaining = 3,
                HidingSpots = hidingSpots
            };

            return _game;
        }
        public static IRepository<Book> Create()
        {
            var listOfBooks = new List<Book>();
            for (int i = 0; i < 20; i++)
            {
                listOfBooks.Add(new Book
                {
                    Id = i,
                    Title = "Book " + i,
                    Description = "Description" + i,
                    Author = new Author
                    {
                        FirstName = "FirstName " + i,
                        LastName = "LastName " + i
                    }
                });
            }

            var repository = new Mock<IRepository<Book>>();
            repository.Setup(r => r.All()).Returns(listOfBooks.AsQueryable());
            repository.Setup(r => r.Add(It.IsAny<Book>())).Callback<Book>(b =>
            {
                b.Id = 1;
            });
            repository.Setup(r => r.SaveChanges()).Verifiable();

            return repository.Object;
        }
示例#26
0
        public void Deserialise(Reader In)
        {
            Bookings = new List<Booking>(In.ReadInt32());
            for (int x = 0; x < Bookings.Capacity; x++)
                Bookings.Add(DataModel.DeserialiseExternal<Booking>(In));

            Departments = new List<Department>(In.ReadInt32());
            for (int x = 0; x < Departments.Capacity; x++)
                Departments.Add(DataModel.DeserialiseExternal<Department>(In));

            Periods = new List<TimeSlot>(In.ReadInt32());
            for (int x = 0; x < Periods.Capacity; x++)
                Periods.Add(DataModel.DeserialiseExternal<TimeSlot>(In));

            Rooms = new List<Room>(In.ReadInt32());
            for (int x = 0; x < Rooms.Capacity; x++)
                Rooms.Add(DataModel.DeserialiseExternal<Room>(In));

            Users = new List<User>(In.ReadInt32());
            for (int x = 0; x < Users.Capacity; x++)
                Users.Add(DataModel.DeserialiseExternal<User>(In));

            Subjects = new List<Subject>(In.ReadInt32());
            for (int x = 0; x < Subjects.Capacity; x++)
                Subjects.Add(DataModel.DeserialiseExternal<Subject>(In));

            Classes = new List<Class>(In.ReadInt32());
            for (int x = 0; x < Classes.Capacity; x++)
                Classes.Add(DataModel.DeserialiseExternal<Class>(In));
        }
示例#27
0
 internal void RunTest1()
 {
     //BlockStore.AddBlock("C:\\Users\\jony\\Files\\Data\\SEDM\\v3\\2009\\October2009\\01Oct0900_0.zip");
     string datRoot = "C:\\Users\\jony\\Files\\Data\\SEDM\\v3\\2009\\October2009\\01Oct0900_";
     List<string> files = new List<string>();
     for (int i = 0; i < 10; i++) files.Add(datRoot + i + ".zip");
     BlockStore.AddBlocks(files.ToArray());
 }
示例#28
0
 public DataRow(object[] values)
 {
     fields = new List<DataField>(values.Length);
       foreach( object f in values)
       {
     fields.Add(new DataField(f));
       }
 }
        public static void HandleUrl(string url, MetroWindow window)
        {
            url = WebUtility.UrlDecode(url.Remove(0, FullName.Length));

            var r = Regex.Matches(url, "(project|projectGroup)/([^/]*)/([^/]*)/([^/]*)/?");
            foreach (Match m in r)
            {
                var linkType = m.Groups[1].ToString();
              
                switch (linkType)
                {
                    case "project":
                        var gitHubUser = m.Groups[2].ToString();
                        var repositoryName = m.Groups[3].ToString();
                        var assemblyName = m.Groups[4].ToString();

                        var w = new InstallerWindow { Owner = window };
                        w.ListAssemblies(
                            string.Format("https://github.com/{0}/{1}", gitHubUser, repositoryName), true,
                            assemblyName != "" ? m.Groups[4].ToString() : null);
                        w.ShowDialog();
                        break;

                    case "projectGroup":
                        
                        var remaining = url.Remove(0, 13);
                        var assemblies = new List<LeagueSharpAssembly>();

                        while (remaining.IndexOf("/", StringComparison.InvariantCulture) != -1)
                        {
                            var data = remaining.Split(new[] {'/'});
                            if (data.Length < 3)
                            {
                                break;
                            }
                            
                            var assembly = new LeagueSharpAssembly(data[2], "", 
                                string.Format("https://github.com/{0}/{1}", data[0], data[1]));
                            assemblies.Add(assembly);
                            for (int i = 0; i < 3; i++)
                            {
                                remaining = remaining.Remove(0, remaining.IndexOf("/", StringComparison.InvariantCulture) + 1);
                            }
                        }

                        if (assemblies.Count > 0)
                        {
                            assemblies.ForEach(
                                assembly => Config.Instance.SelectedProfile.InstalledAssemblies.Add(assembly));
                            ((MainWindow) window).PrepareAssemblies(assemblies, true, true, false);
                            ((MainWindow) window).ShowTextMessage(Utility.GetMultiLanguageText("Installer"),
                                Utility.GetMultiLanguageText("SuccessfullyInstalled"));
                        }
                        break;
                }
            }
        }
示例#30
0
        public void Scrape()
        {
            KopipastaContext db = new KopipastaContext();
            var posts = db.PostsUncreated.Where(x => x.Status == PostUnscrapedStatus.unscraped).Take(10).ToList();

            //var posts = new List<PostUnscraped> { new PostUnscraped { Id = 0, SiteId = 1, Status = PostUnscrapedStatus.unscraped }, new PostUnscraped { Id = 1, SiteId = 2, Status = PostUnscrapedStatus.unscraped } };

            List<Post> CreatedPosts = new List<Post>();

            IWebDriver driver = new ChromeDriver(@"C:\Selenium\");
            for (int i = 0; i < posts.Count(); i++)
            {
                var post = posts[i];
                driver.Navigate().GoToUrl(baseUrl + post.SiteId);

                try
                {
                    log.Info("parsing post №: " + post.SiteId);
                    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3));
                    string postTitle = wait.Until((d) => { return d.FindElement(By.CssSelector(titleSelector)).Text; });
                    string postBody = driver.FindElement(By.ClassName(bodySelector)).Text;

                    string postRating = ratingBase + post.SiteId;
                    int rating = int.Parse(driver.FindElement(By.Id(postRating)).Text);

                    string DateString = driver.FindElement(By.ClassName(postDate)).Text;

                    var ScrapedPost = new Post() { Body = postBody, Header = postTitle, Rating = rating, SiteId = post.SiteId, Created = DateString };
                    CreatedPosts.Add(ScrapedPost);

                    try
                    {
                        db.Posts.Add(ScrapedPost);
                        db.SaveChanges();
                        db.PostsUncreated.Remove(post);
                    }
                    catch (Exception ex)
                    {
                        log.Error("error saving post to db, post №: " + post.SiteId);
                        log.Error(ex.StackTrace);
                    }

                }
                catch (System.FormatException ex)
                {
                    log.Error("error on parsing post rating, post №: " + post.SiteId);
                    log.Error(ex.StackTrace);
                }
                catch (Exception ex)
                {
                    log.Error("error on scraping post №: " + post.SiteId);
                    log.Error(ex.StackTrace);
                }
            }
            driver.Quit();
        }