public bool CreateListeAbonnements(List<Abonnement> abonnements = null)
        {
            try
            {
                Abonnement = new List<SelectListItem>();
                if (abonnements.IsNotEmpty())
                {
                    foreach (var abonnement in abonnements)
                    {
                        Abonnement.Add(new SelectListItem
                        {
                            Value = abonnement.Id.ToString(),
                            Text = abonnement.Titre
                        });
                    }
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
 public ViewModelRegisterFranchise(List<Abonnement> abonnements = null)
 {
     Abonnement = new List<SelectListItem>();
     if (abonnements.IsNotEmpty())
     {
         CreateListeAbonnements(abonnements);
     }
 }
        public ViewModelFormAddSalon(List<Abonnement> abonnements = null)
        {
            Genre = new List<SelectListItem>
            {
               new SelectListItem { Value = "1", Text = "Homme" },
               new SelectListItem { Value = "2", Text = "Femme" }
            };

            Abonnement = new List<SelectListItem>();
            if (abonnements.IsNotEmpty())
            {
                CreateListeAbonnements(abonnements);
            }
        }
        public void op_IsNotEmpty_IEnumerable()
        {
            var obj = new List<string>
                          {
                              "item"
                          };

            Assert.True(obj.IsNotEmpty());
        }
        public void op_IsNotEmpty_IEnumerableEmpty()
        {
            var obj = new List<string>();

            Assert.False(obj.IsNotEmpty());
        }
 private long GetMinConsumedMessageOffset(IEnumerable<QueueConsumedOffset> queueConsumedOffsets)
 {
     var messageOffsetList = new List<long>();
     foreach (var queueConsumedOffset in queueConsumedOffsets)
     {
         messageOffsetList.Add(GetMessageOffsetByQueueOffset(queueConsumedOffset.Topic, queueConsumedOffset.QueueId, queueConsumedOffset.ConsumedOffset));
     }
     if (messageOffsetList.IsNotEmpty())
     {
         return messageOffsetList.Min();
     }
     return -1L;
 }
Example #7
0
        private void TransformBlock(Block hir, Block xhir, bool insideThreadLoop)
        {
            if (hir == null) return;

            var deepFission = new List<Node>();
            var regions = new List<ReadOnlyCollection<Node>>();
            var curr_region = new List<Node>();
            foreach (var stmt in hir)
            {
                if (_callsToSyncThreads.Contains(stmt as Eval))
                {
                    if (curr_region.IsNotEmpty()) regions.Add(curr_region.ToReadOnly());
                    curr_region = new List<Node>();
                }
                else if (_callsToSyncThreads.Any(c => Set.Intersect(c.Hierarchy(), stmt.MkArray()).IsNotEmpty()))
                {
                    if (curr_region.IsNotEmpty()) regions.Add(curr_region.ToReadOnly());
                    curr_region = new List<Node>();

                    deepFission.Add(stmt);
                    regions.Add(stmt.MkArray().ToReadOnly());
                }
                else
                {
                    curr_region.Add(stmt);
                }
            }
            if (curr_region.IsNotEmpty()) regions.Add(curr_region.ToReadOnly());
            curr_region = null;

            var privateLocals = hir.Locals.Where(l => Alloc(l) == allocPrivate).ToReadOnly();
            var privateUsages = privateLocals.ToDictionary(l => l, 
                l => regions.Where(r => r.UsagesOfLocal(l).IsNotEmpty()).ToReadOnly());
            privateUsages.ForEach(kvp =>
            {
                var needsReplication = kvp.Value.Count() > 1;
                _needsReplication[kvp.Key] = needsReplication;
                if (needsReplication)
                {
                    _xhir.Insert(_lastIndex++, _replicatedInits[kvp.Key]);
                    _xhir.Locals.Add(_replicatedLocals[kvp.Key]);
                }
            });

            foreach (var region in regions)
            {
                var xregion = new Block();

                var needsToBeWrapped = !deepFission.Contains(region.SingleOrDefault2());
                var regionIsInsideThreadLoop = insideThreadLoop || needsToBeWrapped;
                foreach (var stmt in region)
                {
                    if (stmt is Expression)
                    {
                        TransformExpression(((Expression)stmt), xregion, regionIsInsideThreadLoop);
                    }
                    else if (stmt is If)
                    {
                        TransformIf(((If)stmt), xregion, regionIsInsideThreadLoop);
                    }
                    else if (stmt is Loop)
                    {
                        TransformLoop(((Loop)stmt), xregion, regionIsInsideThreadLoop);
                    }
                    else
                    {
                        throw AssertionHelper.Fail();
                    }
                }

                if (needsToBeWrapped && !insideThreadLoop)
                {
                    xhir.Add(new Loop
                    {
                        Init = new Block(new Assign(new Ref(_tids["z"]), new Const(0))),
                        Test = Operator.LessThan(new Ref(_tids["z"]), new Fld(typeof(int3).GetField("Z"), new Prop(typeof(IGridApi).GetProperty("BlockDim"), new Ref(_this), true))),
                        Body = new Block(new Loop
                        {
                            Init = new Block(new Assign(new Ref(_tids["y"]), new Const(0))),
                            Test = Operator.LessThan(new Ref(_tids["y"]), new Fld(typeof(int3).GetField("Y"), new Prop(typeof(IGridApi).GetProperty("BlockDim"), new Ref(_this), true))),
                            Body = new Block(new Loop
                            {
                                Init = new Block(new Assign(new Ref(_tids["x"]), new Const(0))),
                                Test = Operator.LessThan(new Ref(_tids["x"]), new Fld(typeof(int3).GetField("X"), new Prop(typeof(IGridApi).GetProperty("BlockDim"), new Ref(_this), true))),
                                Body = new Block(xregion.Children),
                                Iter = new Block(Operator.PreIncrement(new Ref(_tids["x"]))),
                            }),
                            Iter = new Block(Operator.PreIncrement(new Ref(_tids["y"]))),
                        }),
                        Iter = new Block(Operator.PreIncrement(new Ref(_tids["z"]))),
                    });
                }
                else
                {
                    xhir.AddElements(xregion.Children);
                }
            }

            var locals = hir.Locals.Except(_liftedLocals).ToReadOnly();
            locals.ForEach(l => xhir.Locals.Add(l.DeepClone()));
        }
Example #8
0
        public void ExecuteQuery()
        {
            var requiredAttributes = new List<SelectableAttribute>();

            // attributes selection is possible only when directly querying for type selected in the list
            // otherwise there is no smart/easy way to tell if queried object contains any of currently displayed attributes
            if (querying_selected_type())
            {
                if (CurrentAttributes.Any(x => x.IsSelected))
                {
                    requiredAttributes = CurrentAttributes.Where(x => x.IsSelected).ToList();
                }
                else
                {
                    requiredAttributes = CurrentAttributes.ToList();
                }

                if (requiredAttributes.None(x => x.Attribute.Name == RmResource.AttributeNames.ObjectID.Name))
                {
                    requiredAttributes.Add(CurrentAttributes.Single(x => x.Attribute.Name == RmResource.AttributeNames.ObjectID.Name));
                }
            }

            // empty array if querying for other type than selected => all attributes will be fetched
            var attributesToFetch = new AttributesToFetch(requiredAttributes.Select(x => x.Attribute.Name).ToArray());

            string query = XPath.Replace(Environment.NewLine, string.Empty);

            RmResource[] results = _parent.LongRunningOperation(_parent.loadingIndicator,
                () => _fimClient.EnumerateAll<RmResource>(query, attributesToFetch)
                    .ToArray()
                );

            DataTable table = new DataTable();

            if (results.IsNotEmpty())
            {
                // assuming that all results are of the same type
                var firstResult = results.First();
                var resultType = firstResult.GetResourceType();
                var resultTypeAttributes = firstResult.Attributes;

                SelectableAttribute[] fetchedAttributes;
                if (requiredAttributes.IsNotEmpty())
                {
                    fetchedAttributes = requiredAttributes.ToArray();
                }
                else
                {
                    FetchAttributesForObjectType(resultType);
                    fetchedAttributes = _attributesCache[resultType].ToArray();
                }

                var resultTableColumnNames = new List<string>();

                foreach (var a in resultTypeAttributes.OrderBy(x => x.Key.Name))
                {
                    var selectedAttribute = fetchedAttributes.SingleOrDefault(x => x.Attribute.Name == a.Key.Name);
                    if (selectedAttribute == null)
                    {
                        continue;
                    }

                    var column = table.Columns.Add(selectedAttribute.Attribute.DisplayName);
                    resultTableColumnNames.Add(selectedAttribute.Attribute.Name);

                    // window can detect references by their 'object' type as opposed to 'string' defined for all other fields
                    if (selectedAttribute.Attribute.DataType == RmFactory.RmAttributeType.Reference.ToString())
                    {
                        column.DataType = typeof(object);
                    }
                    else
                    {
                        column.DataType = typeof(string);
                    }
                }

                foreach (var resource in results)
                {
                    var newRowValues = resultTableColumnNames
                        .Select(x =>
                            {
                                if (resource.Attributes.Keys.Any(y => y.Name == x))
                                {
                                    return resource.Attributes.First(y => y.Key.Name == x)
                                        .Value.Value;
                                }
                                else
                                {
                                    return null;
                                }
                            })
                        .ToArray();

                    table.Rows.Add(newRowValues);
                }
            }

            QueriedValues = table;
        }
Example #9
0
        protected CommandLineConfig(String[] s_args)
        {
            Log = Logger.Get(GetType());
            Log.MinLevel = Level.Info;

            if (s_args.Count() == 1 && s_args[0] == "/?")
            {
                Banners.About();
                throw new ConfigException(String.Empty);
            }
            else
            {
                if (s_args.LastOrDefault() == "/verbose")
                {
                    IsVerbose = true;
                    s_args = s_args.SkipLast().ToArray();

                    Info.WriteLine("Detected the \"/verbose\" switch, entering verbose mode.");
                    Log.MinLevel = Level.Debug;

                    Debug.EnsureBlankLine();
                    Debug.Write("Command line args are: ");
                    if (s_args.IsEmpty()) Debug.WriteLine("empty");
                    else Debug.WriteLine("({0} arg{1})", s_args.Count(), s_args.Count() == 1 ? "" : "s");
                    s_args.ForEach((arg, i) => Debug.WriteLine("{0}: {1}", i + 1, arg));
                }

                Debug.EnsureBlankLine();
                Debug.WriteLine("Pre-parsing arguments...");
                var named_args = new Dictionary<String, String>();
                var shortcut_args = new List<String>();
                foreach (var s_arg in s_args)
                {
                    var m = s_arg.Parse("^-(?<name>.*?):(?<value>.*)$");
                    var name = m != null ? m["name"] : null;
                    var value = m != null ? m["value"] : s_arg;
                    if (m != null) Debug.WriteLine("Parsed \"{0}\" as name/value pair: {1} => \"{2}\".", s_arg, name, value);
                    else Debug.WriteLine("Parsed \"{0}\" as raw value.", s_arg);

                    if (name == null)
                    {
                        if (named_args.IsNotEmpty()) throw new ConfigException("Fatal error: shortcut arguments must be specified before named arguments.");
                        else shortcut_args.Add(value);
                    }
                    else
                    {
                        if (named_args.ContainsKey(name)) throw new ConfigException("Fatal error: duplicate argument \"{0}\".", name);
                        else named_args.Add(name, value);
                    }
                }
                Debug.WriteLine("Pre-parse completed: found {0} named argument{1} and {2} shortcut argument{3}.",
                    named_args.Count(), named_args.Count() == 1 ? "" : "s",
                    shortcut_args.Count(), shortcut_args.Count() == 1 ? "" : "s");

                Debug.EnsureBlankLine();
                Debug.WriteLine("Parsing arguments...");

                var parsed_args = new Dictionary<PropertyInfo, Object>();
                if (named_args.IsNotEmpty())
                {
                    Debug.WriteLine("Parsing named arguments...");
                    parsed_args = ParseArgs(named_args);
                }

                if (shortcut_args.IsNotEmpty())
                {
                    Debug.WriteLine("Parsing shortcut arguments...");

                    Dictionary<PropertyInfo, Object> parsed_shortcut_args = null;
                    var shortcuts = GetType().Attrs<ShortcutAttribute>().OrderBy(shortcut => shortcut.Priority);
                    var bind_errors = new Dictionary<String, String>();
                    foreach (var shortcut in shortcuts)
                    {
                        Debug.WriteLine("Considering shortcut schema \"{0}\"...", shortcut.Schema);
                        var words = shortcut.Schema.SplitWords();
                        if (words.Count() != shortcut_args.Count())
                        {
                            var message = String.Format("argument count mismatch.");
                            bind_errors.Add(shortcut.Schema, message);
                            Debug.WriteLine("Schema \"{0}\" won't work: {1}", shortcut.Schema, message);
                            continue;
                        }

                        try { parsed_shortcut_args = ParseArgs(words.Zip(shortcut_args).ToDictionary(t => t.Item1, t => t.Item2)); }
                        catch (ConfigException cex)
                        {
                            bind_errors.Add(shortcut.Schema, cex.Message);
                            Debug.WriteLine(cex.Message);
                            Debug.WriteLine("Schema \"{0}\" won't work: failed to parse arguments.", shortcut.Schema);

                            continue;
                        }

                        var dupes = Set.Intersect(parsed_args.Keys, parsed_shortcut_args.Keys);
                        if (dupes.IsNotEmpty())
                        {
                            var a = dupes.AssertFirst().Attr<ParamAttribute>();
                            var name = named_args.Keys.Single(k => a.Aliases.Contains(k));
                            Debug.WriteLine("Schema \"{0}\" won't work: shortcut argument duplicates parsed argument \"{1}\".", shortcut.Schema, name);
                            parsed_shortcut_args = null;
                            continue;
                        }
                        else
                        {
                            Debug.WriteLine("Schema \"{0}\" works fine, skipping other schemas (if any).", shortcut.Schema);
                            break;
                        }
                    }

                    if (parsed_shortcut_args == null)
                    {
                        var message = "Fatal error: failed to match the shortcuts.";
                        var bind_summary = bind_errors.Select(kvp => String.Format("Failed to match \"{0}\": {1}", kvp.Key, kvp.Value.Replace("Fatal error: ", String.Empty))).StringJoin(Environment.NewLine);
                        if (!IsVerbose) message = message + Environment.NewLine + bind_summary;
                        throw new ConfigException(message);
                    }
                    else
                    {
                        parsed_args.AddElements(parsed_shortcut_args);
                    }
                }

                Debug.WriteLine("Parse completed.");
                Debug.EnsureBlankLine();
                Debug.WriteLine("Setting configuration parameters...");
                var props = this.GetType().GetProperties(BF.AllInstance).Where(p => p.HasAttr<ParamAttribute>()).OrderBy(p => p.Attr<ParamAttribute>().Priority);
                props.ForEach(p =>
                {
                    if (parsed_args.ContainsKey(p))
                    {
                        var value = parsed_args[p];
                        Debug.WriteLine("Resolved %{0} as {1}.", p.Name, value.ToLog());
                        p.SetValue(this, value, null);
                    }
                    else
                    {
                        var p_default = this.GetType().GetProperty("Default" + p.Name, BF.AllStatic);
                        if (p_default == null) throw new ConfigException("Fatal error: parameter \"{0}\" must be specified.");

                        var value = p_default.GetValue(null, null);
                        Debug.WriteLine("Defaulted %{0} to {1}.", p.Name, value.ToLog());
                        p.SetValue(this, value, null);
                    }
                });
                Debug.WriteLine("Configuration parameters successfully set.");
            }
        }
Example #10
0
        public static ControlFlowGraph DoCreateCarcass(IMethodBody cil, out ReadOnlyDictionary<ControlFlowBlock, ReadOnlyCollection<IILOp>> blocks2parts)
        {
            // create the control flow graph
            var cfg = new ControlFlowGraph();

            // partition the code into blocks with continuous control flow
            // todo. support switches and protected regions
            var targets = new HashSet<IILOp>(cil.OfType<Branch>().Select(br => br.Target));
            var l_partitions = new List<ReadOnlyCollection<IILOp>>();
            var l_partition = new List<IILOp>();
            Action qualifyPartition = () => { if (l_partition.IsNotEmpty()) { l_partitions.Add(l_partition.ToReadOnly()); l_partition = new List<IILOp>(); } };
            foreach (var op in cil)
            {
                if (op is Branch || op is Ret) qualifyPartition();
                else 
                {
                    if (targets.Contains(op)) qualifyPartition();
                    l_partition.Add(op);
                    if (op is Throw) qualifyPartition();
                }
            }
            qualifyPartition();
            var partitions = l_partitions.ToReadOnly();

            // create blocks and map those to ops and partitions
            blocks2parts = partitions.ToDictionary(p => new ControlFlowBlock(), p => p).ToReadOnly();
            blocks2parts.ForEach(kvp => cfg.AddVertex(kvp.Key));
            var op2blocks = new Dictionary<IILOp, ControlFlowBlock>();
            blocks2parts.ForEach(kvp => kvp.Value.ForEach(op => op2blocks.Add(op, kvp.Key)));
            cil.ForEach(op => { if (!op2blocks.ContainsKey(op)) op2blocks.Add(op, null); });

            // prepare to link the blocks
            Action<IILOp, IILOp, CilPredicateType?> link = (op1, op2, cil_pred) =>
            {
                var source = op1 == null ? cfg.Start : op2blocks[op1];
                var target = op2 == null ? cfg.Finish : op2blocks[op2];
                var hir_pred = cil_pred == null ? (HirPredicateType?)null :
                    (HirPredicateType)Enum.Parse(typeof(HirPredicateType), cil_pred.Value.ToString());
                cfg.AddEdge(new ControlFlowEdge(source, target, hir_pred));
            };

            // link the blocks (down from 300+ LOC to this simple loop =))
            if (cil.IsEmpty()) link(null, null, null);
            foreach (var op in cil)
            {
                // todo. support switches here
                if (op is Switch) throw AssertionHelper.Fail();

                // todo. support general case of control flow
                // n0te. throw needs something on stack, so br > throw is impossible
                Func<IILOp, bool> isJmp = op1 => op1 is Ret || op1 is Branch;
                if (isJmp(op) && isJmp(op.Prev)) continue;

                if (isJmp(op))
                {
                    Func<IILOp, CilPredicateType?> pred = op1 => op1 is Ret ? null : op1 is Branch ? ((Branch)op1).PredicateType : ((Func<CilPredicateType?>)(() => { throw AssertionHelper.Fail(); }))();
                    Func<IILOp, bool> uncond = op1 => isJmp(op1) && pred(op1) == null;
                    Func<IILOp, bool> cond = op1 => isJmp(op1) && pred(op1) != null;
                    Func<IILOp, IILOp> target = null; target = op1 => 
                        op1 is Ret ? null : op1 is Branch ? target(((Branch)op1).Target) : op1;

                    (target(op) is Branch).AssertFalse();
                    if (target(op) is Ret) link(op.Prev, null, pred(op));
                    else link(op.Prev, target(op), pred(op));

                    isJmp(op.Next).AssertImplies(uncond(op.Next));
                    if (cond(op)) link(op.Prev, target(op.Next), pred(op).Negate());
                }
                else if (op is Throw)
                {
                    // do nothing - throw doesn't create links
                }
                else
                {
                    if (op.Prev == null) link(null, op, null);
                    if (isJmp(op.Next)) continue;

                    var blk = op2blocks.GetOrDefault(op);
                    var blk_next = op2blocks.GetOrDefault(op.Next);
                    if (blk != blk_next) link(op, op.Next, null);
                }
            }

            // yield control to the next step of the pipeline
            return cfg;
        }