public override IEnumerable<string> WriteToFile(string outputFile, List<FeatureItemGroup> features, List<string> samples, string removeNamePrefix)
    {
      var result = base.WriteToFile(outputFile, features, samples, removeNamePrefix).ToList();

      var ntaFile = Path.ChangeExtension(outputFile, ".NTA.count");
      var isomiRFile = Path.ChangeExtension(outputFile, ".isomiR.count");
      var isomiRntaFile = Path.ChangeExtension(outputFile, ".isomiR_NTA.count");
      using (StreamWriter swNTA = new StreamWriter(ntaFile))
      using (StreamWriter swIso = new StreamWriter(isomiRFile))
      using (StreamWriter swIsoNTA = new StreamWriter(isomiRntaFile))
      {
        swNTA.WriteLine("Feature\tLocation\tSequence\t{0}", samples.Merge("\t"));
        swIso.WriteLine("Feature\tLocation\tSequence\t{0}", samples.Merge("\t"));
        swIsoNTA.WriteLine("Feature\tLocation\tSequence\t{0}", samples.Merge("\t"));

        foreach (var feature in features)
        {
          OutputCount(swNTA, feature, samples, MirnaConsts.NO_OFFSET, true, "", removeNamePrefix);

          OutputCount(swIso, feature, samples, 0, false, "_+_0", removeNamePrefix);
          OutputCount(swIso, feature, samples, 1, false, "_+_1", removeNamePrefix);
          OutputCount(swIso, feature, samples, 2, false, "_+_2", removeNamePrefix);

          OutputCount(swIsoNTA, feature, samples, 0, true, "_+_0", removeNamePrefix);
          OutputCount(swIsoNTA, feature, samples, 1, true, "_+_1", removeNamePrefix);
          OutputCount(swIsoNTA, feature, samples, 2, true, "_+_2", removeNamePrefix);
        }
      }

      result.Add(ntaFile);
      result.Add(isomiRFile);
      result.Add(isomiRntaFile);

      return result;
    }
Example #2
0
            public async Task Draw(IUserMessage msg, int num = 1)
            {
                var channel = (ITextChannel)msg.Channel;
                var cards = AllDecks.GetOrAdd(channel.Guild, (s) => new Cards());
                var images = new List<Image>();
                var cardObjects = new List<Cards.Card>();
                if (num > 5) num = 5;
                for (var i = 0; i < num; i++)
                {
                    if (cards.CardPool.Count == 0 && i != 0)
                    {
                        try { await channel.SendMessageAsync("No more cards in a deck.").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); }
                        break;
                    }
                    var currentCard = cards.DrawACard();
                    cardObjects.Add(currentCard);
                    using (var stream = File.OpenRead(Path.Combine(cardsPath, currentCard.ToString().ToLowerInvariant()+ ".jpg").Replace(' ','_')))
                        images.Add(new Image(stream));
                }
                MemoryStream bitmapStream = new MemoryStream();
                images.Merge().SaveAsPng(bitmapStream);
                bitmapStream.Position = 0;
                //todo CARD NAMES?
                var toSend = $"{msg.Author.Mention}";
                if (cardObjects.Count == 5)
                    toSend += $" drew `{Cards.GetHandValue(cardObjects)}`";

                await channel.SendFileAsync(bitmapStream, images.Count + " cards.jpg", toSend).ConfigureAwait(false);
            }
Example #3
0
        public override Func<CommandEventArgs, Task> DoFunc() {
            Random r = new Random();
            return async e => {
                if (e.Args[0] == "") {
                    int num1 = r.Next(0, 10);
                    int num2 = r.Next(0, 10);

                    Image[] images;

                    if (num1 == 0 && num2 == 0 && r.Next(0, 2) == 1) {
                        images = new Image[3] { GetDice(1), GetDice(0), GetDice(0) };
                    } else {
                        images = new Image[2] { GetDice(num1), GetDice(num2) };
                    }

                    Bitmap bitmap = images.Merge();
                    await e.Channel.SendFile("dice.png", bitmap.ToStream(ImageFormat.Png));
                    return;
                } else {
                    try {
                        int num = int.Parse(e.Args[0]);
                        if (num < 1) num = 1;
                        if (num > 30) {
                            await e.Send("You can roll up to 30 dies at a time.");
                            num = 30;
                        }
                        List<Image> dices = new List<Image>(num);
                        List<int> values = new List<int>(num);
                        for (int i = 0; i < num; i++) {
                            int randomNumber = r.Next(1, 7);
                            int toInsert = dices.Count;
                            if (randomNumber == 6 || dices.Count == 0)
                                toInsert = 0;
                            else if (randomNumber != 1)
                                for (int j = 0; j < dices.Count; j++) {
                                    if (values[j] < randomNumber) {
                                        toInsert = j;
                                        break;
                                    }
                                }
                            dices.Insert(toInsert, GetDice(randomNumber));
                            values.Insert(toInsert, randomNumber);
                        }

                        Bitmap bitmap = dices.Merge();
                        await e.Send(values.Count + " Dies rolled. Total: **" + values.Sum() + "** Average: **" + (values.Sum() / (1.0f * values.Count)).ToString("N2") + "**");
                        await e.Channel.SendFile("dices.png", bitmap.ToStream(ImageFormat.Png));
                    } catch  {
                        await e.Send("Please enter a number of dices to roll.");
                        return;
                    }
                }
            };
        }
Example #4
0
        public void Add(string message, List<KeyValuePair<string, string>> options)
        {
            defaults.Add(new KeyValuePair<string, string>("apikey", this.ProwlConfig.ApiKey));

            List<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>();

            data.AddRange(options);
            data = data.Merge(defaults);
            data.Add(new KeyValuePair<string, string>("event", message));

            this._api("add", data);
        }
