Example #1
0
    static void Main(string[] args)
    {
        List<double> results;
        List<double> modularity;
        string line = "";
        System.IO.File.Delete(Properties.Settings.Default.ResultFile);

        for (double mod = Properties.Settings.Default.Modularity_From; mod <= Properties.Settings.Default.Modularity_To; mod += Properties.Settings.Default.Modularity_Step)
        {
                Console.WriteLine();
                line = "";
                for(double bias = Properties.Settings.Default.bias_from; bias <= Properties.Settings.Default.bias_to; bias += Properties.Settings.Default.bias_step)
                {
                    results = new List<double>();
                    modularity = new List<double>();
                    System.Threading.Tasks.Parallel.For(0, Properties.Settings.Default.runs, j =>
                    {
                        ClusterNetwork net = new ClusterNetwork(Properties.Settings.Default.Nodes, Properties.Settings.Default.Edges, Properties.Settings.Default.Clusters, mod);

                        Console.WriteLine("Run {0}, created cluster network with modularity={1:0.00}", j, (net as ClusterNetwork).NewmanModularityUndirected);
                        /// TODO: Run experiment
                    });
                    line = string.Format(new CultureInfo("en-US").NumberFormat, "{0:0.000} {1:0.000} {2:0.000} {3:0.000} \t", MathNet.Numerics.Statistics.Statistics.Mean(modularity.ToArray()), bias, MathNet.Numerics.Statistics.Statistics.Mean(results.ToArray()), MathNet.Numerics.Statistics.Statistics.StandardDeviation(results.ToArray()));
                    System.IO.File.AppendAllText(Properties.Settings.Default.ResultFile, line + "\n");
                    Console.WriteLine("Finished spreading on cluster network for modularity = {0:0.00}, bias = {1:0.00}, Average = {2:0.00}", mod, bias, MathNet.Numerics.Statistics.Statistics.Mean(results.ToArray()));
                }
                System.IO.File.AppendAllText(Properties.Settings.Default.ResultFile, "\n");
        }
    }
Example #2
0
        private Delegate CreateActionDelegate(MethodInfo method)
        {
            List<ParameterExpression> parameters = new List<ParameterExpression>();
            foreach (ParameterInfo parameterInfo in method.GetParameters())
            {
                parameters.Add(Expression.Parameter(parameterInfo.ParameterType, parameterInfo.Name));
            }

            LambdaExpression lambda;

            if (method.IsStatic)
            {
                lambda = Expression.Lambda(
                    GetActionType(parameters.Select(p => p.Type).ToArray()),
                    Expression.Call(method, parameters.Cast<Expression>().ToArray()),
                    parameters.ToArray());
            }
            else
            {
                Type bindingType = method.DeclaringType;
                Expression<Func<object>> getInstanceExpression =
                    () => ScenarioContext.Current.GetBindingInstance(bindingType);

                lambda = Expression.Lambda(
                    GetActionType(parameters.Select(p => p.Type).ToArray()),
                    Expression.Call(
                        Expression.Convert(getInstanceExpression.Body, bindingType),
                        method,
                        parameters.Cast<Expression>().ToArray()),
                    parameters.ToArray());
            }


            return lambda.Compile();
        }
        private static object[] GetInvokeParametersForMethod(MethodInfo methodInfo, IList<string> arguments)
        {
            var invokeParameters = new List<object>();
            var args = new List<string>(arguments);
            var methodParameters = methodInfo.GetParameters();
            bool methodHasParams = false;

            if (methodParameters.Length == 0) {
                if (args.Count == 0)
                    return invokeParameters.ToArray();
                return null;
            }

            if (methodParameters[methodParameters.Length - 1].ParameterType.IsAssignableFrom(typeof(string[]))) {
                methodHasParams = true;
            }

            if (!methodHasParams && args.Count != methodParameters.Length) return null;
            if (methodHasParams && (methodParameters.Length - args.Count >= 2)) return null;

            for (int i = 0; i < args.Count; i++) {
                if (methodParameters[i].ParameterType.IsAssignableFrom(typeof(string[]))) {
                    invokeParameters.Add(args.GetRange(i, args.Count - i).ToArray());
                    break;
                }
                invokeParameters.Add(Convert.ChangeType(arguments[i], methodParameters[i].ParameterType));
            }

            if (methodHasParams && (methodParameters.Length - args.Count == 1)) invokeParameters.Add(new string[] { });

            return invokeParameters.ToArray();
        }
