/// <summary> /// Parses a the value for the header Content-Disposition to a <see cref="ContentDisposition"/> object. /// </summary> /// <param name="headerValue">The value to be parsed</param> /// <returns>A <see cref="ContentDisposition"/> object</returns> /// <exception cref="ArgumentNullException">If <paramref name="headerValue"/> is <see langword="null"/></exception> public static ContentDisposition ParseContentDisposition(string headerValue) { if (headerValue == null) { throw new ArgumentNullException("headerValue"); } // See http://www.ietf.org/rfc/rfc2183.txt for RFC definition // Create empty ContentDisposition - we will fill in details as we read them ContentDisposition contentDisposition = new ContentDisposition(); // Now decode the parameters List <KeyValuePair <string, string> > parameters = Rfc2231Decoder.Decode(headerValue); foreach (KeyValuePair <string, string> keyValuePair in parameters) { string key = keyValuePair.Key.ToUpperInvariant().Trim(); string value = keyValuePair.Value; switch (key) { case "": // This is the DispisitionType - it has no key since it is the first one // and has no = in it. contentDisposition.DispositionType = value; break; // The correct name of the parameter is filename, but some emails also contains the parameter // name, which also holds the name of the file. Therefore we use both names for the same field. case "NAME": case "FILENAME": // The filename might be in qoutes, and it might be encoded-word encoded contentDisposition.FileName = EncodedWord.Decode(StringUtility.RemoveQuotesIfAny(value)); break; case "CREATION-DATE": // Notice that we need to create a new DateTime because of a failure in .NET 2.0. // The failure is: you cannot give contentDisposition a DateTime with a Kind of UTC // It will set the CreationDate correctly, but when trying to read it out it will throw an exception. // It is the same with ModificationDate and ReadDate. // This is fixed in 4.0 - maybe in 3.0 too. // Therefore we create a new DateTime which have a DateTimeKind set to unspecified DateTime creationDate = new DateTime(Rfc2822DateTime.StringToDate(StringUtility.RemoveQuotesIfAny(value)).Ticks); contentDisposition.CreationDate = creationDate; break; case "MODIFICATION-DATE": DateTime midificationDate = new DateTime(Rfc2822DateTime.StringToDate(StringUtility.RemoveQuotesIfAny(value)).Ticks); contentDisposition.ModificationDate = midificationDate; break; case "READ-DATE": DateTime readDate = new DateTime(Rfc2822DateTime.StringToDate(StringUtility.RemoveQuotesIfAny(value)).Ticks); contentDisposition.ReadDate = readDate; break; case "SIZE": contentDisposition.Size = int.Parse(StringUtility.RemoveQuotesIfAny(value), CultureInfo.InvariantCulture); break; default: if (key.StartsWith("X-")) { contentDisposition.Parameters.Add(key, StringUtility.RemoveQuotesIfAny(value)); break; } throw new ArgumentException("Unknown parameter in Content-Disposition. Ask developer to fix! Parameter: " + key); } } return(contentDisposition); }
public void setRoomID(int roomID) { mRoomIDLabel.setLabel(StringUtility.intToString(roomID)); }
/// <inheritdoc /> public IReadOnlyList <IChangeEntryData> GetAllEntries(string query = null) { // Filter items by search query query = StringUtility.TrimAndToLower(query); return(entryData.Values.Where(e => e.Entry.Path.ToLower().Contains(query)).ToList()); }
/// <summary> /// 取得重新載入用的連結內容 /// </summary> private string GetLinkUrlToReload(int pageCode) { //設定網址中的參數值 return(StringUtility.SetParaValueInUrl(linkUrlToReload, pageCodeParaName, pageCode.ToString())); }
public static float calculateFloat(string str) { // 判断字符串是否含有非法字符,也就是除数字,小数点,运算符以外的字符 str = StringUtility.checkFloatString(str, "+-*/()"); // 判断左右括号数量是否相等 int leftBracketCount = 0; int rightBracketCount = 0; int newStrLen = str.Length; for (int i = 0; i < newStrLen; ++i) { if (str[i] == '(') { ++leftBracketCount; } else if (str[i] == ')') { ++rightBracketCount; } } if (leftBracketCount != rightBracketCount) { // 计算错误,左右括号数量不对应 return(0); } // 循环判断传入的字符串有没有括号 while (true) { // 先判断有没有括号,如果有括号就先算括号里的,如果没有就退出while循环 if (str.IndexOf("(") != -1 || str.IndexOf(")") != -1) { int curpos = str.LastIndexOf("("); string strInBracket = str.Substring(curpos + 1, str.Length - curpos - 1); strInBracket = strInBracket.Substring(0, strInBracket.IndexOf(")")); float ret = calculateFloat(strInBracket); // 如果括号中的计算结果是负数,则标记为负数 bool isMinus = false; if (ret < 0) { ret = -ret; isMinus = true; } // 将括号中的计算结果替换原来的表达式,包括括号也一起替换 string floatStr = (Math.Round(ret, 4)).ToString(); str = StringUtility.strReplace(str, curpos, curpos + strInBracket.Length + 2, floatStr); byte[] strchar = BinaryUtility.stringToBytes(str, Encoding.ASCII); if (isMinus) { // 如果括号中计算出来是负数,则将负号提取出来,将左边的第一个加减号改为相反的符号 bool changeMark = false; for (int i = curpos - 1; i >= 0; --i) { // 找到第一个+号,则直接改为减号,然后退出遍历 if (strchar[i] == '+') { strchar[i] = (byte)'-'; str = BinaryUtility.bytesToString(strchar, Encoding.ASCII); changeMark = true; break; } // 找到第一个减号,如果减号的左边有数字,则直接改为+号 // 如果减号的左边不是数字,则该减号是负号,将减号去掉, else if (strchar[i] == '-') { if (strchar[i - 1] >= '0' && strchar[i - 1] <= '9') { strchar[i] = (byte)'+'; str = BinaryUtility.bytesToString(strchar, Encoding.ASCII); } else { str = StringUtility.strReplace(str, i, i + 1, ""); } changeMark = true; break; } } // 如果遍历完了还没有找到可以替换的符号,则在表达式最前面加一个负号 if (!changeMark) { str = "-" + str; } } } else { break; } } List <float> numbers = new List <float>(); List <char> factors = new List <char>(); // 表示上一个运算符的下标+1 int beginpos = 0; for (int i = 0; i < str.Length; ++i) { // 遍历到了最后一个字符,则直接把最后一个数字放入列表,然后退出循环 if (i == str.Length - 1) { string num = str.Substring(beginpos, str.Length - beginpos); float fNum = float.Parse(num); numbers.Add(fNum); break; } // 找到第一个运算符 if ((str[i] < '0' || str[i] > '9') && str[i] != '.') { if (i != 0) { string num = str.Substring(beginpos, i - beginpos); float fNum = float.Parse(num); numbers.Add(fNum); } // 如果在表达式的开始就发现了运算符,则表示第一个数是负数,那就处理为0减去这个数的绝对值 else { numbers.Add(0); } factors.Add(str[i]); beginpos = i + 1; } } if (factors.Count + 1 != numbers.Count) { // 计算错误,运算符与数字数量不符 return(0); } // 现在开始计算表达式,按照运算优先级,先计算乘除和取余 while (true) { // 表示是否还有乘除表达式 bool hasMS = false; for (int i = 0; i < (int)factors.Count; ++i) { // 先遍历到哪个就先计算哪个 if (factors[i] == '*' || factors[i] == '/') { // 第一个运算数的下标与运算符的下标是相同的 float num1 = numbers[i]; float num2 = numbers[i + 1]; float num3 = 0.0f; if (factors[i] == '*') { num3 = num1 * num2; } else if (factors[i] == '/') { num3 = num1 / num2; } // 删除第i + 1个数,然后将第i个数替换为计算结果 numbers.RemoveAt(i + 1); if (numbers.Count == 0) { // 计算错误 return(0); } numbers[i] = num3; // 删除第i个运算符 factors.RemoveAt(i); hasMS = true; break; } } if (!hasMS) { break; } } // 再计算加减法 while (true) { if (factors.Count == 0) { break; } if (factors[0] == '+' || factors[0] == '-') { // 第一个运算数的下标与运算符的下标是相同的 float num1 = numbers[0]; float num2 = numbers[1]; float num3 = 0.0f; if (factors[0] == '+') { num3 = num1 + num2; } else if (factors[0] == '-') { num3 = num1 - num2; } // 删除第1个数,然后将第0个数替换为计算结果 numbers.RemoveAt(1); if (numbers.Count == 0) { // 计算错误 return(0); } numbers[0] = num3; // 删除第0个运算符 factors.RemoveAt(0); } } if (numbers.Count != 1) { // 计算错误 return(0); } else { return(numbers[0]); } }
public Result <OlescUser> ChangePassword(string username, string password) { int NumOfRecords = 0; /* Create the result object ; which will be returned at the end * of the method */ Result <OlescUser> result = new Result <OlescUser>(); /* Database Connection */ OlescEntities dbCon = null; try { /* Database Connection */ dbCon = new OlescEntities(); OlescUser user = dbCon.OlescUsers.Where(u => u.Email.Equals(username)).FirstOrDefault(); if (user != null) { password = StringUtility.CreateMD5Hash(password); if (!user.Password.Equals(password)) { user.Password = password; NumOfRecords = dbCon.SaveChanges(); /* if there is at least 1 record saved -> true, if not -> false */ if (NumOfRecords >= 1) { result.isSuccess = true; result.message = "Password changed successfully"; NotificationManagementService nms = new NotificationManagementService(); /* Email notification service */ /* Conent */ String emailContent; emailContent = "Dear " + user.UserProfile.FirstName; emailContent += "\nThis email is notify you that your password has been changed."; emailContent += "\nIf you haven't changed your password, please reset your password in the login page."; emailContent += "\n\nRegards,\nOLESC Team"; /* Subject*/ String emailSubject; emailSubject = "Your Password has been Changed"; /* Sending the email */ nms.Notify(user.Email, null, null, emailSubject, emailContent); } else { result.isSuccess = false; result.message = "Error changing password"; } } else { result.isSuccess = false; result.message = "Old password is the same as the new password"; } } else { result.isSuccess = false; result.message = "User does not exist"; } } catch (Exception e) { result.isSuccess = false; result.message = e.Message; result.resultObject = null; } finally { if (dbCon != null) { /* Same as in Java dbCon.Close() */ dbCon.Dispose(); } } return(result); }
private static IEnumerable <MemberDeclarationSyntax> CreateMembers(IEnumerable <CodeFixDescriptor> codeFixes, IComparer <string> comparer) { yield return(PropertyDeclaration( Modifiers.ProtectedOverride(), PredefinedStringType(), Identifier("DisabledByDefault"), AccessorList(AutoGetAccessorDeclaration()), ParseExpression( "$\"" + string.Join(",", codeFixes .Where(f => !f.IsEnabledByDefault) .OrderBy(f => f.Identifier, comparer) .Select(f => $"{{CodeFixIdentifiers.{f.Identifier}}}")) + "\""))); yield return(PropertyDeclaration( Modifiers.ProtectedOverride(), PredefinedStringType(), Identifier("MaxId"), AccessorList(AutoGetAccessorDeclaration()), ParseExpression($"CodeFixIdentifiers.{codeFixes.OrderBy(f => f.Id, comparer).Last().Identifier}"))); yield return(MethodDeclaration( Modifiers.ProtectedOverride(), VoidType(), Identifier("Fill"), ParameterList(Parameter(ParseTypeName("ICollection<BaseModel>"), Identifier("codeFixes"))), Block( SingletonList(ExpressionStatement(ParseExpression("codeFixes.Clear()"))) .AddRange(codeFixes .OrderBy(f => f.Id, comparer) .Select(codeFix => { return ExpressionStatement( ParseExpression($"codeFixes.Add(new BaseModel(CodeFixIdentifiers.{codeFix.Identifier}, \"{StringUtility.EscapeQuote(codeFix.Title)} (fixes {string.Join(", ", codeFix.FixableDiagnosticIds)})\", IsEnabled(CodeFixIdentifiers.{codeFix.Identifier})))")); }))))); }
STModel ConvertReplace(replace repl) { //create a disjunction of all the regexes //each case terminated by the identifier int K = 0; //max pattern length //HashSet<int> finalReplacers = new HashSet<int>(); //for efficieny keep lookup tables of character predicates to sets Dictionary <Expr, BDD> predLookup = new Dictionary <Expr, BDD>(); Automaton <BDD> previouspatterns = Automaton <BDD> .MkEmpty(css); Automaton <BV2> N = Automaton <BV2> .MkFull(css2); var hasNoEndAnchor = new HashSet <int>(); for (int i = 0; i < repl.CaseCount; i++) { replacecase rcase = repl.GetCase(i); var pat = "^" + rcase.Pattern.val; var M = css.Convert("^" + rcase.Pattern.val, System.Text.RegularExpressions.RegexOptions.Singleline).Determinize(css).Minimize(css); #region check that the pattern is a feasible nonempty sequence if (M.IsEmpty) { throw new BekParseException(string.Format("Semantic error: pattern {0} is infeasible.", rcase.Pattern.ToString())); } int _K; if (!M.CheckIfSequence(out _K)) { throw new BekParseException(string.Format("Semantic error: pattern {0} is not a sequence.", rcase.Pattern.ToString())); } if (_K == 0) { throw new BekParseException(string.Format("Semantic error: empty pattern {0} is not allowed.", rcase.Pattern.ToString())); } K = Math.Max(_K, K); #endregion var liftedMoves = new List <Move <BV2> >(); var st = M.InitialState; var newFinalState = M.MaxState + 1; var endAnchor = css.MkCharConstraint((char)i); //lift the moves to BV2 moves, adding end-markers while (!M.IsFinalState(st)) { var mv = M.GetMoveFrom(st); var pair_cond = new BV2(mv.Label, css.False); var liftedMove = new Move <BV2>(mv.SourceState, mv.TargetState, pair_cond); liftedMoves.Add(liftedMove); if (M.IsFinalState(mv.TargetState)) { var end_cond = new BV2(css.False, endAnchor); if (M.IsLoopState(mv.TargetState)) { hasNoEndAnchor.Add(i); //var loop_cond = css2.MkNot(end_cond); //var loopMove = new Move<BV2>(mv.TargetState, mv.TargetState, loop_cond); //liftedMoves.Add(loopMove); } var endMove = new Move <BV2>(mv.TargetState, newFinalState, end_cond); liftedMoves.Add(endMove); } st = mv.TargetState; } var N_i = Automaton <BV2> .Create(css2, M.InitialState, new int[] { newFinalState }, liftedMoves); //Microsoft.Automata.Visualizer.ToDot(N_i, "N" + i , "C:\\Automata\\Docs\\Papers\\Bex\\N" + i +".dot", x => "(" + css.PrettyPrint(x.First) + "," + css.PrettyPrint(x.Second) + ")"); N = N.Intersect(N_i.Complement(css2), css2); #region other approach: disallow overlapping patterns //Visualizer.ShowGraph(M2.Complement(css2), "M2", lab => { return "<" + css.PrettyPrint(lab.First) + "," + css.PrettyPrint(lab.Second) + ">"; }); //note: keep here the original pattern, add only the start anchor to synchronize prefixes //var thispattern = css.Convert("^" + rcase.Pattern.val, System.Text.RegularExpressions.RegexOptions.Singleline).Determinize(css).Minimize(css); //var thispattern1 = thispattern.Minus(previouspatterns, css); //Visualizer.ShowGraph(thispattern1, "test", css.PrettyPrint); //#region check that thispattern does not overlap with any previous pattern //var common = thispattern.Intersect(previouspatterns, css); //if (!(common.IsEmpty)) //{ // int j = 0; // while ((j < i) && css.Convert("^" + repl.GetCase(j).Pattern.val, // System.Text.RegularExpressions.RegexOptions.Singleline).Determinize(css).Intersect(thispattern, css).IsEmpty) // j++; // throw new BekParseException(rcase.id.line, rcase.id.pos, string.Format("Semantic error: pattern {0} overlaps pattern {1}.", // rcase.Pattern.ToString(), repl.GetCase(j).Pattern.ToString())); //} //previouspatterns = previouspatterns.Union(thispattern).RemoveEpsilons(css.MkOr); //TBD: better union //#endregion #endregion } N = N.Complement(css2).Minimize(css2); //Microsoft.Automata.Visualizer.ShowGraph(N, "N", x => "<" + css.PrettyPrint(x.First) + "," + css.PrettyPrint(x.Second) + ">"); //Microsoft.Automata.Visualizer.ToDot(N, "N","C:\\Automata\\Docs\\Papers\\Bex\\N.dot", x => "(" + css.PrettyPrint(x.First) + "," + css.PrettyPrint(x.Second) + ")"); var D = new Dictionary <int, int>(); var G = new Dictionary <int, BDD>(); #region compute distance from initial state and compute guard unions var S = new Stack <int>(); D[N.InitialState] = 0; G[N.InitialState] = css.False; S.Push(N.InitialState); while (S.Count > 0) { var q = S.Pop(); foreach (var move in N.GetMovesFrom(q)) { G[q] = css.MkOr(G[q], move.Label.First); var p = move.TargetState; var d = D[q] + 1; if (!(N.IsFinalState(p)) && !D.ContainsKey(p)) { D[p] = d; G[p] = css.False; S.Push(p); } if (!(N.IsFinalState(p)) && D[p] != d) { throw new BekException(string.Format("Unexpected error, inconsitent distances {0} and {1} to state {2}", D[p], d, p)); } } } #endregion #region check that outputs do not have out of bound variables foreach (var fs in N.GetFinalStates()) { foreach (var move in N.GetMovesTo(fs)) { if (move.Label.Second.IsEmpty) { throw new BekException("Internal error: missing end anchor"); } //if (!css.IsSingleton(move.Condition.Second)) //{ // var one = (int)css.GetMin(move.Condition.Second); // var two = (int)css.GetMax(move.Condition.Second); // throw new BekParseException(repl.GetCase(two).id.line, repl.GetCase(two).id.pos, string.Format("Ambiguous replacement patterns {0} and {1}.", repl.GetCase(one).Pattern, repl.GetCase(two).Pattern)); //} //pick the minimum case identifer when there are several, essentially pick the earliest case int id = (int)css.GetMin(move.Label.Second); int distFromRoot = D[move.SourceState]; var e = repl.GetCase(id).Output; HashSet <int> vars = new HashSet <int>(); foreach (var v in e.GetBoundVars()) { if (v.GetVarId() >= distFromRoot) { throw new BekParseException(v.line, v.pos, string.Format("Syntax error: pattern variable '{0}' is out ouf bounds, valid range is from '#0' to '#{1}']", v.name, distFromRoot - 1)); } } } } #endregion int finalState = N.FinalState; K = K - 1; //this many registers are needed var zeroChar = stb.Solver.MkCharExpr('\0'); var STmoves = new List <Move <Rule <Expr> > >(); var STstates = new HashSet <int>(); var STdelta = new Dictionary <int, List <Move <Rule <Expr> > > >(); var STdeltaInv = new Dictionary <int, List <Move <Rule <Expr> > > >(); var FinalSTstates = new HashSet <int>(); var STdeletedMoves = new HashSet <Move <Rule <Expr> > >(); Action <Move <Rule <Expr> > > STmovesAdd = r => { var p = r.SourceState; var q = r.TargetState; STmoves.Add(r); if (STstates.Add(p)) { STdelta[p] = new List <Move <Rule <Expr> > >(); STdeltaInv[p] = new List <Move <Rule <Expr> > >(); } if (STstates.Add(q)) { STdelta[q] = new List <Move <Rule <Expr> > >(); STdeltaInv[q] = new List <Move <Rule <Expr> > >(); } if (r.Label.IsFinal) { FinalSTstates.Add(p); } STdelta[p].Add(r); STdeltaInv[q].Add(r); }; var regsorts = new Sort[K]; for (int j = 0; j < K; j++) { regsorts[j] = stb.Solver.CharSort; } var regsort = stb.Solver.MkTupleSort(regsorts); var regvar = stb.MkRegister(regsort); var initialRegisterValues = new Expr[K]; for (int j = 0; j < K; j++) { initialRegisterValues[j] = zeroChar; } var initialRegister = stb.Solver.MkTuple(initialRegisterValues); Predicate <int> IsCaseEndState = s => { return(N.OutDegree(s) == 1 && N.GetMoveFrom(s).Label.First.IsEmpty); }; #region compute the forward moves and the completion moves var V = new HashSet <int>(); S.Push(N.InitialState); while (S.Count > 0) { var p = S.Pop(); #region forward moves foreach (var move in N.GetMovesFrom(p)) { var q = move.TargetState; //this move occurs if p has both an end-move and a non-end-move //note that if p is an case-end-state then it is never pushed to S if (N.IsFinalState(q)) { continue; } var distance = D[p]; Expr chExpr; Expr chPred; MkExprPred(move.Label.First, out chExpr, out chPred); predLookup[chPred] = move.Label.First; Expr[] regUpds = new Expr[K]; for (int i = 0; i < K; i++) { if (i == distance) { regUpds[i] = chExpr; } else //if (i < distance) { regUpds[i] = stb.Solver.MkProj(i, regvar); } //else // regUpds[i] = zeroChar; } Expr regExpr = stb.Solver.MkTuple(regUpds); var moveST = stb.MkRule(p, q, chPred, regExpr); //there are no yields STmovesAdd(moveST); if (V.Add(q) && !IsCaseEndState(q)) { S.Push(q); } } #endregion #region completion is only enabled if there exists an else case if (repl.HasElseCase) { var guards = G[p]; var guards0 = G[N.InitialState]; #region nonmatching cases to the initial state var nomatch = css.MkNot(css.MkOr(guards, guards0)); if (!nomatch.IsEmpty) { Expr chExpr; Expr nomatchPred; MkExprPred(nomatch, out chExpr, out nomatchPred); predLookup[nomatchPred] = nomatch; var else_yields_list = new List <Expr>(); for (int i = 0; i < D[p]; i++) { else_yields_list.AddRange(GetElseYieldInstance(repl.ElseOutput, stb.Solver.MkProj(i, regvar))); } else_yields_list.AddRange(GetElseYieldInstance(repl.ElseOutput, stb.MkInputVariable(stb.Solver.CharSort))); var else_yields = else_yields_list.ToArray(); var resetMove = stb.MkRule(p, N.InitialState, nomatchPred, initialRegister, else_yields); STmovesAdd(resetMove); } #endregion #region matching cases via the initial state foreach (var move0 in N.GetMovesFrom(N.InitialState)) { var g0 = move0.Label.First; var match = css.MkAnd(css.MkNot(guards), g0); if (!match.IsEmpty) { Expr chExpr; Expr matchPred; MkExprPred(match, out chExpr, out matchPred); predLookup[matchPred] = match; var resetYieldsList = new List <Expr>(); //for all unprocessed inputs produce the output yield according to the else case for (int i = 0; i < D[p]; i++) { resetYieldsList.AddRange(GetElseYieldInstance(repl.ElseOutput, stb.Solver.MkProj(i, regvar))); } var resetYields = resetYieldsList.ToArray(); Expr[] regupd = new Expr[K]; regupd[0] = chExpr; for (int j = 1; j < K; j++) { regupd[j] = zeroChar; } var regupdExpr = stb.Solver.MkTuple(regupd); var resetMove = stb.MkRule(p, move0.TargetState, matchPred, regupdExpr, resetYields); STmovesAdd(resetMove); } } #endregion } #endregion } #endregion foreach (var last_move in N.GetMovesTo(N.FinalState)) { //i is the case identifier int i = (int)css.GetMin(last_move.Label.Second); if (hasNoEndAnchor.Contains(i)) { #region this corresponds to looping back to the initial state on the given input //the final outputs produced after a successful pattern match #region compute the output terms int distFromRoot = D[last_move.SourceState]; Func <ident, Expr> registerMap = id => { // --- already checked I think --- if (!id.IsVar || id.GetVarId() >= distFromRoot) { throw new BekParseException(id.Line, id.Pos, string.Format("illeagal variable '{0}' in output", id.name)); } if (id.GetVarId() == distFromRoot - 1) //the last reg update refers to the current variable { return(stb.MkInputVariable(stb.Solver.CharSort)); } else { return(stb.Solver.MkProj(id.GetVarId(), regvar)); } }; Expr[] yields; var outp = repl.GetCase(i).Output; if (outp is strconst) { var s = ((strconst)outp).val; yields = Array.ConvertAll(s.ToCharArray(), c => this.str_handler.iter_handler.expr_handler.Convert(new charconst("'" + StringUtility.Escape(c) + "'"), registerMap)); } else //must be an explicit list construct { if (!(outp is functioncall) || !((functioncall)outp).id.name.Equals("string")) { throw new BekParseException("Invalid pattern output."); } var s = ((functioncall)outp).args; yields = Array.ConvertAll(s.ToArray(), e => this.str_handler.iter_handler.expr_handler.Convert(e, registerMap)); } #endregion //shortcut all the incoming transitions to the initial state foreach (var move in STdeltaInv[last_move.SourceState]) { //go to the initial state, i.e. the matching raps around int p = move.SourceState; int q0 = N.InitialState; List <Expr> yields1 = new List <Expr>(move.Label.Yields); //incoming yields are yields1.AddRange(yields); var rule = stb.MkRule(p, q0, move.Label.Guard, initialRegister, yields1.ToArray()); STmovesAdd(rule); //STdeletedMoves.Add(move); STmoves.Remove(move); //the move has been replaced } #endregion } else { #region this is the end of the input stream case #region compute the output terms int distFromRoot = D[last_move.SourceState]; Func <ident, Expr> registerMap = id => { if (!id.IsVar || id.GetVarId() >= distFromRoot) { throw new BekParseException(id.Line, id.Pos, string.Format("illeagal variable '{0}' in output", id.name)); } return(stb.Solver.MkProj(id.GetVarId(), regvar)); }; Expr[] yields; var outp = repl.GetCase(i).Output; if (outp is strconst) { var s = ((strconst)outp).val; yields = Array.ConvertAll(s.ToCharArray(), c => this.str_handler.iter_handler.expr_handler.Convert(new charconst("'" + c.ToString() + "'"), registerMap)); } else //must be an explicit list construct { if (!(outp is functioncall) || !((functioncall)outp).id.name.Equals("string")) { throw new BekParseException("Invalid pattern output."); } var s = ((functioncall)outp).args; yields = Array.ConvertAll(s.ToArray(), e => this.str_handler.iter_handler.expr_handler.Convert(e, registerMap)); } #endregion int p = last_move.SourceState; var rule = stb.MkFinalOutput(p, stb.Solver.True, yields); STmovesAdd(rule); #endregion } } if (repl.HasElseCase) { #region final completion (upon end of input) for all non-final states foreach (var p in STstates) { if (!FinalSTstates.Contains(p) && !IsCaseEndState(p)) //there is no final rule for p, so add the default one { Expr[] finalYields; finalYields = new Expr[D[p]]; for (int i = 0; i < finalYields.Length; i++) { finalYields[i] = stb.Solver.MkProj(i, regvar); } var p_finalMove = stb.MkFinalOutput(p, stb.Solver.True, finalYields); STmovesAdd(p_finalMove); } } #endregion } else { //in this case there is a final rule from the initial state var q0_finalMove = stb.MkFinalOutput(N.InitialState, stb.Solver.True); STmovesAdd(q0_finalMove); } var resST = stb.MkST(name, initialRegister, stb.Solver.CharSort, stb.Solver.CharSort, regsort, N.InitialState, STmoves); var resSTb = new STModel(stb.Solver, name, stb.Solver.CharSort, stb.Solver.CharSort, regsort, initialRegister, N.InitialState); //create STb from the moves, we use here the knowledge that the ST is deterministic //we also use the lookuptable of conditions to eliminate dead code //resST.ShowGraph(); //resST.ToDot("C:\\Automata\\Docs\\Papers\\Bex\\B.dot"); #region compute the rules of the resulting STb //V.Clear(); //S.Push(resST.InitialState); //V.Add(resST.InitialState); foreach (var st in resST.GetStates()) { var condUnion = css.False; var st_moves = new List <Move <Rule <Expr> > >(); foreach (var move in resST.GetNonFinalMovesFrom(st)) { condUnion = css.MkOr(condUnion, predLookup[move.Label.Guard]); st_moves.Add(move); } STbRule <Expr> st_rule; if (st_moves.Count > 0) { //collect all rules with singleton guards and put them into a switch statement var st_rules1 = new List <KeyValuePair <Expr, STbRule <Expr> > >(); var st_moves2 = new List <Move <Rule <Expr> > >(); foreach (var move in st_moves) { if (css.ComputeDomainSize(predLookup[move.Label.Guard]) == 1) { var v = stb.Solver.MkNumeral(css.Choose(predLookup[move.Label.Guard]), stb.Solver.CharSort); var r = new BaseRule <Expr>(new Sequence <Expr>(move.Label.Yields), move.Label.Update, move.TargetState); st_rules1.Add(new KeyValuePair <Expr, STbRule <Expr> >(v, r)); } else { st_moves2.Add(move); } } STbRule <Expr> defaultcase = new UndefRule <Expr>("reject"); //make st_moves2 into an ite rule if (st_moves2.Count > 0) { for (int j = st_moves2.Count - 1; j >= 0; j--) { var r = new BaseRule <Expr>(new Sequence <Expr>(st_moves2[j].Label.Yields), st_moves2[j].Label.Update, st_moves2[j].TargetState); if (j == (st_moves2.Count - 1) && condUnion.IsFull) { defaultcase = r; } else { defaultcase = new IteRule <Expr>(st_moves2[j].Label.Guard, r, defaultcase); } } } else if (condUnion.IsFull) { defaultcase = st_rules1[st_rules1.Count - 1].Value; st_rules1.RemoveAt(st_rules1.Count - 1); } if (st_rules1.Count == 0) { st_rule = defaultcase; } else { st_rule = new SwitchRule <Expr>(stb.MkInputVariable(stb.Solver.CharSort), defaultcase, st_rules1.ToArray()); } } else { st_rule = new UndefRule <Expr>("reject"); } resSTb.AssignRule(st, st_rule); var st_finalrules = new List <Rule <Expr> >(resST.GetFinalRules(st)); if (st_finalrules.Count > 1) { throw new BekException("Unexpected error: multiple final rules per state."); } if (st_finalrules.Count > 0) { resSTb.AssignFinalRule(st, new BaseRule <Expr>(new Sequence <Expr>(st_finalrules[0].Yields), initialRegister, st)); } } resSTb.ST = resST; resST.STb = resSTb; #endregion return(resSTb); }
public void PrintFormatted(string text, params object[] args) { if (text is null) { throw new ArgumentNullException(nameof(text)); } int currentArgument = 0; int currentCharacter = 0; while (currentCharacter < text.Length) { char c = text[currentCharacter]; if (c != '%') { this.DisplayCharacter(c); } else { currentCharacter++; c = text[currentCharacter]; switch (c) { case 's': { // string string arg = (string)args[currentArgument]; currentArgument++; this.DisplayString(arg); break; } case 'd': { // decimal short arg = short.Parse(args[currentArgument].ToString(), NumberStyles.Integer, CultureInfo.CurrentCulture); currentArgument++; if (arg < 0) { this.DisplayCharacter('-'); this.DisplayString(StringUtility.NumberToString(arg * -1)); } else { this.DisplayString(StringUtility.NumberToString(arg)); } break; } case 'u': { // unsigned decimal ushort arg = ushort.Parse(args[currentArgument].ToString(), NumberStyles.Integer, CultureInfo.CurrentCulture); currentArgument++; this.DisplayString(StringUtility.NumberToString(arg)); break; } case 'x': { // hex number ushort arg = ushort.Parse(args[currentArgument].ToString(), NumberStyles.Integer, CultureInfo.CurrentCulture); currentArgument++; this.DisplayString(StringUtility.NumberToHexString(arg)); break; } case 'c': { // character char arg = '\0'; string s = args[currentArgument].ToString(); if (s.Length > 0) { arg = s[0]; } currentArgument++; this.DisplayCharacter(arg); break; } default: { // not recognised this.DisplayCharacter('%'); currentCharacter--; break; } } } currentCharacter++; } this.UpdateTextRegion(); }
private void Display(string text, StringBuilder message) { int textIndex = 0; while (textIndex < text.Length && this.MessageState.TextHeight <= (HeightMax - 1)) { while (this.dispCharCur < this.dispWidthMax) { if (textIndex >= text.Length) { return; } if (text[textIndex] == this.MessageState.NewlineChar) { textIndex++; message.Append(text[textIndex]); textIndex++; this.dispCharCur++; } else { switch (text[textIndex]) { case (char)0x0a: // linefeed message.Append(text[textIndex]); textIndex++; this.NewLine(); break; case (char)0x20: // space this.dispLastWordIndex = message.Length; message.Append(text[textIndex]); textIndex++; this.dispCharCur++; break; case (char)0x25: // % control textIndex++; int num = 0; string embedded; switch (text[textIndex++]) { case 'g': num = StringUtility.ParseNumber(text, ref textIndex); embedded = this.Interpreter.ResourceManager.LogicResources[0].GetMessage(num); if (embedded is not null) { this.Display(embedded, message); } break; case 'm': num = StringUtility.ParseNumber(text, ref textIndex); embedded = this.Interpreter.LogicInterpreter.CurrentLogic.GetMessage(num); if (embedded is not null) { this.Display(embedded, message); } break; case 'o': num = StringUtility.ParseNumber(text, ref textIndex); embedded = this.Interpreter.ResourceManager.InventoryResource.Items[this.Interpreter.State.Variables[num]].Name; this.Display(embedded, message); break; case 's': num = StringUtility.ParseNumber(text, ref textIndex); embedded = this.Interpreter.State.Strings[num]; this.Display(embedded, message); break; case 'v': num = StringUtility.ParseNumber(text, ref textIndex); embedded = StringUtility.NumberToString(this.Interpreter.State.Variables[num]); if (textIndex < text.Length && text[textIndex] == '|') { textIndex++; int paddingSize = StringUtility.ParseNumber(text, ref textIndex); embedded = StringUtility.PadWithZeros(embedded, paddingSize); } this.Display(embedded, message); break; case 'w': num = StringUtility.ParseNumber(text, ref textIndex); num--; embedded = this.Interpreter.ParserResults[num].Word; this.Display(embedded, message); break; default: break; } break; default: // normal character message.Append(text[textIndex]); textIndex++; this.dispCharCur++; break; } } } if (this.dispLastWordIndex == -1) { message.Append((char)0x0a); this.NewLine(); } else { this.dispCharCur = this.dispCharCur - (message.Length - this.dispLastWordIndex); this.NewLine(); message[this.dispLastWordIndex] = (char)0x0a; this.dispCharCur = message.Length - this.dispLastWordIndex - 1; this.dispLastWordIndex = -1; } } }
private void BindLbl(string PrjId) { ProjectInfo byId = ProjectInfo.GetById(PrjId); if (byId != null) { this.lblPrjId.Text = PrjId.ToString(); this.lblBllProducer.Text = byId.GetUserName(base.UserCode); this.lblPrintDate.Text = System.DateTime.Now.ToShortDateString(); this.lblPrjState.Text = TypeList.GetTypeName(byId.PrjState.ToString(), "2", "ProjectState"); this.lblBudgetWay.Text = TypeList.GetTypeName(byId.BudgetWay, "1", "ysType"); this.lblContractWay.Text = TypeList.GetTypeName(byId.ContractWay, "1", "cbType"); this.lblKeyPart.Text = TypeList.GetTypeName(byId.KeyPart, "1", "primaryGrade"); this.lblPayCondition.Text = TypeList.GetTypeName(byId.PayCondition, "1", "payment"); this.lblPayWay.Text = TypeList.GetTypeName(byId.PayWay, "1", "jsType"); if (byId.PrjTypes != null) { System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); System.Text.StringBuilder stringBuilder2 = new System.Text.StringBuilder(); foreach (ProjectKind current in byId.PrjTypes) { stringBuilder2.Append(current.ProfessionalCost.ToString()).Append("<br />"); stringBuilder.Append(TypeList.GetTypeName(current.PrjKind, "1", "ProjectType")).Append("<br />"); } this.lblPrjKindClass.Text = stringBuilder.ToString(); this.lblPrjProfessionalCost.Text = stringBuilder2.ToString(); } this.lblProperty.Text = TypeList.GetTypeName(byId.PrjProperty, "1", "ProjectProperty"); this.lblInfoOrigin.Text = this.ReplaceTxt(byId.ProjInfoOrigin); this.lblElseRequest.Text = this.ReplaceTxt(byId.ProjElseRequest); this.lblQualityClass.Text = TypeList.GetTypeName(byId.QualityClass, "1", "ProjectQuality"); if (byId.PrjRanks != null) { System.Text.StringBuilder stringBuilder3 = new System.Text.StringBuilder(); foreach (ProjectRank current2 in byId.PrjRanks) { stringBuilder3.Append(TypeList.GetTypeName(current2.Rank, "1", "zzGrade") + " " + current2.RankLevel).Append("<br />"); } this.lblRank.Text = stringBuilder3.ToString(); } this.lblTenderWay.Text = TypeList.GetTypeName(byId.TenderWay, "1", "zbType"); this.lblXmgroup.Text = TypeList.GetXmlGroupName(byId.Xmgroup); if (byId.EngineeringTypes != null) { System.Text.StringBuilder stringBuilder4 = new System.Text.StringBuilder(); foreach (EngineeringType current3 in byId.EngineeringTypes) { stringBuilder4.Append(current3.ToString()).Append("<br />"); } this.lblBuildingType.Text = stringBuilder4.ToString(); } this.lblTelphone.Text = byId.Telephone; if (byId.ProgAgent != "") { this.lblAgent.Text = byId.ProgAgentName; } this.lblBuildingArea.Text = byId.BuildingArea; this.lblDesigner.Text = byId.Designer; this.lblDuration.Text = byId.Duration; this.lblEndDate.Text = Common2.GetTime(byId.EndDate); this.lblgrade.Text = byId.PrjGrade; this.lblInspector.Text = byId.Inspector; this.lblOtherStatement.Text = StringUtility.ReplaceTxt(byId.OtherStatement); this.lblPrjCode.Text = byId.PrjCode; if (byId.PrjCost.ToString() != "0" && byId.PrjCost.ToString() != "") { this.lblPrjCost.Text = byId.PrjCost.ToString(); } this.lblPrjFundInfo.Text = byId.PrjFundInfo; this.lblPrjInfo.Text = StringUtility.ReplaceTxt(byId.PrjInfo); if (byId.PrjManager != "") { this.lblPrjManager.Text = byId.PrjManagerName; } if (byId.Businessman != "") { this.lblBusinessman.Text = byId.BusinessmanName; } this.lblPrjName.Text = byId.PrjName; this.lblPrjPlace.Text = byId.PrjPlace; this.lblRemark1.Text = StringUtility.ReplaceTxt(byId.Remark); this.lblStartDate.Text = Common2.GetTime(byId.StartDate); this.lblTotalHouseNum.Text = byId.TotalHouseNum; this.lblUndergroundArea.Text = byId.UndergroundArea; this.lblUsegrounArea.Text = byId.UsegrounArea; this.lblAfforestArea.Text = byId.AfforestArea; this.lblParkArea.Text = byId.ParkArea; if (byId.WorkUnit != "") { this.lblWorkUnit.Text = byId.WorkUnitName; } this.lblForecastProfitRate.Text = byId.ForecastProfitRate.ToString(); this.lblEngineeringEstimates.Text = byId.EngineeringEstimates; if (byId.PrjDutyPerson != "") { this.lblDutyPerson.Text = byId.PrjDutyPersonName; } this.lblApprovalOf.Text = byId.PrjApprovalOf; this.lblFundWorkable.Text = byId.PrjFundWorkable; this.lblManagementMargin.Text = byId.ManagementMargin.ToString(); this.lblMigrantQualityMarginRate.Text = byId.MigrantQualityMarginRate.ToString(); this.lblWithholdingTaxRate.Text = byId.WithholdingTaxRate.ToString(); this.lblPerformanceBond.Text = byId.PerformanceBond.ToString(); this.lblElseMargin.Text = byId.ElseMargin.ToString(); this.lblOwner.Text = byId.OwnerName; this.lblOwnerLinkMan.Text = byId.OwnerLinkMan; this.lblOwnerLinkManPhone.Text = byId.OwnerLinkPhone; this.lblOwnerAddress.Text = byId.OwnerAddress; this.lblCorp.Text = byId.ProjPeopleCorp; this.lblPhone.Text = byId.ProjPeopleTel; this.lblDuty.Text = byId.ProjPeopleDuty; this.lblName.Text = byId.ProjPeopleUserName; this.lblPrjManagerRequire.Text = byId.PrjManagerRequire; this.lblTechnicalLeaderRequire.Text = byId.TechnicalLeaderRequire; this.lblPrjReadOne.Text = WebUtil.GetUserNames(byId.PrjReadOne); if (!string.IsNullOrEmpty(byId.Province)) { if (byId.City == "北京" || byId.City == "上海" || byId.City == "天津" || byId.City == "重庆" || byId.City == "香港" || byId.City == "澳门") { this.lblArea.Text = byId.City; return; } this.lblArea.Text = byId.Province + byId.City; } } }
/// <summary> /// Returns the number of accepted strings from the given list of strings. /// Outputs the total time taken in seconds. /// </summary> public static int Test(bool accept, string[] strs, out double sec) { int totAccepted = 0; bool res = false; int totTime = System.Environment.TickCount; for (int i = 0; i < strs.Length; i++) { for (int j = 0; j < CodeGenTests.Repetitions; j++) { res = compiledregex.IsMatch(strs[i]); } if (res) { totAccepted += 1; } if (accept && !res) { Assert.Fail(string.Format("DotNetTest Positive mismatch: regex {0} should accept {1}", compiledregex.ToString(), StringUtility.Escape(strs[i]))); } if (!accept && res) { Assert.Fail(string.Format("DotNetTest Negative mismatch: regex {0} should reject {1}", compiledregex.ToString(), StringUtility.Escape(strs[i]))); } } totTime = System.Environment.TickCount - totTime; sec = ((double)totTime) / (1000.0); return(totAccepted); }
/// <summary> /// Returns the number of accepted strings from the given list of strings. /// Outputs the total time taken in seconds. /// </summary> public static int Test(bool accept, int index, byte[][] strs, string[] strings, out double sec) { //avoid measuring the unmanaged dll loading time //fixed (byte* pArr = strs[0]) // IsMatch(index, strs[0].Length, pArr); IsMatch(index, strs[0].Length, strs[0]); int totAccepted = 0; int totTime = System.Environment.TickCount; for (int i = 0; i < strs.Length; i++) { int res = 0; //fixed (byte* pArr = strs[i]) //avoid marshalling { var pArr = strs[i]; for (int j = 0; j < CodeGenTests.Repetitions; j++) { res = IsMatch(index, strs[i].Length, pArr); } if (res == 1) { totAccepted += 1; } if (accept && (res == 0)) { Assert.Fail(string.Format("CppTest Positive mismatch: regex {0} should accept {1}", index, StringUtility.Escape(strings[i]))); } if (!accept && (res == 1)) { Assert.Fail(string.Format("CppTest Negative mismatch: regex {0} should reject {1}", index, StringUtility.Escape(strings[i]))); } } } totTime = System.Environment.TickCount - totTime; sec = ((double)totTime) / (1000.0); return(totAccepted); }
protected void btnQuery_Click(object sender, System.EventArgs e) { this.lbSelect.DataSource = this.ptYhmcBll.GetAllModelByWhere(string.Format("where v_xm like '%{0}%' and state=1", this.txtQuery.Text.Trim())); this.lbSelect.DataBind(); this.lbUser.DataSource = this.ptYhmcBll.GetAllModelByWhere(string.Format("where v_yhdm in({0})", StringUtility.GetArrayToInStr(this.hdId.Value.Split(new char[] { ',' })))); this.lbUser.DataBind(); }
public void GenerateUniqueId() { UniqueId = StringUtility.GenerateAlphabet(12); }
/// <summary> /// Initializes a new instance of the <see cref="CreditCard"/> class. /// </summary> /// <param name="creditCardNumber">The credit card number.</param> public CreditCard(string creditCardNumber) { _stringUtility = new StringUtility(); CreditCardNumber = creditCardNumber; }
public static void ValidateDirectory(string path, string pattern, ValidationEventHandler validationEventHandler) { ValidateReadFromDirectory(path); var tablePath = Path.Combine(path, CremaSchemaObsolete.TableDirectoryObsolete); var typePath = Path.Combine(path, CremaSchemaObsolete.TypeDirectoryObsolete); if (Directory.Exists(tablePath) == true || Directory.Exists(typePath) == true) { } else { tablePath = Path.Combine(path, CremaSchema.TableDirectory); typePath = Path.Combine(path, CremaSchema.TypeDirectory); } var query = from item in DirectoryUtility.Exists(tablePath) ? DirectoryUtility.GetAllFiles(tablePath, "*" + CremaSchema.XmlExtension) : new string[] { } where StringUtility.GlobMany(Path.GetFileNameWithoutExtension(item), pattern) select item; var errorList = new List <ValidationEventArgs>(); Parallel.ForEach(query, item => { Validate(item, (s, e) => { lock (errorList) { errorList.Add(e); } }); }); var sourceUri = string.Empty; foreach (var item in errorList.OrderBy(i => i.Exception.SourceUri)) { if (sourceUri != item.Exception.SourceUri) { if (sourceUri != string.Empty) { Console.WriteLine(); } sourceUri = item.Exception.SourceUri; Console.WriteLine(sourceUri); } if (item.Severity == XmlSeverityType.Error) { Console.ForegroundColor = ConsoleColor.Red; Console.Write("error: "); Console.WriteLine(new XmlException(item.Message, item.Exception, item.Exception.LineNumber, item.Exception.LinePosition).Message); Console.ResetColor(); } else { Console.Write("warning: "); Console.WriteLine(item.Message); } } }
protected override AutobotBase CreateInstance(string autobotID) { return(new Autobot(this.cremaHost, this, autobotID, StringUtility.ToSecureString("1111"))); }
public static void AddTextLine(RichTextBox sourceRichEdit, string text, Color color, float size, bool bold, bool italic, bool strikeout, bool underline) { Win32RichEditUtility.AddText(sourceRichEdit, text + StringUtility.CreateLinefeedString(), color, size, bold, italic, strikeout, underline); }
private IEnumerable <MemberDeclarationSyntax> CreateMembers(IEnumerable <RefactoringDescriptor> refactorings) { yield return(ConstructorDeclaration("RefactoringsOptionsPage") .WithModifiers(Modifiers.Public()) .WithBody(Block( refactorings .Where(f => ShouldGenerateProperty(f)) .Select(f => ExpressionStatement(ParseExpression($"{f.Identifier} = {TrueOrFalseLiteralExpression(f.IsEnabledByDefault)}"))) .Concat(new StatementSyntax[] { SimpleAssignmentStatement( IdentifierName("DisabledRefactorings"), ParseExpression( "$\"" + string.Join(",", refactorings .Where(f => !f.IsEnabledByDefault) .OrderBy(f => f.Identifier, InvariantComparer) .Select(f => $"{{RefactoringIdentifiers.{f.Identifier}}}")) + "\"")) })))); yield return(MethodDeclaration(VoidType(), "MigrateValuesFromIdentifierProperties") .WithModifiers(Modifiers.Public()) .WithParameterList(ParameterList()) .WithBody( Block(refactorings .Where(f => ShouldGenerateProperty(f)) .OrderBy(f => f.Id, InvariantComparer) .Select(refactoring => ExpressionStatement(ParseExpression($"SetIsEnabled(RefactoringIdentifiers.{refactoring.Identifier}, {refactoring.Identifier})")))))); yield return(MethodDeclaration(VoidType(), "SetRefactoringsDisabledByDefault") .WithModifiers(Modifiers.PublicStatic()) .WithParameterList(ParameterList(Parameter(IdentifierName("RefactoringSettings"), Identifier("settings")))) .WithBody( Block(refactorings .Where(f => !f.IsEnabledByDefault) .OrderBy(f => f.Identifier, InvariantComparer) .Select(refactoring => { return ExpressionStatement( ParseExpression($"settings.DisableRefactoring(RefactoringIdentifiers.{refactoring.Identifier})")); })))); yield return(MethodDeclaration(VoidType(), "Fill") .WithModifiers(Modifiers.Public()) .WithParameterList(ParameterList(Parameter(ParseTypeName("ICollection<RefactoringModel>"), Identifier("refactorings")))) .WithBody( Block((new StatementSyntax[] { ExpressionStatement(ParseExpression("refactorings.Clear()")) }) .Concat(refactorings .OrderBy(f => f.Id, InvariantComparer) .Select(refactoring => { return ExpressionStatement( ParseExpression($"refactorings.Add(new RefactoringModel(RefactoringIdentifiers.{refactoring.Identifier}, \"{StringUtility.EscapeQuote(refactoring.Title)}\", IsEnabled(RefactoringIdentifiers.{refactoring.Identifier})))")); }))))); foreach (RefactoringDescriptor info in refactorings .Where(f => ShouldGenerateProperty(f)) .OrderBy(f => f.Identifier, InvariantComparer)) { yield return(PropertyDeclaration(BoolType(), info.Identifier) .WithAttributeLists( AttributeList(Attribute(IdentifierName("Browsable"), FalseLiteralExpression())), AttributeList(Attribute(IdentifierName("Category"), IdentifierName("RefactoringCategory"))), AttributeList(Attribute(IdentifierName("TypeConverter"), TypeOfExpression(IdentifierName("EnabledDisabledConverter"))))) .WithModifiers(Modifiers.Public()) .WithAccessorList( AccessorList( AutoGetAccessorDeclaration(), AutoSetAccessorDeclaration()))); } }
private void generatePoolHABox(Pool pool) { Host master = Helpers.GetMaster(pool.Connection); if (master == null || master.RestrictHAOrlando) { // Don't generate the box at all return; } if (!pool.ha_enabled) { return; } // 'High Availability' heading CustomListRow header = CreateHeader(Messages.HA_CONFIGURATION_TITLE); customListPanel.AddRow(header); AddRow(header, GetFriendlyName("pool.ha_enabled"), pool, getPoolHAStatus, false); { // ntol row. May be red and bold. bool redBold = pool.ha_host_failures_to_tolerate == 0; CustomListRow newChild = CreateNewRow(Messages.HA_CONFIGURED_CAPACITY, new ToStringWrapper <Pool>(pool, getNtol), redBold); header.AddChild(newChild); if (redBold) { newChild.Items[1].ForeColor = Color.Red; ToolStripMenuItem editHa = MainWindow.NewToolStripMenuItem(Messages.CONFIGURE_HA_ELLIPSIS, delegate(object sender, EventArgs e) { EditHA(pool); }); newChild.MenuItems.Add(editHa); newChild.DefaultMenuItem = editHa; } else { newChild.Items[1].ForeColor = BaseTabPage.ItemValueForeColor; } } { // plan_exists_for row needs some special work: the text may be red and bold bool redBold = haStatusRed(pool); CustomListRow newChild = CreateNewRow(Messages.HA_CURRENT_CAPACITY, new ToStringWrapper <Pool>(pool, getPlanExistsFor), redBold); header.AddChild(newChild); if (redBold) { newChild.Items[1].ForeColor = Color.Red; ToolStripMenuItem editHa = MainWindow.NewToolStripMenuItem(Messages.CONFIGURE_HA_ELLIPSIS, delegate(object sender, EventArgs e) { EditHA(pool); }); newChild.MenuItems.Add(editHa); newChild.DefaultMenuItem = editHa; } else { newChild.Items[1].ForeColor = BaseTabPage.ItemValueForeColor; } } AddBottomSpacing(header); // 'Heartbeating status' heading header = CreateHeader(Messages.HEARTBEATING_STATUS); customListPanel.AddRow(header); // Now build the heartbeat target health table List <SR> heartbeatSRs = pool.GetHAHeartbeatSRs(); // Sort heartbeat SRs using NaturalCompare heartbeatSRs.Sort((Comparison <SR>) delegate(SR a, SR b) { return(StringUtility.NaturalCompare(a.Name, b.Name)); }); List <Host> members = new List <Host>(pool.Connection.Cache.Hosts); // Sort pool members using NaturalCompare members.Sort((Comparison <Host>) delegate(Host a, Host b) { return(StringUtility.NaturalCompare(a.Name, b.Name)); }); int numCols = 1 + 2 + (2 * heartbeatSRs.Count); // Hostnames col, then 2 each for each HB target (network + SRs) int numRows = 1 + members.Count; // Create rows and cols tableLatencies.SuspendLayout(); tableLatencies.ColumnCount = numCols; tableLatencies.ColumnStyles.Clear(); for (int i = 0; i < numCols; i++) { tableLatencies.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); } tableLatencies.RowCount = numRows; tableLatencies.RowStyles.Clear(); for (int i = 0; i < numRows; i++) { tableLatencies.RowStyles.Add(new RowStyle(SizeType.AutoSize)); } { // Network icon PictureBox p = new PictureBox(); p.Image = Images.GetImage16For(Icons.Network); p.SizeMode = PictureBoxSizeMode.AutoSize; p.Padding = new Padding(0); tableLatencies.Controls.Add(p); tableLatencies.SetCellPosition(p, new TableLayoutPanelCellPosition(1, 0)); // Network text Label l = new Label(); l.Padding = new Padding(0, 5, 5, 5); l.Font = BaseTabPage.ItemLabelFont; l.ForeColor = BaseTabPage.ItemLabelForeColor; l.AutoSize = true; l.Text = Messages.NETWORK; tableLatencies.Controls.Add(l); tableLatencies.SetCellPosition(l, new TableLayoutPanelCellPosition(2, 0)); } for (int i = 0; i < heartbeatSRs.Count; i++) { // SR icon PictureBox p = new PictureBox(); p.Image = Images.GetImage16For(heartbeatSRs[i].GetIcon); p.SizeMode = PictureBoxSizeMode.AutoSize; p.Padding = new Padding(0); tableLatencies.Controls.Add(p); tableLatencies.SetCellPosition(p, new TableLayoutPanelCellPosition((2 * i) + 3, 0)); // SR name Label l = new Label(); l.Padding = new Padding(0, 5, 5, 5); l.Font = BaseTabPage.ItemLabelFont; l.ForeColor = BaseTabPage.ItemLabelForeColor; l.AutoSize = false; l.Size = new Size(200, 25); l.AutoEllipsis = true; l.Text = heartbeatSRs[i].Name; tableLatencies.Controls.Add(l); tableLatencies.SetCellPosition(l, new TableLayoutPanelCellPosition((2 * i) + 4, 0)); } for (int i = 0; i < members.Count; i++) { // Server name label Label l = new Label(); l.Padding = new Padding(5); l.Font = BaseTabPage.ItemLabelFont; l.ForeColor = BaseTabPage.ItemLabelForeColor; l.AutoSize = true; l.Text = members[i].Name.Ellipsise(30); tableLatencies.Controls.Add(l); tableLatencies.SetCellPosition(l, new TableLayoutPanelCellPosition(0, i + 1)); // Network HB status l = new Label(); l.Padding = new Padding(0, 5, 0, 5); l.Font = BaseTabPage.ItemValueFont; l.AutoSize = true; if (members[i].ha_network_peers.Length == members.Count) { l.ForeColor = Color.Green; } else { l.ForeColor = BaseTabPage.ItemValueForeColor; } if (members[i].ha_network_peers.Length == 0) { l.Text = Messages.HA_HEARTBEAT_UNHEALTHY; } else if (members[i].ha_network_peers.Length == members.Count) { l.Text = Messages.HA_HEARTBEAT_HEALTHY; } else { l.Text = string.Format(Messages.HA_HEARTBEAT_SERVERS, members[i].ha_network_peers.Length, members.Count); } tableLatencies.Controls.Add(l); tableLatencies.SetCellPosition(l, new TableLayoutPanelCellPosition(1, i + 1)); tableLatencies.SetColumnSpan(l, 2); // For each heartbeat SR, show health from this host's perspective for (int j = 0; j < heartbeatSRs.Count; j++) { l = new Label(); l.Padding = new Padding(0, 5, 0, 5); l.Font = BaseTabPage.ItemValueFont; l.ForeColor = BaseTabPage.ItemValueForeColor; l.AutoSize = true; l.Text = Messages.HA_HEARTBEAT_UNHEALTHY; foreach (string opaqueRef in members[i].ha_statefiles) { XenRef <VDI> vdiRef = new XenRef <VDI>(opaqueRef); VDI vdi = pool.Connection.Resolve(vdiRef); if (vdi == null) { continue; } SR sr = pool.Connection.Resolve(vdi.SR); if (sr == null) { continue; } if (sr == heartbeatSRs[j]) { l.ForeColor = Color.Green; l.Text = Messages.HA_HEARTBEAT_HEALTHY; break; } } tableLatencies.Controls.Add(l); tableLatencies.SetCellPosition(l, new TableLayoutPanelCellPosition((2 * j) + 2, i + 1)); tableLatencies.SetColumnSpan(l, 2); } } tableLatencies.ResumeLayout(); tableLatencies.PerformLayout(); }
public Result <OlescUser> Register(OlescUser newUser, UserProfile newUserProfile, List <OlescRole> roles) { int NumOfRecords = 0; /* Create the result object ; which will be returned at the end * of the method */ Result <OlescUser> result = new Result <OlescUser>(); /* Database Connection */ OlescEntities dbCon = null; try { /* Database Connection */ dbCon = new OlescEntities(); /* Adding a newUser to User table, * and returns the object with user ID */ newUser.isActive = "A"; /* Take the user password and turn in into MD5 hash, * then save the hash in the database */ newUser.Password = StringUtility.CreateMD5Hash(newUser.Password); newUser = dbCon.OlescUsers.Add(newUser); /* assign ID to UserProfile table; because it's PF */ //newUserProfile.UserID = newUser.ID; newUserProfile.user = newUser; /* Adding a newUserProfile to UserProfile table, * and returns the object */ newUserProfile = dbCon.UserProfiles.Add(newUserProfile); foreach (OlescRole role in roles) { /* creating an object for userrole, using userrole table */ OlescUserRole newUserRole = new OlescUserRole(); /* What I need to assign a role is to have RoleID and UserID * "Check database table UserRole"*/ //newUserRole.UserID = newUser.ID; newUserRole.User = newUser; newUserRole.RoleID = role.ID; /*Adding the role assigned tp userRole table*/ newUserRole = dbCon.OlescUserRoles.Add(newUserRole); } NumOfRecords = dbCon.SaveChanges(); /* if there is at least 1 record saved -> true, if not -> false */ if (NumOfRecords >= 1) { result.isSuccess = true; result.message = "Thank you " + newUser.UserProfile.FirstName + " for regstering in OLESC!"; NotificationManagementService nms = new NotificationManagementService(); /* Email notification service */ /* Conent */ String emailContent; emailContent = "Thank you for registering in OLESC"; emailContent += "\nYour Username is your email: " + newUser.Email; emailContent += "\nEnjoy our Online Learning Srvices!"; emailContent += "\n\nRegards,\nOLESC Team"; /* Subject*/ String emailSubject; emailSubject = "OLESC Registration"; /* Sending the email */ nms.Notify(newUser.Email, null, null, emailSubject, emailContent); } else { result.isSuccess = false; result.message = "Error in registration, please check you information"; } } catch (Exception e) { result.isSuccess = false; result.message = e.Message; result.resultObject = null; } /* Whatever you want to clean up, close after error to delete from memory*/ finally { if (dbCon != null) { /* Same as in Java dbCon.Close() */ dbCon.Dispose(); } } return(result); }
/// <summary> /// Decorates the specified rollbar data. /// </summary> /// <param name="rollbarData">The rollbar data.</param> protected override void Decorate(Data rollbarData) { if (this._rollbarHttpContext == null) { return; //nothing to decorate with... } Dictionary <string, object> customRequestFields = null; if (this._rollbarHttpContext != null) { customRequestFields = new Dictionary <string, object>(); customRequestFields.Add("httpRequestTimestamp", this._rollbarHttpContext.Timestamp); if (this._rollbarHttpContext.HttpAttributes != null) { customRequestFields.Add("httpRequestID", this._rollbarHttpContext.HttpAttributes.RequestID); customRequestFields.Add("scheme", this._rollbarHttpContext.HttpAttributes.RequestScheme); customRequestFields.Add("protocol", this._rollbarHttpContext.HttpAttributes.RequestProtocol); customRequestFields.Add("statusCode", this._rollbarHttpContext.HttpAttributes.ResponseStatusCode); } } if (customRequestFields != null && customRequestFields.Count > 0) { if (rollbarData.Request == null) { rollbarData.Request = new Request(customRequestFields); } else { foreach (var item in customRequestFields) { rollbarData.Request.Add(item); } } } if (this._rollbarHttpContext.HttpAttributes != null) { if (rollbarData.Request == null) { rollbarData.Request = new Request(); } rollbarData.Request.Url = this._rollbarHttpContext.HttpAttributes.RequestHost.Value + this._rollbarHttpContext.HttpAttributes.RequestPath; rollbarData.Request.QueryString = this._rollbarHttpContext.HttpAttributes.RequestQuery.Value; rollbarData.Request.Params = null; rollbarData.Request.Method = this._rollbarHttpContext.HttpAttributes.RequestMethod; if (this._rollbarHttpContext.HttpAttributes.RequestHeaders?.Count > 0) { rollbarData.Request.Headers = new Dictionary <string, string>(this._rollbarHttpContext.HttpAttributes.RequestHeaders.Count); foreach (var header in this._rollbarHttpContext.HttpAttributes.RequestHeaders) { if (header.Value.Count == 0) { continue; } rollbarData.Request.Headers.Add(header.Key, StringUtility.Combine(header.Value, ", ")); } } if (rollbarData.Response == null) { rollbarData.Response = new Response(); } rollbarData.Response.StatusCode = this._rollbarHttpContext.HttpAttributes.ResponseStatusCode; if (this._rollbarHttpContext.HttpAttributes.ResponseHeaders?.Count > 0) { rollbarData.Response.Headers = new Dictionary <string, string>(this._rollbarHttpContext.HttpAttributes.ResponseHeaders.Count); foreach (var header in this._rollbarHttpContext.HttpAttributes.ResponseHeaders) { if (header.Value.Count == 0) { continue; } rollbarData.Response.Headers.Add(header.Key, StringUtility.Combine(header.Value, ", ")); } } } }
private static string DetectTargetFrameworks() { var targetFrameworks = RuntimeEnvironmentUtility.GetAssemblyTargetFrameworks(typeof(Data)); return(StringUtility.Combine(targetFrameworks, "; ")); }
public override string ToString() { var result = "orderby " + StringUtility.Join(", ", Orderings); return(result); }
static void Main(string[] args) { string sentence = "This is fun whoa"; Console.WriteLine(StringUtility.SummarizeText(sentence, 25)); }
protected void refreshProgressLabel() { mProgressLabel.setLabel(StringUtility.floatToString(mProgressBar.getFillPercent() * 100.0f, 1) + "%"); }
/// <summary> /// Parses a the value for the header Content-Type to /// a <see cref="ContentType"/> object. /// </summary> /// <param name="headerValue">The value to be parsed</param> /// <returns>A <see cref="ContentType"/> object</returns> /// <exception cref="ArgumentNullException">If <paramref name="headerValue"/> is <see langword="null"/></exception> public static ContentType ParseContentType(string headerValue) { if (headerValue == null) { throw new ArgumentNullException("headerValue"); } // We create an empty Content-Type which we will fill in when we see the values ContentType contentType = new ContentType(); // Now decode the parameters List <KeyValuePair <string, string> > parameters = Rfc2231Decoder.Decode(headerValue); foreach (KeyValuePair <string, string> keyValuePair in parameters) { string key = keyValuePair.Key.ToUpperInvariant().Trim(); string value = StringUtility.RemoveQuotesIfAny(keyValuePair.Value.Trim()); switch (key) { case "": // This is the MediaType - it has no key since it is the first one mentioned in the // headerValue and has no = in it. // Check for illegal content-type if (value.ToUpperInvariant().Equals("TEXT")) { value = "text/plain"; } contentType.MediaType = value; break; case "BOUNDARY": contentType.Boundary = value; break; case "CHARSET": contentType.CharSet = value; break; case "NAME": contentType.Name = EncodedWord.Decode(value); break; default: // This is to shut up the code help that is saying that contentType.Parameters // can be null - which it cant! if (contentType.Parameters == null) { throw new Exception("The ContentType parameters property is null. This will never be thrown."); } // We add the unknown value to our parameters list // "Known" unknown values are: // - title // - report-type contentType.Parameters.Add(key, value); break; } } return(contentType); }
string IPackRule.GetBundleName(PackRuleData data) { return(StringUtility.RemoveExtension(data.CollectPath)); }
protected void trvwDepartment_SelectedNodeChanged(object sender, System.EventArgs e) { string selectedValue = this.TvBranch.SelectedValue; this.lbSelect.DataSource = this.ptYhmcBll.GetAllModelByWhere(string.Format("where i_bmdm = {0} and state=1", selectedValue)); this.lbSelect.DataBind(); this.lbUser.DataSource = this.ptYhmcBll.GetAllModelByWhere(string.Format("where v_yhdm in({0})", StringUtility.GetArrayToInStr(this.hdId.Value.Split(new char[] { ',' })))); this.lbUser.DataBind(); }
/// <summary> /// Parse a sequence of queries. /// Eeach query in the sequence must end with a ';'. /// Output also the individual query strings. /// </summary> public static List <Expression> ParseQueries(string query_sequence, out List <string> query_strings) { try { var input = new Antlr.Runtime.ANTLRStringStream(query_sequence); var lexer = new queryLexer(input); var tokens = new Antlr.Runtime.CommonTokenStream(lexer); var parser = new queryParser(tokens); var res = parser.Queries(); query_strings = res.Item2; return(res.Item1); } catch (Antlr.Runtime.MismatchedTokenException e) { string tok = (e.Token != null ? "'" + e.Token.Text + "'" : (e.Character >= 0 ? StringUtility.Escape((char)e.Character) : "")); string msg = "unexpected token " + tok; if (tok != "" && 0 <= e.Expecting && e.Expecting < queryParser.tokenNames.Length) { msg += string.Format(" expecting {0}", queryParser.tokenNames[e.Expecting]); } throw new QueryParseException(e.Line, e.CharPositionInLine + 1, msg); } catch (Antlr.Runtime.FailedPredicateException e) { string msg = string.Format("unexpected '{0}' failed {1}", (e.Token != null ? e.Token.Text : ((char)e.Character).ToString()), e.PredicateText); throw new QueryParseException(e.Line, e.CharPositionInLine + 1, msg); } catch (Antlr.Runtime.NoViableAltException e) { string msg = string.Format("unexpected '{0}' no alternatives", (e.Token != null ? e.Token.Text : ((char)e.Character).ToString())); throw new QueryParseException(e.Line, e.CharPositionInLine + 1, msg); } catch (Antlr.Runtime.RecognitionException e) { string msg = string.Format("unexpected '{0}'", (e.Token != null ? e.Token.Text : ((char)e.Character).ToString())); throw new QueryParseException(e.Line, e.CharPositionInLine + 1, msg); } catch (QueryParseException e) { throw e; } catch (Exception e) { throw new QueryParseException(1, 1, e.Message); } }
public void Setup() { _stringUtility = new StringUtility(); }
/// <summary> /// Initializes a new instance of the <see cref="CreditCard"/> class. /// </summary> public CreditCard() { _stringUtility = new StringUtility(); }