Example #5
0
        public static IList<Cms_Category> GetCategory(IList<Cms_Category> list)
        {
            IList<Cms_Category> result = new List<Cms_Category>();
            var a = from p in list where string.IsNullOrEmpty(p.Pguid) select p;

            IList<Cms_Category> rootlist = a.ToList<Cms_Category>();
            foreach (var item in rootlist)
            {
                result.Add(item);
                result = result.Merge(GetRecursionCateory(item.Fguid, list));
            }
            result.OrderBy(d => d.Categoryid);
            return result;
        }
Example #6
0
        public static IList<Base_Module> GetModule(IList<Base_Module> list)
        {
            IList<Base_Module> result = new List<Base_Module>();
            var a = from p in list where string.IsNullOrEmpty(p.Pguid) select p;

            IList<Base_Module> rootlist = a.ToList<Base_Module>();
            foreach (var item in rootlist)
            {
                result.Add(item);
                result = result.Merge(GetRecursionModule(item.Fguid, list));
            }
            result.OrderBy(d => d.Moduleno);
            return result;
        }
    private string GetKeywordSql()
    {
      if (Keywords.Length == 0)
      {
        return string.Empty;
      }

      var sqls = new List<string>();

      sqls.Add(GetSql("gse.title", this.Keywords));
      sqls.Add(GetSql("gse.summary", this.Keywords));
      sqls.Add(GetSql("gse.type", this.Keywords));
      sqls.Add(GetSql("gse.overall_design", this.Keywords));

      return sqls.Merge(" or ");
    }
    public virtual IEnumerable<string> WriteToFile(string outputFile, List<FeatureItemGroup> features, List<string> samples, string removeNamePrefix)
    {
      using (StreamWriter sw = new StreamWriter(outputFile))
      {
        //sw.NewLine = Environment.NewLine;
        sw.WriteLine("Feature\tLocation\tSequence\t{0}", samples.Merge("\t"));
        foreach (var feature in features)
        {
          OutputCount(sw, feature, samples, MirnaConsts.NO_OFFSET, false, "", removeNamePrefix);
        }
      }

      string readFile = WriteReadCountTable(outputFile, features, samples);

      return new[] { outputFile, readFile };
    }
Example #9
0
        public override Func<CommandEventArgs, Task> DoFunc() => async (e) =>
          {
              if (cards == null)
              {
                  await e.Send("Shuffling cards...");
                  cards = new Cards();
              }

              try
              {
                  int num = 1;
                  var isParsed = int.TryParse(e.GetArg("count"), out num);
                  if (!isParsed || num < 2)
                  {
                      var c = cards.DrawACard();
                      await e.Channel.SendFile(c.Name +".jpg",(Properties.Resources.ResourceManager.GetObject(c.Name) as Image).ToStream());
                      return;
                  }
                  if (num > 5)
                      num = 5;

                  List<Image> images = new List<Image>();
                  List<Cards.Card> cardObjects = new List<Cards.Card>();
                  for (int i = 0; i < num; i++)
                  {
                      if (cards.CardPool.Count == 0 && i != 0)
                      {
                          await e.Send("No more cards in a deck.");
                          break;
                      }
                      var currentCard = cards.DrawACard();
                      cardObjects.Add(currentCard);
                      images.Add(Properties.Resources.ResourceManager.GetObject(currentCard.Name) as Image);
                  }
                  Bitmap bitmap = images.Merge();
                  await e.Channel.SendFile(images.Count + " cards.jpg", bitmap.ToStream());
                  if (cardObjects.Count == 5)
                  {
                      await e.Send(Cards.GetHandValue(cardObjects));
                  }
              }
              catch (Exception ex)
              {
                  Console.WriteLine("Error drawing (a) card(s) " + ex.ToString());
              }
          };
Example #10
0
        private static IList<Base_Module> GetRecursionModule(string fguid, IList<Base_Module> list)
        {
            IList<Base_Module> result = new List<Base_Module>();
            var a = from p in list where p.Pguid == fguid select p;
            IList<Base_Module> sublist = a.ToList<Base_Module>();

            char nbsp = (char)0xA0;
            foreach (var item in sublist)
            {
                int nodenolen = item.Moduleno.Length;
                string text = "∟" + item.Title.Trim();
                int len = nodenolen * 2 + text.Length-5;
                item.Title = text.PadLeft(len, nbsp);
                result.Add(item);
                result = result.Merge(GetRecursionModule(item.Fguid, list));
            }
            return result;
        }
Example #11
0
        private static IList<Cms_Category> GetRecursionCateory(string fguid, IList<Cms_Category> list)
        {
            IList<Cms_Category> result = new List<Cms_Category>();
            var a = from p in list where p.Pguid == fguid select p;
            IList<Cms_Category> sublist = a.ToList<Cms_Category>();

            char nbsp = (char)0xA0;
            foreach (var item in sublist)
            {
                int nodenolen = item.Categoryid.Length;
                string text = "∟" + item.Title.Trim();
                int len = nodenolen + text.Length;
                item.Title = text.PadLeft(len, nbsp);
                result.Add(item);
                result = result.Merge(GetRecursionCateory(item.Fguid, list));
            }
            return result;
        }