Example #4
0
 internal static string ParseCPUTreeUsageInfo(List<string> processStrings, List<string> errorStrings)
 {
     if (processStrings.Count == 1) return processStrings[0];
     if (errorStrings.Count > 0 && errorStrings.Exists(s => s.Contains("NoSuchProcess"))) throw new InvalidOperationException("Process could not be found. Output from CPU sampler is:"+string.Join(",", processStrings.ToArray()));
     throw new ApplicationException(
         string.Format("Could not process cpu snapshot output. StdOutput: {0}, ErrOutput: {1}", string.Join(",", processStrings.ToArray()), string.Join(",", errorStrings.ToArray())));
 }
    public static string GetCompactedJavaScript()
    {
        List<string> scripts = new List<string>();
        foreach (string script in SiteUtility.Scripts)
        {
            scripts.Add(HttpContext.Current.Request.MapPath(script));
        }

        // set to expire cache when any of the source files changes
        CacheDependency cacheDependency = new CacheDependency(scripts.ToArray());

        Cache cache = HttpRuntime.Cache;
        string cacheKey = "CompactedJavaScript";
        if (cache[cacheKey] != null)
        {
            return cache[cacheKey] as string;
        }

        StringBuilder sb = new StringBuilder();
        sb.AppendLine("/*  Generated " + DateTime.Now.ToUniversalTime().ToString("R", DateTimeFormatInfo.InvariantInfo) + "  */\n");
        sb.AppendLine(FileProcessor.Run(PackMode.JSMin, scripts.ToArray(), false));

        string output = sb.ToString();

        // hold for 30 minutes
        cache.Insert(cacheKey, output, cacheDependency, DateTime.Now.AddMinutes(30),
            Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);

        return output;
    }
        internal static MethodInvoker Create(MethodInfo method, object target)
        {

            var args = new List<Type>(method.GetParameters().Select(p => p.ParameterType));
            Type delegateType;

            var returnMethodInvoker = new MethodInvoker
            {
                ParameterTypeList = args.ToList(),
                ParameterCount = args.Count,
                ReturnType = method.ReturnType,
                MethodName = method.Name
            };


            if (method.ReturnType == typeof(void))
            {
                delegateType = Expression.GetActionType(args.ToArray());
            }
            else
            {
                args.Add(method.ReturnType);
                delegateType = Expression.GetFuncType(args.ToArray());
            }

            returnMethodInvoker.MethodDelegate = method.CreateDelegate(delegateType, target);

            return returnMethodInvoker;

        }
 private static string[] GetAllFiles(DirectoryInfo directory, string extension)
 {
     List<string> allFiles = new List<string>();
     DirectoryInfo[] allDirectory = directory.GetDirectories();
     if (allDirectory.Length > 0)
     {
         foreach (string[] files in allDirectory.Select(single => GetAllFiles(single, extension)))
         {
             allFiles.AddRange(files);
         }
         FileInfo[] fileInfos = directory.GetFiles();
         allFiles.AddRange(from file in fileInfos
                           where file.Extension.ToLower().Equals(extension)
                           select file.FullName);
         return allFiles.ToArray();
     }
     else
     {
         FileInfo[] files = directory.GetFiles();
         allFiles.AddRange(from file in files
                           where file.Extension.ToLower().Equals(extension)
                           select file.FullName);
         return allFiles.ToArray();
     }
 }
        public void JsonObjectConstructorParmsTest()
        {
            JsonObject target = new JsonObject();
            Assert.Equal(0, target.Count);

            string key1 = AnyInstance.AnyString;
            string key2 = AnyInstance.AnyString2;
            JsonValue value1 = AnyInstance.AnyJsonValue1;
            JsonValue value2 = AnyInstance.AnyJsonValue2;

            List<KeyValuePair<string, JsonValue>> items = new List<KeyValuePair<string, JsonValue>>()
            {
                new KeyValuePair<string, JsonValue>(key1, value1),
                new KeyValuePair<string, JsonValue>(key2, value2),
            };

            target = new JsonObject(items[0], items[1]);
            Assert.Equal(2, target.Count);
            ValidateJsonObjectItems(target, key1, value1, key2, value2);

            target = new JsonObject(items.ToArray());
            Assert.Equal(2, target.Count);
            ValidateJsonObjectItems(target, key1, value1, key2, value2);

            // Invalid tests
            items.Add(new KeyValuePair<string, JsonValue>(key1, AnyInstance.DefaultJsonValue));
            ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject(items[0], items[1], items[2]); });
            ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject(items.ToArray()); });
        }
Example #9
0
        public static string[] GetValueListFromJSONArray(string jsonString)
        {
            List<string> valueList = new List<string>();

            if (string.IsNullOrEmpty(jsonString)
            || jsonString.Equals("null")
            )
                return valueList.ToArray();
            try
            {
                JArray jo = JArray.Parse(jsonString);
                foreach (JToken token in jo.Values())
                {
                    if (token.Type == JsonTokenType.String)
                        valueList.Add(token.Value<string>().Trim());
                }
            }
            catch (Exception e)
            {
                valueList.Add(jsonString);
                return valueList.ToArray();
            }

            return valueList.ToArray();
        }
Example #10
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            TKChart chart = new TKChart (this.ExampleBounds);
            chart.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            this.View.AddSubview (chart);

            Random r = new Random ();
            List<CustomObject> data = new List<CustomObject> ();
            for (int i = 0; i < 5; i++) {
                CustomObject obj = new CustomObject () {
                    ObjectID = i,
                    Value1 = r.Next (100),
                    Value2 = r.Next (100),
                    Value3 = r.Next (100)
                };
                data.Add (obj);
            }

            chart.AddSeries (new TKChartAreaSeries (data.ToArray(), "ObjectID", "Value1"));
            chart.AddSeries (new TKChartAreaSeries (data.ToArray(), "ObjectID", "Value2"));
            chart.AddSeries (new TKChartAreaSeries (data.ToArray(), "ObjectID", "Value3"));

            TKChartStackInfo stackInfo = new TKChartStackInfo (new NSNumber (1), TKChartStackMode.Stack);
            for (int i = 0; i < chart.Series.Length; i++) {
                TKChartSeries series = chart.Series [i];
                series.SelectionMode = TKChartSeriesSelectionMode.Series;
                series.StackInfo = stackInfo;
            }

            chart.ReloadData ();
        }
Example #11
0
        public ModelQty[] GetModelQty()
        {

            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
            IList<ModelQty> ret = new List<ModelQty>();
            DateTime now = new DateTime(2014, 1, 1);
            Random rnd = new Random();            
            try
            {

                //1.检查传进来的参数
                //Execute.ValidateParameter(CustSN);

                //2.获取DB中的数据
                //ModelResponse modelReponse = Execute.modelResponseMsg(CustSN);

                //logger.DebugFormat("Reponse data:{0}", modelReponse.ToString());
                for (int i = 0; i <= 100; ++i)
                {
                    ret.Add(new ModelQty { Qty = rnd.Next(0, 200), Date = now.AddDays(i) });
                }
                return ret.ToArray();
            }
            catch (Exception e)
            {              

                ret.Add(new ModelQty { Qty = 0, Date = now });
                return ret.ToArray();
            }
            finally
            {
               
            }
        }
        public PartialViewResult FlashACard(string wantedDisplayDrug)
        {
            FlashDrugSetModel drugSetModel = new FlashDrugSetModel();

            List<Drug> myBrandSearch = new DrugCardsRepository().GetDrugBrand(wantedDisplayDrug);
            List<Drug> myGenericSearch = new DrugCardsRepository().GetDrugGeneric(wantedDisplayDrug);

            drugSetModel.currentArrayIndex = 0;
            List<string> resultInfo = new List<string>();

            if (myBrandSearch.Count > 0 )
            {
                drugSetModel.currentDisplayDrug = myBrandSearch.First();

                resultInfo.AddRange(myBrandSearch.Select(x => x.DrugBrand).ToList());
                drugSetModel.userDrugInfoArray = resultInfo.ToArray();
            }
            else if(myGenericSearch.Count>0)
            {
                drugSetModel.currentDisplayDrug = myGenericSearch.First();

                resultInfo.AddRange(myGenericSearch.Select(x => x.DrugBrand).ToList());
                drugSetModel.userDrugInfoArray = resultInfo.ToArray();
            }

            return PartialView("_FlashMyCard", drugSetModel);
        }