Example #12
0
        private Func<CommandEventArgs, Task> DrawCardFunc() => async (e) =>
        {
            var cards = AllDecks.GetOrAdd(e.Server, (s) => new Cards());

            try
            {
                var num = 1;
                var isParsed = int.TryParse(e.GetArg("count"), out num);
                if (!isParsed || num < 2)
                {
                    var c = cards.DrawACard();
                    await e.Channel.SendFile(c.Name + ".jpg", (Properties.Resources.ResourceManager.GetObject(c.Name) as Image).ToStream()).ConfigureAwait(false);
                    return;
                }
                if (num > 5)
                    num = 5;

                var images = new List<Image>();
                var cardObjects = new List<Cards.Card>();
                for (var i = 0; i < num; i++)
                {
                    if (cards.CardPool.Count == 0 && i != 0)
                    {
                        await e.Channel.SendMessage("No more cards in a deck.").ConfigureAwait(false);
                        break;
                    }
                    var currentCard = cards.DrawACard();
                    cardObjects.Add(currentCard);
                    images.Add(Properties.Resources.ResourceManager.GetObject(currentCard.Name) as Image);
                }
                var bitmap = images.Merge();
                await e.Channel.SendFile(images.Count + " cards.jpg", bitmap.ToStream()).ConfigureAwait(false);
                if (cardObjects.Count == 5)
                {
                    await e.Channel.SendMessage($"{e.User.Mention} `{Cards.GetHandValue(cardObjects)}`").ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error drawing (a) card(s) " + ex.ToString());
            }
        };
Example #13
0
        public void TestMerge()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            var selRes = ed.Select("Выбери полилинии для объединения");
            if (selRes.Count==0) return;

            using (var t = db.TransactionManager.StartTransaction())
            {
                var pls = new List<Polyline>();
                foreach (var item in selRes)
                {
                    if (!item.IsValidEx()) continue;
                    var pl = item.GetObject(OpenMode.ForRead) as Polyline;
                    if (pl != null)
                    {
                        pls.Add(pl);
                    }
                }

                try
                {
                    var plMerged = pls.Merge();

                    var cs = db.CurrentSpaceId.GetObject(OpenMode.ForWrite) as BlockTableRecord;
                    cs.AppendEntity(plMerged);
                    t.AddNewlyCreatedDBObject(plMerged, true);
                    plMerged.ColorIndex = 5;
                }
                catch(System.Exception ex)
                {
                    Application.ShowAlertDialog(ex.ToString());
                }

                t.Commit();
            }
        }
    private static void WriteToFile(string fileName, List<RockhopperTranscriptResult> data, List<string> genes, Func<RockhopperTranscript, bool> significantFilter)
    {
      using (var sw = new StreamWriter(fileName))
      {
        sw.Write("Gene,Product");
        foreach (var d in data)
        {
          sw.Write(",{0}_RPKM_{1},{0}_RPKM_{2},{0}_log2({1}/{2}),{0}_qValue", d.ComparisonName, d.Group1, d.Group2);
        }
        sw.WriteLine(",Significant");

        foreach (var gene in genes)
        {
          sw.Write(gene);

          var synonym = gene.StringBefore(",");
          List<string> significant = new List<string>();
          foreach (var d in data)
          {
            if (d.UnpredictedMap.ContainsKey(synonym))
            {
              var entry = d.UnpredictedMap[synonym];
              sw.Write(",{0},{1},{2:0.00},{3}", entry.RPKM1, entry.RPKM2, entry.FoldChange, entry.Qvalue);
              if (significantFilter(entry))
              {
                significant.Add(d.ComparisonName);
              }
            }
            else
            {
              sw.Write(",0,0,0,1");
            }
          }

          sw.WriteLine(",{0}", significant.Merge(";"));
        }
      }
    }
Example #15
0
        private IObservable<EventPattern<FileSystemEventArgs>> GenerateWatchers()
        {
            var observables = new List<IObservable<EventPattern<FileSystemEventArgs>>>();
            foreach (Directory directory in _configuration.Watch)
            {
                if (!System.IO.Directory.Exists(directory.Path)) continue;
                var watcher = new FileSystemWatcher(directory.Path)
                {
                    IncludeSubdirectories = directory.IncludeSubDirs,
                    EnableRaisingEvents = false
                };
                _watchers.Add(watcher);
                foreach (var listenerType in directory.GetListenerTypes())
                {
                    IObservable<EventPattern<FileSystemEventArgs>> observable;
                    switch (listenerType)
                    {
                        case ListenerType.Created:
                            observable =
                                Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
                                    ev => watcher.Created += ev, ev => watcher.Created -= ev);
                            observables.Add(observable);
                            break;
                        case ListenerType.Changed:
                            observable = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
                                ev => watcher.Changed += ev, ev => watcher.Changed -= ev);
                            observables.Add(observable);
                            break;
                        case ListenerType.Deleted:
                            observable = Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
                                ev => watcher.Deleted += ev, ev => watcher.Deleted -= ev);
                            observables.Add(observable);
                            break;
                        case ListenerType.Renamed:
                            var renamedObservable = Observable.FromEventPattern<RenamedEventHandler, RenamedEventArgs>(
                                ev => watcher.Renamed += ev, ev => watcher.Renamed -= ev);
                            observables.Add(
                                renamedObservable.Select(
                                    evpat => new EventPattern<FileSystemEventArgs>(evpat.Sender, evpat.EventArgs)));
                            break;
                    }
                }
            }

            var mergedObservables = observables.Merge();
            return mergedObservables;
        }
Example #16
0
        public void TagListMerging()
        {
            IList<Tag> tl = new List<Tag>();
            tl.Add(new Tag("http://nu.nl", Tag.FHIRTAGNS, "v1"));
            tl.Add(new Tag("http://dan.nl", Tag.FHIRTAGNS, "v2"));

            IList<Tag> tl2 = new List<Tag>();
            tl2.Add(new Tag("http://nu.nl", Tag.FHIRTAGNS, "v3"));
            tl2.Add(new Tag("http://nooit.nl", Tag.FHIRTAGNS, "v4"));

            var result = tl.Merge(tl2);

            Assert.AreEqual(3, result.Count());
            Assert.AreEqual(1, result.FilterFhirTags().FindByTerm("http://nu.nl").Count());
            Assert.AreEqual("v3", result.FindByTerm("http://nu.nl", Tag.FHIRTAGNS).First().Label);
            Assert.AreEqual(1, result.FilterFhirTags().FindByTerm("http://nooit.nl").Count());
        }
Example #17
0
 private IObservable<Unit> CancelInternal() {
     var list = new List<IObservable<GameLockChanged>>();
     foreach (var l in _list) {
         l.Value.Cancel();
         _lockChanged.OnNext(new GameLockChanged(l.Key, true, false));
         list.Add(GenerateObservable(l.Key));
     }
     return list.Any() ? list.Merge().Select(x => Unit.Value) : Observable.Return(Unit.Value);
 }
Example #18
0
    public override IEnumerable<string> Process()
    {
      var result = new List<string>();

      Dictionary<string, BarInfo> barMap;

      barMap = new Dictionary<string, BarInfo>();
      foreach (var tumor in _options.TumorTypes)
      {
        var curMap = TCGAUtils.GetBarcodeFileMap(_options.TCGADirectory,
          _options.GetTechnology(), tumor, _options.Platforms, _options.GetTCGASampleCodes().ToArray());

        foreach (var v in curMap)
        {
          barMap[GetSampleKey(tumor, v.Key)] = v.Value;
        }
      }

      var headers = new List<string>();
      var clindata = new Dictionary<string, IAnnotation>();
      foreach (var tumor in _options.TumorTypes)
      {
        ReadClinData(clindata, tumor, headers);
      }
      Console.WriteLine("{0} patient clinical information readed", clindata.Count);

      List<string> noclinical = new List<string>();
      var keyvalues = barMap.ToList();
      foreach (var bm in keyvalues)
      {
        if (!clindata.ContainsKey(GetSampleKey(GetTumorType(bm.Key), bm.Value.Paticipant)))
        {
          noclinical.Add(bm.Key);

          Console.Error.WriteLine(string.Format("Cannot find clinical data for patient {0}", bm.Value.Paticipant));
          if (_options.WithClinicalInformationOnly)
          {
            barMap.Remove(bm.Key);
          }
        }
      }

      Progress.SetMessage("Reading data ...");
      Func<double, double> getValue;
      var valueMap = GetData(barMap, out getValue);

      var genes = GetCommonGenes(valueMap);
      var samples = valueMap.Keys.OrderBy(m => m).ToList();

      Progress.SetMessage("Saving data ...");

      result.Add(_options.OutputFile);
      result.Add(_options.DesignFile);
      if (_options.TumorTypes.Count > 1)
      {
        using (var sw = new StreamWriter(_options.OutputFile))
        {
          sw.WriteLine("Gene\t{0}", samples.Merge("\t"));
          foreach (var gene in genes)
          {
            sw.Write(gene);
            foreach (var sample in samples)
            {
              sw.Write("\t{0}", getValue(valueMap[sample][gene]));
            }
            sw.WriteLine();
          }
        }

        using (var sw = new StreamWriter(_options.DesignFile))
        {
          sw.Write("Sample\tBarcode\tPatient\tTumorType\tPlatform\tSampleType\tSampleTypeDescription");
          if (headers.Count > 0)
          {
            sw.WriteLine("\t{0}", headers.Merge("\t"));
          }
          else
          {
            sw.WriteLine();
          }

          foreach (var entry in barMap)
          {
            var tumor = GetTumorType(entry.Key);
            var type = TCGASampleCode.Find(entry.Value.Sample);
            sw.Write("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", entry.Key, entry.Value.BarCode, entry.Value.Paticipant, tumor, entry.Value.Platform, type.ShortLetterCode,
              type.Definition);
            var key = GetSampleKey(tumor, entry.Value.Paticipant);
            var vdata = clindata.ContainsKey(key) ? clindata[key] : new Annotation();
            foreach (var header in headers)
            {
              if (vdata.Annotations.ContainsKey(header))
              {
                sw.Write("\t{0}", vdata.Annotations[header]);
              }
              else
              {
                sw.Write("\t");
              }
            }
            sw.WriteLine();
          }
        }
      }
      else
      {
        using (var sw = new StreamWriter(_options.OutputFile))
        {
          sw.WriteLine("Gene\t{0}", (from s in samples select s.StringAfter("_")).Merge("\t"));
          foreach (var gene in genes)
          {
            sw.Write(gene);
            foreach (var sample in samples)
            {
              sw.Write("\t{0}", getValue(valueMap[sample][gene]));
            }
            sw.WriteLine();
          }
        }

        using (var sw = new StreamWriter(_options.DesignFile))
        {
          sw.Write("Sample\tBarcode\tPatient\tTumorType\tPlatform\tSampleType\tSampleTypeDescription");
          if (headers.Count > 0)
          {
            sw.WriteLine("\t{0}", headers.Merge("\t"));
          }
          else
          {
            sw.WriteLine();
          }

          foreach (var entry in barMap)
          {
            var tumor = _options.TumorTypes.First();
            var type = TCGASampleCode.Find(entry.Value.Sample);
            sw.Write("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", entry.Key.StringAfter("_"), entry.Value.BarCode, entry.Value.Paticipant, tumor, entry.Value.Platform, type.ShortLetterCode,
              type.Definition);
            var key = GetSampleKey(tumor, entry.Value.Paticipant);
            var vdata = clindata.ContainsKey(key) ? clindata[key] : new Annotation();
            foreach (var header in headers)
            {
              if (vdata.Annotations.ContainsKey(header))
              {
                sw.Write("\t{0}", vdata.Annotations[header]);
              }
              else
              {
                sw.Write("\t");
              }
            }
            sw.WriteLine();
          }
        }

        var clinicalOptions = new TCGAClinicalInformationBuilderOptions()
        {
          ClinicalFile = TCGAUtils.GetClinicPatientFile(_options.TCGADirectory, _options.TumorTypes.First()),
          DataFile = _options.OutputFile,
          ThrowException = false,
        };
        result.AddRange(new TCGAClinicalInformationBuilder(clinicalOptions) { Progress = this.Progress }.Process());
      }
      Progress.End();

      if (noclinical.Count == 0)
      {
        return result.ToArray();
      }
      else
      {
        return new[] { string.Format("There are {0} samples without patient information:\n  {1}\n\nResult have been saved to:\n  {2}", noclinical.Count, noclinical.Merge("\n  "), result.Merge("\n  ")) };
      }
    }
    public override IEnumerable<string> WriteToFile(string outputFile, List<FeatureItemGroup> features, List<string> samples, string removeNamePrefix)
    {
      var header = "Feature\tLocation\tSequence\t" + samples.Merge("\t");

      var dicList = new List<Dictionary<string, double>>();
      var ntaList = new List<string[]>();
      var isomiRList = new List<string[]>();
      var ntaIsomiRList = new List<string[]>();
      foreach (var featureGroup in features)
      {
        var dic = new Dictionary<string, double>();
        var ntas = new HashSet<string>();
        var isomiRs = new HashSet<string>();
        var ntaIsomiRs = new HashSet<string>();
        foreach (var feature in featureGroup)
        {
          foreach (var featureLoc in feature.Locations)
          {
            foreach (var samLoc in featureLoc.SamLocations)
            {
              var ntaKey = GetNTAKey(samLoc.SamLocation.Parent.ClippedNTA);
              var isomiRkey = GetIsomiRKey(samLoc.Offset);
              var ntaIsomiRKey = GetNTAIsomiRKey(samLoc.SamLocation.Parent.ClippedNTA, samLoc.Offset);

              ntas.Add(ntaKey);
              isomiRs.Add(isomiRkey);
              ntaIsomiRs.Add(ntaIsomiRKey);

              var samCount = samLoc.SamLocation.Parent.GetEstimatedCount();

              string sampleKey = samLoc.SamLocation.Parent.Sample;
              AddCount(dic, sampleKey, samCount);

              var sampleNTAKey = GetSampleKey(samLoc.SamLocation.Parent.Sample, ntaKey);
              AddCount(dic, sampleNTAKey, samCount);

              string sampleIsomiRKey = GetSampleKey(samLoc.SamLocation.Parent.Sample, isomiRkey);
              AddCount(dic, sampleIsomiRKey, samCount);

              var sampleNTAIsomiRKey = GetSampleKey(samLoc.SamLocation.Parent.Sample, ntaIsomiRKey);
              AddCount(dic, sampleNTAIsomiRKey, samCount);
            }
          }
        }

        dicList.Add(dic);
        ntaList.Add(ntas.OrderBy(m => m).ToArray());
        isomiRList.Add(isomiRs.OrderBy(m => m).ToArray());
        ntaIsomiRList.Add(ntaIsomiRs.OrderBy(m => m).ToArray());
      }

      var ntaFile = Path.ChangeExtension(outputFile, ".NTA.count");
      var isomiRFile = Path.ChangeExtension(outputFile, ".isomiR.count");
      var ntaIsomiRFile = Path.ChangeExtension(outputFile, ".isomiR_NTA.count");
      using (var sw = new StreamWriter(outputFile))
      using (var swNTA = new StreamWriter(ntaFile))
      using (var swIsomiR = new StreamWriter(isomiRFile))
      using (var swNTAIsomiR = new StreamWriter(ntaIsomiRFile))
      {
        sw.WriteLine(header);
        swNTA.WriteLine(header);
        swIsomiR.WriteLine(header);
        swNTAIsomiR.WriteLine(header);

        for (int i = 0; i < features.Count; i++)
        {
          var feature = features[i];
          var dic = dicList[i];
          var ntas = ntaList[i];
          var isomiRs = isomiRList[i];
          var ntaIsomiRs = ntaIsomiRList[i];

          var featureName = (from f in feature select f.Name.StringAfter(removeNamePrefix)).Merge(";");
          var featureSequences = (from l in feature select l.Sequence).ToArray();
          var sequence = featureSequences.Distinct().Count() == 1 ? featureSequences.First() : featureSequences.Merge(";");
          var featureLocations = feature.DisplayLocations;

          WriteCounts(samples, sw, dic, new[] { string.Empty }, featureName, sequence, featureLocations);
          WriteCounts(samples, swNTA, dic, ntas, featureName, sequence, featureLocations);
          WriteCounts(samples, swIsomiR, dic, isomiRs, featureName, sequence, featureLocations);
          WriteCounts(samples, swNTAIsomiR, dic, ntaIsomiRs, featureName, sequence, featureLocations);
        }
      }

      string readFile = WriteReadCountTable(outputFile, features, samples);

      return new[] { outputFile, ntaFile, isomiRFile, ntaIsomiRFile, readFile };
    }