Example #13
0
        /// <summary>
        /// Takes a list of metric strings, separating them with newlines into a byte packet of the maximum specified size.
        /// </summary>
        /// <param name="metrics">   	The metrics to act on. </param>
        /// <param name="packetSize">	Maximum size of each packet (512 bytes recommended for Udp). </param>
        /// <returns>	A streamed list of byte arrays, where each array is a maximum of 512 bytes. </returns>
        public static IEnumerable<byte[]> ToMaximumBytePackets(this IEnumerable<string> metrics, int packetSize)
        {
            List<byte> packet = new List<byte>(packetSize);

            foreach (string metric in metrics)
            {
                var bytes = Encoding.UTF8.GetBytes(metric);
                if (packet.Count + _terminator.Length + bytes.Length <= packetSize)
                {
                    packet.AddRange(bytes);
                    packet.AddRange(_terminator);
                }
                else if (bytes.Length >= packetSize)
                {
                    yield return bytes;
                }
                else
                {
                    yield return packet.ToArray();
                    packet.Clear();
                    packet.AddRange(bytes);
                    packet.AddRange(_terminator);
                }
            }

            if (packet.Count > 0)
            {
                yield return packet.ToArray();
            }
        }
        /// <summary>
        /// Frame the incoming data and raise the OnFrameReceived when the lastBuffer holds at least a frame type in the frames to listen to list.
        /// </summary>
        public void ProcessData(byte[] bytes)
        {
            lastBuffer.AddRange(bytes.ToList());
            List<byte> workingBuffer = new List<byte>();
            //Get all the bytes that constitute a whole frame
            var str = toStr(bytes);
            while (lastBuffer.IndexOf(frameSeparator) > 0)
            {
                if (lastBuffer.Count > lastBuffer.IndexOf(frameSeparator))
                    workingBuffer = lastBuffer.Take(lastBuffer.IndexOf(frameSeparator) + 1).ToList();
                else if (lastBuffer.Count == lastBuffer.IndexOf(frameSeparator))
                    workingBuffer = lastBuffer;


                if (workingBuffer.Count() > 0)
                {
                    foreach (var frame in Frames)
                    {
                        if (frame.IsFrameType(workingBuffer.ToArray()))
                        {
                            if (OnFrameReceived != null)
                                OnFrameReceived(frame.GetFrame(workingBuffer.ToArray()));
                        }
                    }
                    workingBuffer.Clear();
                }
                //Get the bytes from the last buffer that trail the last frame
                if (lastBuffer.IndexOf(frameSeparator) + 1 == lastBuffer.Count)
                    lastBuffer.Clear();
                else if (lastBuffer.IndexOf(frameSeparator) + 1 < lastBuffer.Count)
                    lastBuffer.RemoveRange(0, lastBuffer.IndexOf(frameSeparator) + 1);
            }
        }
Example #15
0
  static void Main()
  {
    Solver solver = new Google.OrTools.ConstraintSolver.Solver("p");

    // creating dummy variables
    List<IntVar> vars = new List<IntVar>();
    for (int i = 0; i < 200000; i++)
    {
      vars.Add(solver.MakeIntVar(0, 1));
    }

    IntExpr globalSum = solver.MakeSum(vars.ToArray());

    DecisionBuilder db = solver.MakePhase(
        vars.ToArray(),
        Google.OrTools.ConstraintSolver.Solver.INT_VAR_SIMPLE,
        Google.OrTools.ConstraintSolver.Solver.INT_VALUE_SIMPLE);

    solver.NewSearch(db, new OptimizeVar(solver, true, globalSum.Var(), 100));

    GC.Collect();
    GC.WaitForPendingFinalizers();

    while (solver.NextSolution())
    {
      Console.WriteLine("solution " + globalSum.Var().Value());
    }
    Console.WriteLine("fini");
    Console.ReadLine();
  }