Example #20
0
        // Returns a list of all direct and indirect assignments of this variable
        protected IReference[] GetAssignmentsRecursive(ref HashSet<LuatValue> visited)
        {
            visited.Add(this);

            var assignments = new List<IReference>();
            assignments.AddRange(Assignments);

            foreach (IReference reference in Assignments)
            {
                var variable = reference.Value as LuatVariable;
                if (variable != null && visited.Contains(variable))
                    continue;

                if (variable != null)
                    assignments.Merge(variable.GetAssignmentsRecursive(ref visited));
            }

            return assignments.ToArray();
        }
Example #21
0
        public void GotoDefinition(ILuaIntellisenseDocument document)
        {
            if (!CanGoto(document))
                return;

            Func<Expression, List<LuatValue.IReference>> func =
                expression =>
                {
                    var definitions = new List<LuatValue.IReference>();
                    foreach (LuatValue value in expression.ResolvedValues.Values)
                    {
                        var variable = value as LuatVariable;
                        if (variable != null)
                            definitions.Merge(variable.Assignments.ToArray());
                    }

                    return definitions;
                };

            GotoDefinitions("Goto definition", document, func);
        }
Example #22
0
        /// <summary>
        /// Presents the parameter info prompt to the user
        /// </summary>
        /// <param name="syntaxEditor"></param>
        /// <returns></returns>
        private bool ShowIntelliPromptParameterInfoImmediate(ActiproSoftware.SyntaxEditor.SyntaxEditor syntaxEditor)
        {
            // Initialize the parameter info
            syntaxEditor.IntelliPrompt.ParameterInfo.Hide();
            syntaxEditor.IntelliPrompt.ParameterInfo.Info.Clear();
            syntaxEditor.IntelliPrompt.ParameterInfo.SelectedIndex = 0;

            // Get the compilation unit
            var cu = syntaxEditor.Document.SemanticParseData as CompilationUnit;
            if (cu == null)
                return false;

            // Move back to the last open bracket
            int caret = syntaxEditor.Caret.Offset;
            TextStream stream = syntaxEditor.Document.GetTextStream(caret);
            stream.GoToPreviousTokenWithID(LuatTokenId.OpenParenthesis);

            // Find the argument list the caret is within
            var arguments = cu.FindNodeRecursive<ArgumentList>(stream.Offset);
            ArgumentList next = arguments;
            while (null != next && false == arguments.InsideBrackets(caret))
            {
                arguments = next;
                next = next.FindAncestor<ArgumentList>();
            }

            if (arguments == null)
                return false;

            var call = arguments.ParentNode as FunctionCall;
            if (call == null)
                throw new Exception("ArgumentList does not have FunctionCall as parent");

            // Configure the parameter info
            var textRange = new TextRange(arguments.ListTextRange.StartOffset, arguments.ListTextRange.EndOffset + 1);

            IntelliPromptParameterInfo pi = syntaxEditor.IntelliPrompt.ParameterInfo;
            pi.ValidTextRange = textRange;
            pi.CloseDelimiterCharacter = ')';
            pi.UpdateParameterIndex();
            pi.HideOnParentFormDeactivate = true;

            var functions = new List<LuatValue>();
            foreach (var value in call.ResolvedFunctions)
            {
                if (false == value.Type is LuatTypeFunction)
                    continue;

                functions.Merge(value);

                pi.Info.Add(GetQuickInfoForFunctionCall(value, pi.ParameterIndex));
            }

            // Store the function types in the context
            pi.Context = functions.ToArray();

            // Show the parameter info
            pi.Show(caret);

            return false;
        }
Example #23
0
        /// <summary>
        /// Populates the warnings for each compilation unit registered with the database
        /// </summary>
        private void DoProcessWarnings()
        {
            lock (this)
            {
                // Remove warnings that are created from this function
                foreach (LuatScript script in m_scripts)
                {
                    if (script.CU == null)
                        continue;

                    script.CU.ClearWarnings(WarningType.UnresolvedVariable);
                    script.CU.ClearWarnings(WarningType.MixedType);
                    script.CU.ClearWarnings(WarningType.UnknownType);

                    foreach (Expression expression in script.UnresolvedExpressions)
                    {
                        var variable = expression as VariableExpression;
                        if (variable != null)
                        {
                            expression.AddWarning(script, WarningType.UnresolvedVariable, "Unknown variable '" + variable.Name.Text + "'");
                            continue;
                        }

                        var index = expression as IndexExpression;
                        if ((index != null) && (index.RHS != null))
                        {
                            index.RHS.AddWarning(script, WarningType.UnresolvedVariable, "Unknown index '" + index.RHS.DisplayText + "'");
                            continue;
                        }
                    }
                }

                foreach (LuatVariable variable in m_unresolvedVariableTypes)
                {
                    var types = new List<LuatType>();
                    foreach (LuatValue assignment in variable.ValueAssignments)
                    {
                        types.Merge(null != assignment ? assignment.Type : LuatTypeUnknown.Instance);
                    }

                    int typeCount = types.Count;
                    if (typeCount > 1)
                    {
                        var sb = new StringBuilder();
                        sb.Append("Assignment of different types ");
                        sb.Append("( ");
                        sb.Append(types.ToArray().ToCommaSeperatedList(type => type.ToString()));
                        sb.Append(" )");

                        foreach (LuatValue.IReference assignment in variable.Assignments)
                        {
                            string warning = string.Format(sb.ToString());
                            assignment.AddWarning(WarningType.MixedType, warning);
                        }
                    }

                    //                 foreach ( LuatValue.IReference reference in variable.References )
                    //                 {
                    //                     reference.AddWarning( WarningType.UnknownType, "Unknown type '" + reference.DisplayText + "'" );
                    //                 }
                }
            }
        }
Example #24
0
        public void GotoReference(ILuaIntellisenseDocument document)
        {
            if (!CanGoto(document))
                return;

            Func<Expression, List<LuatValue.IReference>> func =
                expression =>
                {
                    var definitions = new List<LuatValue.IReference>();
                    foreach (LuatValue value in expression.ResolvedValues.Values)
                    {
                        definitions.Merge(value.References.ToArray());
                    }

                    return definitions;
                };

            GotoDefinitions("Goto reference", document, func);
        }