Example #16
0
 private void button1_Click(object sender, EventArgs e)
 {
     Int32 i = 0;
     richTextBox1.Text = "";
     //HuffmanTree htree = new HuffmanTree();
     htree.Build(textBox1.Text);
     encoded = htree.Encode(textBox1.Text);
     MessageBox.Show("Закодировано");
     foreach (bool bit in encoded)
     {
         richTextBox1.Text += ((bit ? 1 : 0).ToString() + " ");
     }
     foreach (KeyValuePair<char, int> item in htree.Frequencies)
     {
         Debug.Assert( richTextBox3 != null, "richTextBox3 != null" );
         List<String> list = new List<String>();
         foreach (String s in htree.Codec)
         {
             list.Add( s );
         }
         if (list.ToArray().Length > i)
         {
             richTextBox3.Text += (@"Символ: " + item.Key + @"	Количество: " + item.Value.ToString() + @"	Частота: " + Round( value: (float)item.Value / textBox1.Text.Length, digits: 3) + @"	Код " + list.ToArray()[i] + "\n");
         }
         Int32 i1 = i++;
     }
     String originalText = textBox1.Text;
     int countSimbol = originalText.Length;
     int summ = countSimbol * 8;
     textBox2.Text = Convert.ToString(summ);        
     
 }
Example #17
0
        public static string[] AssembleChunks(this List<string> s, int length)
        {
            if (s == null)
                return new string[0];

            var result = new List<string>();

            if (s == null || s.Count == 0)
                return result.ToArray();

            string line = null;

            foreach (var item in s)
            {
                if (item.Length < length)
                {
                    line += item;
                    result.Add(line);
                    line = null;
                }
                else
                    line += item;
            }

            if (line != null)
                result.Add(line);

            return result.ToArray();
        }
        public static void PurgeAllMessages(IEnumerable<AzureMessageQueue> monitorQueues)
        {
            List<Task> tasks = new List<Task>();

              foreach( var queue in monitorQueues ) {

            if( AzureServiceBusReceiver.GetAzureQueueCount(queue.Queue.Name) > 0 ) {
              tasks.Add(Task.Factory.StartNew(() => {
            try {
              _log.Trace("Purging Queue {0}...".With(queue.Queue.Name));
              queue.Purge();
              _log.Trace("Finished Purging Queue " + queue.Queue.Name);

            } catch(Exception ex) {
              _log.Error("Error when Purgin queue {0}, {1}".With(queue.Queue.Name, ex));
            }
              }));
              Thread.Sleep(500);
            }

            if( tasks.Count > 0 && ( tasks.Count % 15) == 0 ) {
              Task.WaitAll(tasks.ToArray());
              tasks.Clear();
            }
              }

              if( tasks.Count > 0 )
            Task.WaitAll(tasks.ToArray());
        }
 public string[] readFile(string filePath)
 {
     StreamReader sr = new StreamReader(filePath);
     List<string> list = new List<string> { };
     try
     {
         string aLine = "";
         while (aLine != null)
         {
             aLine = sr.ReadLine();
             list.Add(aLine);
         }
         list.RemoveAt(list.Count - 1);
         return list.ToArray();
     }
     catch
     {
         list.Add("nothing");
         return list.ToArray();
     }
     finally
     {
         sr.Close();
     }
 }
        public int Add(string input)
        {
            List<string> seperators = new List<string>() { ",", "\n" };

            // check for new seperators and add if need be
            if (input.StartsWith("//") && input[3] == '\n') {
                seperators.Add(input[2].ToString());
                input = input.Replace("//", "");
            }

            // get an empty string
            if (string.IsNullOrEmpty(input))
                return 0;
            // handle two numbers
            else if (input.Contains(seperators.ToArray()))
            {
                // do split method
                string[] numbers = input.Split(seperators.ToArray(),StringSplitOptions.RemoveEmptyEntries);
                int sum = 0;
                foreach (string num in numbers)
                {
                    sum += int.Parse(num);
                }
                return sum;

            }
            else // handle a single number
                return int.Parse(input);
        }
        public short[] GetAppliedMigrationVersions(string scope)
        {
            var shortList = new List<short>();

            if (string.IsNullOrEmpty(scope))
            {
                var list1 = _databaseProvider.ExecuteScalarArray<long>(
                        "SELECT {1} FROM {0} WHERE {2} IS NULL ORDER BY {1}",
                        TableName, VersionColumnName, ScopeColumnName);

                foreach (var item in list1)
                {
                    shortList.Add((short) item);
                }

                return shortList.ToArray();
            }

            var list2 = _databaseProvider.ExecuteScalarArray<long>(
                    "SELECT {1} FROM {0} WHERE {2} = '{3}' ORDER BY {1}",
                    TableName, VersionColumnName, ScopeColumnName, scope);

            foreach (var item in list2)
            {
                shortList.Add((short)item);
            }

            return shortList.ToArray();
        }
        public List<CurrencyBlacklist> GetList(string currencyNumber, Pagination paging)
        {
            string sql = null;
            List<DbParameter> parameterList = new List<DbParameter>();

            sql = " select PkId, CurrencyKindCode, FaceAmount, CurrencyVersion, CurrencyNumber from tbl_currency_blacklist where 1=1 ";

            if (currencyNumber.IsNotNullOrEmpty())
            {
                sql += " and CurrencyNumber like concat(\'%\', {0}, \'%\') ".FormatWith("@CurrencyNumber");

                parameterList.Add(new MySqlParameter("@CurrencyNumber", currencyNumber));
            }

            if (paging != null)
            {
                return DbHelper.ExecutePagingList<CurrencyBlacklist>(sql, paging, parameterList.ToArray());
            }

            else
            {
                sql += " order by PkId desc ";

                return DbHelper.ExecuteList<CurrencyBlacklist>(sql, CommandType.Text, parameterList.ToArray());
            }
        }
Example #23
0
 public int copy_int(int state, int size, string name)
 {
     byte[] s;
     if (size < 2)
     {
         s = new byte[1];
         s[0] = (byte)state;
     }
     else
     {
         s = BitConverter.GetBytes(size == 1 ? (byte)state : (ushort)state);
     }
     name += ": ";
     var nameBytes = new UTF8Encoding().GetBytes(name);
     var list = new List<byte>();
     list.AddRange(nameBytes);
     list.AddRange(s);
     list.AddRange(new byte[] { (byte)'\n' });
     func(buf, list.ToArray(), (uint)list.ToArray().Length);
     if (size < 2)
     {
         return s[0];
     }
     else
     {
         return BitConverter.ToUInt16(s, 0);
     }
 }
Example #24
0
        public object Evaluate(IBindingEnvironment environment)
        {
            ICallable callable = (ICallable)environment.GetValue(this.name);

            if (callable == null)
                callable = (ICallable)Machine.Current.Environment.GetValue(this.name);

            List<object> parameters = new List<object>();

            foreach (IExpression expression in this.arguments)
            {
                object parameter = expression.Evaluate(environment);

                if (expression is VariableVariableExpression)
                {
                    if (parameter != null)
                        foreach (object obj in (IEnumerable)parameter)
                            parameters.Add(obj);
                }
                else
                    parameters.Add(parameter);
            }

            if (callable is ILocalCallable)
                return callable.Invoke(environment, parameters.ToArray());

            return callable.Invoke(parameters.ToArray());
        }
        /// <summary>
        /// 구성 섹션 처리기를 만듭니다.
        /// </summary>
        /// <returns>
        /// 만들어진 섹션 처리기 개체입니다.
        /// </returns>
        /// <param name="parent">부모 개체입니다.</param><param name="configContext">구성 컨텍스트 개체입니다.</param>
        /// <param name="section">섹션 XML 노드입니다.</param>
        public object Create(object parent, object configContext, XmlNode section) {
            if(log.IsInfoEnabled)
                log.Info("MongoDB를 NHibernate 2nd 캐시로 사용하기 위해, 환경설정 값을 로드합니다...");

            var cacheConfigs = new List<RavenCacheConfig>();

            if(section == null)
                return cacheConfigs.ToArray();

            XmlNodeList nodes = section.SelectNodes(SR.NodeCache);

            if(nodes == null)
                return cacheConfigs.ToArray();

            foreach(XmlElement node in nodes) {
                var region = node.AttributeToString(SR.AttrRegion, SR.DefaultRegionName);
                var connectionString = node.AttributeToString(SR.AttrConnectionString, SR.DefaultConnectionString);
                var expiration = node.AttributeToString(SR.AttrExpiration, SR.DefaultExpiry.ToString());
                var compressThreshold = node.AttributeToString(SR.AttrCompressThreshold, "4096");

                if(IsDebugEnabled)
                    log.Debug("MongoDB를 이용한 NHibernate.Caches의 환경설정 정보. " +
                              @"region=[{0}],connectionString=[{1}], expiration=[{2}], compressThreshold=[{3}] bytes",
                              region, connectionString, expiration, compressThreshold);

                cacheConfigs.Add(new RavenCacheConfig(region, connectionString, expiration, compressThreshold));
            }

            if(IsDebugEnabled) {
                log.Debug("MongoDB를 NHibernate 2nd 캐시로 사용하기 위해, 환경설정 값을 모두 로드했습니다. ");
                cacheConfigs.ForEach(cfg => log.Debug(cfg));
            }

            return cacheConfigs.ToArray();
        }
    public string[] GetEmployee(string prefixText, int count)
    {
        MatterView BEL = new MatterView();
        DataTable dt = BEL.SelectLikeDataAssignedLawyer(prefixText.ToUpper());

        List<string> txtItems = new List<string>();
        String dbValues;
        String dbValues1;

        foreach (DataRow row in dt.Rows)
        {
            //String From DataBase(dbValues)
            dbValues1 = row["Employee_Id"].ToString().ToUpper();
            dbValues = row["UserName"].ToString().ToUpper();
            dbValues = dbValues.ToUpper();
            txtItems.Add(string.Format("{0} {1}", dbValues1, dbValues));
            // txtItems.Add(dbValues,);

            if (txtItems.Count > count)
            {
                return txtItems.ToArray();
            }
        }

        return txtItems.ToArray();
    }