Example #25
0
        private Func<CommandEventArgs, Task> RollFunc(bool ordered = true)
        {
            var r = new Random();
            return async e =>
            {
                var arg = e.Args[0]?.Trim();
                if (string.IsNullOrWhiteSpace(arg))
                {
                    var gen = r.Next(0, 101);

                    var num1 = gen / 10;
                    var num2 = gen % 10;

                    var imageStream = new Image[2] { GetDice(num1), GetDice(num2) }.Merge().ToStream(ImageFormat.Png);

                    await e.Channel.SendFile("dice.png", imageStream).ConfigureAwait(false);
                    return;
                }
                Match m;
                if ((m = dndRegex.Match(arg)).Length != 0)
                {
                    int n1;
                    int n2;
                    if (int.TryParse(m.Groups["n1"].ToString(), out n1) &&
                        int.TryParse(m.Groups["n2"].ToString(), out n2) &&
                        n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0)
                    {
                        var arr = new int[n1];
                        for (int i = 0; i < n1; i++)
                        {
                            arr[i] = r.Next(1, n2 + 1);
                        }
                        var elemCnt = 0;
                        await e.Channel.SendMessage($"`Rolled {n1} {(n1 == 1 ? "die" : "dice")} 1-{n2}.`\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false);
                    }
                    return;
                }
                try
                {
                    var num = int.Parse(e.Args[0]);
                    if (num < 1) num = 1;
                    if (num > 30)
                    {
                        await e.Channel.SendMessage("You can roll up to 30 dice at a time.").ConfigureAwait(false);
                        num = 30;
                    }
                    var dices = new List<Image>(num);
                    var values = new List<int>(num);
                    for (var i = 0; i < num; i++)
                    {
                        var randomNumber = r.Next(1, 7);
                        var toInsert = dices.Count;
                        if (ordered)
                        {
                            if (randomNumber == 6 || dices.Count == 0)
                                toInsert = 0;
                            else if (randomNumber != 1)
                                for (var j = 0; j < dices.Count; j++)
                                {
                                    if (values[j] < randomNumber)
                                    {
                                        toInsert = j;
                                        break;
                                    }
                                }
                        }
                        else {
                            toInsert = dices.Count;
                        }
                        dices.Insert(toInsert, GetDice(randomNumber));
                        values.Insert(toInsert, randomNumber);
                    }

                    var bitmap = dices.Merge();
                    await e.Channel.SendMessage(values.Count + " Dice rolled. Total: **" + values.Sum() + "** Average: **" + (values.Sum() / (1.0f * values.Count)).ToString("N2") + "**").ConfigureAwait(false);
                    await e.Channel.SendFile("dice.png", bitmap.ToStream(ImageFormat.Png)).ConfigureAwait(false);
                }
                catch
                {
                    await e.Channel.SendMessage("Please enter a number of dice to roll.").ConfigureAwait(false);
                }
            };
        }
Example #26
0
        /// <summary>
        /// GetElementByTagName
        /// </summary>
        /// <param name="SourceHtml">Html代码</param>
        /// <param name="TagName">标签名称</param>
        /// <returns>返回标签的OuterHtml</returns>
        public static List<string> GetElementByTagName(this string SourceHtml, string TagName)
        {
            string pattern = string.Format(@"<{0}[^>]*>(?<key>[\w\W]*(((?'Open'<{0}[^>]*>)[\w\W]*)+((?'-Open'</{0}>)[\w\W]*)+)*(?(Open)(?!)))</{0}>", TagName);
            List<string> result = new List<string>();
            List<string> first_result = GetMatch(SourceHtml, pattern);
            foreach (string sub in first_result)
            {
                if (sub.CountString(string.Format("</{0}>", TagName)) > 0)
                {
                    result.Merge(GetElementByTagName(sub, TagName));
                }
            }
            result = result.Merge(first_result);

            return result;
        }
Example #27
0
        private static bool CanRenameVariable(ILuaIntellisenseDocument document, out VariableExpression expression, out List<LuatValue.IReference> definitions)
        {
            expression = null;
            definitions = null;

            if (!CanGoto(document))
                return false;

            if (document.SyntaxEditorControl == null)
                return false;

            var se = (ActiproSoftware.SyntaxEditor.SyntaxEditor)document.SyntaxEditorControl;
            if ((se.SelectedView == null) || (se.SelectedView.Selection == null))
                return false;

            expression = GetExpressionAt(se.Document, se.SelectedView.Selection.StartOffset) as VariableExpression;
            if (expression == null)
                return false;

            definitions = new List<LuatValue.IReference>();
            foreach (LuatValue value in expression.ResolvedValues.Values)
            {
                var variable = value.As<LuatVariable>();
                if (variable != null)
                    definitions.Merge(variable.References.ToArray());
            }

            return definitions.Count > 0;
        }
Example #28
0
        public async Task Hearthstone(IUserMessage umsg, [Remainder] string name = null)
        {
            var channel = (ITextChannel)umsg.Channel;
            var arg = name;
            if (string.IsNullOrWhiteSpace(arg))
            {
                await channel.SendMessageAsync("💢 `Please enter a card name to search for.`").ConfigureAwait(false);
                return;
            }

            if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.MashapeKey))
            {
                await channel.SendMessageAsync("💢 `Bot owner didn't specify MashapeApiKey. You can't use this functionality.`").ConfigureAwait(false);
                return;
            }

            await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false);
            string response = "";
            using (var http = new HttpClient())
            {
                http.DefaultRequestHeaders.Clear();
                http.DefaultRequestHeaders.Add("X-Mashape-Key", NadekoBot.Credentials.MashapeKey);
                response = await http.GetStringAsync($"https://omgvamp-hearthstone-v1.p.mashape.com/cards/search/{Uri.EscapeUriString(arg)}")
                                        .ConfigureAwait(false);
                try
                {
                    var items = JArray.Parse(response).Shuffle().ToList();
                    var images = new List<Image>();
                    if (items == null)
                        throw new KeyNotFoundException("Cannot find a card by that name");
                    foreach (var item in items.Where(item => item.HasValues && item["img"] != null).Take(4))
                    {
                        using (var sr = await http.GetStreamAsync(item["img"].ToString()))
                        {
                            var imgStream = new MemoryStream();
                            await sr.CopyToAsync(imgStream);
                            imgStream.Position = 0;
                            images.Add(new Image(imgStream));
                        }
                    }
                    string msg = null;
                    if (items.Count > 4)
                    {
                        msg = "⚠ Found over 4 images. Showing random 4.";
                    }
                    var ms = new MemoryStream();
                    images.Merge().SaveAsPng(ms);
                    ms.Position = 0;
                    await channel.SendFileAsync(ms, arg + ".png", msg).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    await channel.SendMessageAsync($"💢 Error {ex.Message}").ConfigureAwait(false);
                }
            }
        }
    protected static string WriteReadCountTable(string outputFile, List<FeatureItemGroup> features, List<string> samples)
    {
      var readFile = Path.ChangeExtension(outputFile, ".read.count");
      using (var sw = new StreamWriter(readFile))
      {
        var reads = (from feature in features
                     from a in feature.GetAlignedLocations()
                     select a.Parent).Distinct().ToGroupDictionary(l => l.Sequence);

        var sequences = (from read in reads
                         orderby read.Value.Sum(l => l.QueryCount) descending
                         select read.Key).ToArray();

        sw.WriteLine("Sequence\t" + samples.Merge("\t"));
        foreach (var seq in sequences)
        {
          sw.Write(seq);
          var dic = reads[seq];
          foreach (var sample in samples)
          {
            var sampleSam = dic.FirstOrDefault(l => l.Sample.Equals(sample));
            if (sampleSam == null)
            {
              sw.Write("\t");
            }
            else
            {
              sw.Write("\t" + sampleSam.QueryCount.ToString());
            }
          }
          sw.WriteLine();
        }
      }

      return readFile;
    }