Example #27
0
    public static int GetDockedVesselsCount(Vessel Vsl) {
      List<uint> MissionIds = new List<uint> ();
      ProtoPartSnapshot[] Parts = Vsl.protoVessel.protoPartSnapshots.ToArray();

      for (int i = 0; i < Parts.Length; i++) {
        uint missionId = Parts [i].missionID;
        bool found = false;
        for (int k = 0; k < MissionIds.ToArray ().Length; k++) {
          uint _missionId = MissionIds.ToArray () [k];
          if (missionId == _missionId) {
            found = true;
          }
        }

        if (!found) {
          MissionIds.Add (missionId);
        }
      }

      int missionCount = MissionIds.Count - 1;

      if (OnAstroid (Vsl)) {
        missionCount--;
      }

      return missionCount;
    }
Example #28
0
        public void ArrayLiterals()
        {
            //You don't have to specify a type if the arguments can be inferred
            var array = new [] { 42 };
            Assert.Equal(typeof(int[]), array.GetType());
            Assert.Equal(new int[] { 42 }, array);

            //Are arrays 0-based or 1-based?
            Assert.Equal(42, array[((int)0)]);

            //This is important because...
            Assert.True(array.IsFixedSize);

            //...it means we can't do this: array[1] = 13;
            Assert.Throws(typeof(IndexOutOfRangeException), delegate() { array[1] = 13; });

            //This is because the array is fixed at length 1. You could write a function
            //which created a new array bigger than the last, copied the elements over, and
            //returned the new array. Or you could do this:
            List<int> dynamicArray = new List<int>();
            dynamicArray.Add(42);
            Assert.Equal(array, dynamicArray.ToArray());

            dynamicArray.Add(13);
            Assert.Equal((new int[] { 42, (int)13}), dynamicArray.ToArray());
        }
Example #29
0
        public static string[] FindVars(string find, int max)
        {
            List<string> Ret = new List<string>();
            string[] Keys = (string[])CVars.Keys.ToArray();
            for (int x = 0; x < Keys.Length; x++)
            {
                if (Keys.Contains(find))
                {
                    foreach (string S in Keys)
                    {
                        if (S.Contains(find))
                        {
                            if (Ret.Count == max)
                                return Ret.ToArray();
                            Ret.Add(S);
                        }

                    }
                }
                else
                {
                    return new string[0];
                }
            }

            return Ret.ToArray();
        }
		protected override void InitializeInternal()
		{
			var name = new List<byte>();
			var data = new List<byte>();
			bool isName = true;
			foreach (var singleByte in _content.ToArray())
			{
				if (singleByte == '=')
				{
					isName = false;
				}
				else if (singleByte == '&')
				{
					isName = true;
					this[_encoding.GetString(name.ToArray())] = _encoding.GetString(data.ToArray());
					name.Clear();
					data.Clear();
				}
				else
				{
					if (isName)
					{
						name.Add(singleByte);
					}
					else
					{
						data.Add(singleByte);
					}
				}
			}
			if (data.Count > 0 && name.Count > 0)
			{
				this[_encoding.GetString(name.ToArray())] = _encoding.GetString(data.ToArray());
			}
		}