Example #30
0
    public override IEnumerable<string> Process()
    {
      var files = GetFiles(_options.InputDir);

      Func<string, string> nameFunc;
      if (string.IsNullOrEmpty(_options.NamePattern))
      {
        nameFunc = Path.GetFileNameWithoutExtension;
      }
      else
      {
        nameFunc = n =>
        {
          var match = Regex.Match(n, _options.NamePattern);
          if (match.Success)
          {
            var values = new List<string>();
            for (int i = 1; i < match.Groups.Count; i++)
            {
              values.Add(match.Groups[i].Value);
            }
            return values.Merge("");
          }
          else
          {
            return n;
          }
        };
      };

      var map = files.GroupBy(m =>
      {
        if (_options.Recursion && _options.UseDirName)
        {
          return nameFunc(Path.GetFileName(Path.GetDirectoryName(m)));
        }
        else
        {
          return nameFunc(Path.GetFileName(m));
        }
      }).ToDictionary(n => n.Key);


      var names = (from k in map.Keys
                   orderby k
                   select k).ToList();

      if (_options.AutoFill)
      {
        var nameMap = names.ToDictionary(l => l, l => l);
        Regex number = new Regex(@"(.+?)(\d+)$");

        var numbers = (from n in names
                       let m = number.Match(n)
                       where m.Success
                       select new { OldName = n, Prefix = m.Groups[1].Value, Value = m.Groups[2].Value }).ToList();

        var numberMax = numbers.Max(l => l.Value.Length);
        foreach (var num in numbers)
        {
          if (num.Value.Length != numberMax)
          {
            nameMap[num.OldName] = num.Prefix + new string('0', numberMax - num.Value.Length) + num.Value;
          }
        }

        map = map.ToDictionary(l => nameMap[l.Key], l => l.Value);
        names = (from k in map.Keys
                 orderby k
                 select k).ToList();
      }

      if (File.Exists(_options.MapFile))
      {
        Progress.SetMessage("Reading name map from {0} ...", _options.MapFile);
        var namemap = new MapDataReader(0, 1).ReadFromFile(_options.MapFile);
        map = map.ToDictionary(l => namemap.Data[l.Key].Value, l => l.Value);
        names = (from k in map.Keys
                 orderby k
                 select k).ToList();
      }

      var result = new List<string> { "files => {" };
      foreach (var name in names)
      {
        result.Add(string.Format("  \"{0}\" => [{1}],", name, (from l in map[name] select '"' + Path.GetFullPath(l) + '"').Merge(", ")));
      }
      result.Add("},");

      if (string.IsNullOrEmpty(_options.GroupPattern))
        return result;

      var groupmap = names.GroupBy(n =>
      {
        var match = Regex.Match(n, _options.GroupPattern);
        if (!match.Success)
        {
          throw new Exception(string.Format("Cannot find pattern {0} in file {1}", _options.NamePattern, n));
        }


        var values = new List<string>();
        for (var i = 1; i < match.Groups.Count; i++)
        {
          values.Add(match.Groups[i].Value);
        }
        return values.Merge("");

      });

      var gnames = (from k in groupmap
                    orderby k.Key
                    select k).ToList();

      result.Add("groups => {");
      foreach (var name in gnames)
      {
        result.Add(string.Format("  \"{0}\" => [{1}],", name.Key, (from l in name
                                                                   orderby l
                                                                   select '"' + l + '"').Merge(", ")));
      }
      result.Add("},");

      return result;
    }