示例#1
1
    public CharaController(CharaConfiguration chara, Configuration config, GameObject[] objs, bool debug = false)
    {
        _chara = chara;
        _config = config;

        _objs = objs;
        _joints = new ConfigurableJoint[_objs.Length];
        _rigs = new Rigidbody[_objs.Length];
        _init_rot = new Quaternion[_objs.Length];
        _target_rot = new Quaternion[_objs.Length];
        _target_pos = new Vector3[_objs.Length];

        _debug = debug;

        for (int i = 0; i < _objs.Length; ++i) {
            _rigs[i] = _objs[i].GetComponent<Rigidbody>();
            /*
            if (_debug)
                _rigs[i].isKinematic = true;
                */
            _init_rot[i] = _objs[i].transform.localRotation;
            _target_rot[i] = _init_rot[i];

            _joints[i] = _objs[i].GetComponent<ConfigurableJoint>();
        }

        InitializeJoints();
    }
 public void should_load_config_from_path()
 {
     var config = new Configuration(configPath: "alt.config").LoadSection<Application>("alt");
     config.Build.Date.ShouldEqual(DateTime.Parse("10/25/1985"));
     config.Build.DeployTarget.ShouldEqual(Target.Dev);
     config.Build.Version.ShouldEqual("0.0.0.0");
 }
		/// <summary>
		/// Standar Configuration for tests.
		/// </summary>
		/// <returns>The configuration using merge between App.Config and hibernate.cfg.xml if present.</returns>
		public static Configuration GetDefaultConfiguration()
		{
			Configuration result = new Configuration();
			if (hibernateConfigFile != null)
				result.Configure(hibernateConfigFile);
			return result;
		}
 public void should_load_config_from_xml_type_name()
 {
     var config = new Configuration().LoadSection<ApplicationWithXmlTypeName>();
     config.Build.Date.ShouldEqual(DateTime.Parse("11/26/1986"));
     config.Build.DeployTarget.ShouldEqual(Target.CI);
     config.Build.Version.ShouldEqual("1.1.1.1");
 }
        public void SetUp()
        {
            disposables = new CompositeDisposable
            {
                VirtualClock.Start()
            };

            clockName = Any.CamelCaseName();
            targetId = Any.Word();
            target = new CommandTarget(targetId);
            store = new InMemoryStore<CommandTarget>(
                _ => _.Id,
                id => new CommandTarget(id))
            {
                target
            };

            configuration = new Configuration()
                .UseInMemoryCommandScheduling()
                .UseDependency<IStore<CommandTarget>>(_ => store)
                .UseDependency<GetClockName>(c => _ => clockName)
                .TraceScheduledCommands();

            scheduler = configuration.CommandScheduler<CommandTarget>();

            Command<CommandTarget>.AuthorizeDefault = (commandTarget, command) => true;

            disposables.Add(ConfigurationContext.Establish(configuration));
            disposables.Add(configuration);
        }
示例#6
0
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 512;

            // Increase disk quota for mbrace filesystem cache.
            string customTempLocalResourcePath = RoleEnvironment.GetLocalResource("LocalMBraceCache").RootPath;
            Environment.SetEnvironmentVariable("TMP", customTempLocalResourcePath);
            Environment.SetEnvironmentVariable("TEMP", customTempLocalResourcePath);

            bool result = base.OnStart();

            _config = Configuration.Default
                        .WithStorageConnectionString(CloudConfigurationManager.GetSetting("MBrace.StorageConnectionString"))
                        .WithServiceBusConnectionString(CloudConfigurationManager.GetSetting("MBrace.ServiceBusConnectionString"));

            _svc =
                RoleEnvironment.IsEmulated ?
                new Service(_config) : // Avoid long service names when using emulator
                new Service(_config, serviceId: RoleEnvironment.CurrentRoleInstance.Id.Split('.').Last());

            _svc.AttachLogger(new CustomLogger(s => Trace.WriteLine(String.Format("{0} : {1}", DateTime.UtcNow, s))));

            RoleEnvironment.Changed += RoleEnvironment_Changed;

            return result;
        }
示例#7
0
        public Conventions(Configuration configuration)
        {
            Actions.FindBy(x => {
                x.Applies.ToThisAssembly();
                x.IncludeTypesNamed(y => y.EndsWith("Handler"));
            });
            
            Routes
                .HomeIs<GetHandler>(x => x.Execute())
                .IgnoreMethodSuffix("Execute")
                .IgnoreControllerNamesEntirely()
                .IgnoreControllerNamespaceEntirely()
                .ConstrainToHttpMethod(action => action.HandlerType.Name.EndsWith("GetHandler"), "GET");

            Services(x =>
            {
                x.AddService(configuration);
                x.AddService<IDescriptionConvention<BehaviorChain, ModuleDescription>>(configuration.ModuleConvention.Type, configuration.ModuleConvention.Config)
                 .AddService<IDescriptionConvention<BehaviorChain, ResourceDescription>>(configuration.ResourceConvention.Type, configuration.ResourceConvention.Config)
                 .AddService<IDescriptionConvention<BehaviorChain, EndpointDescription>>(configuration.EndpointConvention.Type, configuration.EndpointConvention.Config)
                 .AddService<IDescriptionConvention<PropertyInfo, MemberDescription>>(configuration.MemberConvention.Type, configuration.MemberConvention.Config)
                 .AddService<IDescriptionConvention<System.Type, EnumDescription>>(configuration.EnumConvention.Type, configuration.EnumConvention.Config)
                 .AddService<IDescriptionConvention<FieldInfo, EnumOptionDescription>>(configuration.EnumOptionConvention.Type, configuration.EnumOptionConvention.Config)
                 .AddService<IDescriptionConvention<BehaviorChain, List<StatusCodeDescription>>>(configuration.StatusCodeConvention.Type, configuration.StatusCodeConvention.Config)
                 .AddService<IDescriptionConvention<BehaviorChain, List<HeaderDescription>>>(configuration.HeaderConvention.Type, configuration.HeaderConvention.Config)
                 .AddService<IDescriptionConvention<BehaviorChain, List<MimeTypeDescription>>>(configuration.MimeTypeConvention.Type, configuration.MimeTypeConvention.Config)
                 .AddService<IDescriptionConvention<System.Type, TypeDescription>>(configuration.TypeConvention.Type, configuration.TypeConvention.Config);
            });
        }
示例#8
0
 public static BulkLoader Create(Configuration.Configuration config)
 {
     Type providerType = config.Provider.BulkInsertType;
     BulkLoader result = (BulkLoader) Activator.CreateInstance(providerType, new object[] {config});
     result.Configure();
     return result;
 }
 /// <summary>
 /// Constructor which takes the connection string name
 /// </summary>
 /// <param name="connectionStringName"></param>
 public MySQLDatabase(string connectionStringName)
 {
     var configuration = new Configuration()
         .AddJsonFile("config.json");
     string connectionString = configuration[connectionStringName];
     _connection = new MySqlConnection(connectionString);
 }
示例#10
0
        public void Create(Configuration cfg, OSPCResult r)
        {
            _cfg = cfg;

            if (!Directory.Exists(OutPath))
            {
                Directory.CreateDirectory(OutPath);
            }

            if(!Directory.Exists(Path.Combine(OutPath, "Matches")))
            {
                Directory.CreateDirectory(Path.Combine(OutPath, "Matches"));
            }

            CreateSummaryPage(r);
            CreateDetailPages(r);
            CreateFriendFinderPage(r);

            CreateTokenGraph(r);
            CreateTokenDetailGraph(r);
            CreatePercentGraph(r);
            CreateTokenMatchGraph(r);

            WriteStylesheet();
        }
示例#11
0
 protected BulkLoader(Configuration.Configuration config)
 {
     _jobs = new JobList();
     _jobs.RowsInserted += (s, e) => OnRowsInserted(e);
     Config = config;
     DefaultSchema = "dbo";
 }
示例#12
0
        void RoleEnvironment_Changed(object sender, RoleEnvironmentChangedEventArgs e)
        {
            try
            {
                foreach (var item in e.Changes.OfType<RoleEnvironmentTopologyChange>())
                {
                    if (item.RoleName == RoleEnvironment.CurrentRoleInstance.Role.Name)
                    {
                        // take any action needed on instance count modification; gracefully shrink etc
                    }
                }

                foreach (var item in e.Changes.OfType<RoleEnvironmentConfigurationSettingChange>())
                {
                    if (item.ConfigurationSettingName == "MBrace.ServiceBusConnectionString"
                        || item.ConfigurationSettingName == "MBrace.StorageConnectionString")
                    {
                        string storageConnectionString = CloudConfigurationManager.GetSetting("MBrace.StorageConnectionString");
                        string serviceBusConnectionString = CloudConfigurationManager.GetSetting("MBrace.ServiceBusConnectionString");
                        _config = new Configuration(storageConnectionString, serviceBusConnectionString);
                        _svc.Stop();
                        _svc.Configuration = _config;
                        _svc.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("MBrace.Azure.WorkerRole RoleEnvironment_Changed unhandled exception: {0}", ex);
                throw;
            }
        }
示例#13
0
        private void button1_Click(object sender, EventArgs e)
        {
            var cfg = new Configuration();
            cfg.Configure();
            cfg.AddAssembly(typeof(Domain.User).Assembly);

            var sessions = cfg.BuildSessionFactory();
            var sess = sessions.OpenSession();
            var new_user = new Domain.User

            {
                Name = textBox1.Text,
                Surname = textBox2.Text,
                Patronymic = textBox3.Text,
                Role_id = 1,
                Login = textBox4.Text,
                Pass = textBox5.Text
            };
            if (new_user.Name.Length > 0 && new_user.Surname.Length > 0 && new_user.Patronymic.Length > 0 && new_user.Login.Length > 0 && new_user.Pass.Length > 0)
            {
                sess.Save(new_user);
                sess.Flush();
                this.Hide();
            }
            else
            {
                label6.Text = "Не все поля заполнены!";
            }
        }
        public void SetUp()
        {
            eventStoreDbTest = new EventStoreDbTest();
            clockName = Any.CamelCaseName();

            Clock.Reset();

            disposables = new CompositeDisposable
            {
                Disposable.Create(() => eventStoreDbTest.TearDown()),
                Disposable.Create(Clock.Reset)
            };

            var bus = new FakeEventBus();
            orderRepository = new SqlEventSourcedRepository<Order>(bus);
            accountRepository = new SqlEventSourcedRepository<CustomerAccount>(bus);

            var configuration = new Configuration();
            configuration.UseEventBus(bus)
                         .UseDependency<IEventSourcedRepository<Order>>(t => orderRepository)
                         .UseDependency<IEventSourcedRepository<CustomerAccount>>(t => accountRepository);

            ConfigureScheduler(configuration);

            disposables.Add(ConfigurationContext.Establish(configuration));

            Console.WriteLine(new { clockName });

            clockTrigger = configuration.Container.Resolve<ISchedulerClockTrigger>();
            clockRepository = configuration.Container.Resolve<ISchedulerClockRepository>();
            clockRepository.CreateClock(clockName, Clock.Now());
        }
示例#15
0
        public override bool OnStart()
        {
            try
            {
                // Increase disk quota for mbrace filesystem cache.
                string customTempLocalResourcePath = RoleEnvironment.GetLocalResource("LocalMBraceCache").RootPath;
                string storageConnectionString = CloudConfigurationManager.GetSetting("MBrace.StorageConnectionString");
                string serviceBusConnectionString = CloudConfigurationManager.GetSetting("MBrace.ServiceBusConnectionString");

                bool result = base.OnStart();

                _config = new Configuration(storageConnectionString, serviceBusConnectionString);
                _svc =
                    RoleEnvironment.IsEmulated ?
                    new WorkerService(_config, String.Format("computeEmulator-{0}", Guid.NewGuid().ToString("N").Substring(0, 30))) :
                    new WorkerService(_config, workerId: Environment.MachineName);

                _svc.WorkingDirectory = customTempLocalResourcePath;
                _svc.LogFile = "logs.txt";
                _svc.MaxConcurrentWorkItems = Environment.ProcessorCount * 8;
                
                Environment.SetEnvironmentVariable("TMP", customTempLocalResourcePath, EnvironmentVariableTarget.Process);
                Environment.SetEnvironmentVariable("TEMP", customTempLocalResourcePath, EnvironmentVariableTarget.Process);

                RoleEnvironment.Changed += RoleEnvironment_Changed;

                return result;
            }
            catch (Exception ex)
            {
                Trace.TraceError("MBrace.Azure.WorkerRole OnStart unhandled exception: {0}", ex);
                throw;
            }
        }
示例#16
0
        public SqlEditor(Configuration cfg, ConnectionProvider provider, FileLink link)
        {
            InitializeComponent(cfg);

            this.cfg = cfg;
            this.provider = provider;

            textBox.Document.Blocks.Clear();
            if (link != null)
            {
                this.link = link;
                string text = link.ReadAllText();
                textBox.Document.Blocks.Add(new Paragraph(new Run(text)));
            }
            else
            {
                this.link = FileLink.CreateLink(untitled);
            }
            UpdateTitle();

            tabControl.SelectionChanged += TabControl_SelectionChanged;
            textBox.SelectionChanged += TextBox_SelectionChanged;
            textBox.TextChanged += TextBox_TextChanged;
            textBox.Focus();
        }
示例#17
0
 public bool Uninstall(Configuration.Config c)
 {
     c.Plugins.remove_plugin(this);
     c.Pipeline.RewriteDefaults -= Pipeline_RewriteDefaults;
     c.Pipeline.PostAuthorizeRequestStart -= Pipeline_PostAuthorizeRequestStart;
     return true;
 }
        public void SetUp()
        {
            disposables = new CompositeDisposable
            {
                VirtualClock.Start()
            };

            clockName = Any.CamelCaseName();
            targetId = Any.Word();
            target = new CommandTarget(targetId);
            store = new InMemoryStore<CommandTarget>(
                _ => _.Id,
                id => new CommandTarget(id))
            {
                target
            };

            CommandSchedulerDbContext.NameOrConnectionString =
                @"Data Source=(localdb)\MSSQLLocalDB; Integrated Security=True; MultipleActiveResultSets=False; Initial Catalog=ItsCqrsTestsCommandScheduler";

            configuration = new Configuration()
                .UseInMemoryCommandScheduling()
                .UseDependency<IStore<CommandTarget>>(_ => store)
                .UseDependency<GetClockName>(c => _ => clockName)
                .TraceScheduledCommands();

            scheduler = configuration.CommandScheduler<CommandTarget>();

            Command<CommandTarget>.AuthorizeDefault = (commandTarget, command) => true;

            disposables.Add(ConfigurationContext.Establish(configuration));
            disposables.Add(configuration);
        }
        private void Configure()
        {
            configuration = new Configuration
            {
                Username = "******",
                Password = "******",

            };

            dcApi = new DataCenterApi(configuration);

            lanApi = new LanApi(configuration);

            //Create a datacenter.
            if (datacenter == null)
            {
                datacenter = new Datacenter
                {
                    Properties = new DatacenterProperties
                    {
                        Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                        Description = "Unit test for .Net SDK PB REST V2",
                        Location = "us/lasdev"
                    }
                };

                datacenter = dcApi.Create(datacenter);
            }
        }
示例#20
0
		private IEnumerable<ScheduledAction> InstantiateActions(IEnumerable<ScheduledAction> registeredActions, Configuration.SchedulerElement schedulerElement)
        {
			var isClear = schedulerElement.IsCleared;
			var removedNames = new HashSet<string>(schedulerElement.RemovedElements.Select(re => re.Name));
			var added = schedulerElement.AddedElements.ToDictionary(ae => ae.Name);
			foreach (var action in registeredActions)
            {
				string name = action.GetType().Name;
				if (removedNames.Contains(name) && !added.ContainsKey(name))
					continue;
				if (isClear && !added.ContainsKey(name))
					continue;
				if (added.ContainsKey(name))
				{
					var actionConfig = added[name];
					if (!string.IsNullOrEmpty(actionConfig.ExecuteOnMachineNamed) && actionConfig.ExecuteOnMachineNamed != Environment.MachineName)
						continue;
				}

				if (added.ContainsKey(name))
				{
					var actionConfig = added[name];
					if (actionConfig.Interval.HasValue)
						action.Interval = actionConfig.Interval.Value;
					if (actionConfig.Repeat.HasValue)
						action.Repeat = actionConfig.Repeat.Value ? Repeat.Indefinitely : Repeat.Once;
				}

                yield return action;
            }
        }
 public IncludeExcludeEngineFactory(IPlainEngine plainEngine, Engine.Minify.IMinifyEngine minifyEngine, Http.IHttp http, Configuration.JsMinifierConfiguration configuration)
 {
     _plainEngine = plainEngine;
     _minifyEngine = minifyEngine;
     _http = http;
     _configuration = configuration;
 }
示例#22
0
 public IPlugin Install(Configuration.Config c)
 {
     this.c = c;
     c.Plugins.add_plugin(this);
     c.Pipeline.PreHandleImage += Pipeline_PreHandleImage;
     return this;
 }
示例#23
0
        private static void CreateStuff(Configuration cfg)
        {
            using (ISessionFactory sessionFactory = cfg.BuildSessionFactory())
            using (ISession session = sessionFactory.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                try
                {
                    var tempUser = new User { Username = "******" };
                    session.Save(tempUser);

                    transaction.Commit();
                }
                catch (Exception e)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(e.Message);
                    Console.ResetColor();
                    transaction.Rollback();
                }
                finally
                {
                    session.Close();
                }
            }
        }
示例#24
0
 public void ConfigurationSetCultureExtensionLeavesOriginallyUnmodified()
 {
     var original = new Configuration();
     var modified = original.SetCulture("de-at");
     Assert.AreNotSame(original, modified);
     Assert.AreNotEqual(original.Services.Count(), modified.Services.Count());
 }
示例#25
0
 static Configuration AddLoquaciousMappings(Configuration nhConfiguration)
 {
     ModelMapper mapper = new ModelMapper();
     mapper.AddMappings(typeof(OrderSagaDataLoquacious).Assembly.GetTypes());
     nhConfiguration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
     return nhConfiguration;
 }
示例#26
0
        public UserInfo GetUserInfoById(int userId)
        {
            Configuration cfg = new Configuration().Configure(path);

            ISession session = cfg.BuildSessionFactory().OpenSession();
            return session.Get<UserInfo>(userId);
        }
示例#27
0
 public void ConfigurationWithExtensionLeavesOriginallyUnmodified()
 {
     var original = new Configuration();
     var modified = original.WithCss();
     Assert.AreNotSame(original, modified);
     Assert.AreNotEqual(original.Services.Count(), modified.Services.Count());
 }
 public FileLogWriter(Configuration.MonitorConfiguration conf)
 {
     this.filePath = conf.LogFilePath;
     this.logFileSize = conf.LogFileSize <= 0 ? DefaultLogFileSize : conf.LogFileSize;
     this.maxLogRetention = conf.MaxLogRetention <= 0 ? DefaultLogRetention : conf.MaxLogRetention;
     Directory.CreateDirectory(Path.GetDirectoryName(this.filePath));
 }
示例#29
0
        public Grabber(CheatEngineReader table, MemoryReader reader)
        {
            Config = new Configuration(this);

            //TEMPORARY configuration!
            Config.SamplesBeforeTrigger = 750;
            Config.SamplesAfterTrigger = 750;
            Config.SampleWaitTime = 10000;//ms, 1ms here

            Config.Trigger_Simple_Channel = 0; // gear
            Config.Trigger_Simple_Condition = TriggerCondition.IN_RANGE; // Rising up
            Config.Trigger_Simple_ValueType = MemoryChannelType.INT32;
            Config.Trigger_Simple_Value = new byte[4] { 3, 0, 0, 0 }; // INT32 (5)
            Config.Trigger_Simple_Value2 = new byte[4] { 5, 0, 0, 0 }; // INT32 (5)
            Config.Trigger_Simple = true;

            Channels = new Channels(this,table);
            Waveform = new Waveform(this);
            Trigger = new Triggering(this);

            this.Reader = reader;

            _mGrabberTiming = new MicroStopwatch();

            TritonBase.PreExit += Stop;
        }
        public void SetUp()
        {
            Clock.Reset();

            disposables = new CompositeDisposable
            {
                Disposable.Create(Clock.Reset)
            };

            schedule = GetScheduleDelegate();

            commandsScheduled = new ConcurrentBag<IScheduledCommand>();
            commandsDelivered = new ConcurrentBag<IScheduledCommand>();

            var configuration = new Configuration()
                .TraceScheduledCommands() // trace to console
                .TraceScheduledCommands(
                    onScheduling: _ => { },
                    onScheduled: c => commandsScheduled.Add(c),
                    onDelivering: _ => { },
                    onDelivered: c => commandsDelivered.Add(c));

            Configure(configuration, d => disposables.Add(d));

            disposables.Add(ConfigurationContext.Establish(configuration));
        }
示例#31
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, MyContext myContext, ITasksQzServices tasksQzServices, ISchedulerCenter schedulerCenter, IHostApplicationLifetime lifetime)
        {
            // Ip限流,尽量放管道外层
            app.UseIpLimitMildd();
            // 记录请求与返回数据 
            app.UseReuestResponseLog();
            // 用户访问记录(必须放到外层,不然如果遇到异常,会报错,因为不能返回流)
            app.UseRecordAccessLogsMildd();
            // signalr 
            app.UseSignalRSendMildd();
            // 记录ip请求
            app.UseIPLogMildd();
            // 查看注入的所有服务
            app.UseAllServicesMildd(_services);

            if (env.IsDevelopment())
            {
                // 在开发环境中,使用异常页面,这样可以暴露错误堆栈信息,所以不要放在生产环境。
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // 在非开发环境中,使用HTTP严格安全传输(or HSTS) 对于保护web安全是非常重要的。
                // 强制实施 HTTPS 在 ASP.NET Core,配合 app.UseHttpsRedirection
                //app.UseHsts();
            }

            app.UseSession();
            app.UseSwaggerAuthorized();
            // 封装Swagger展示
            app.UseSwaggerMildd(() => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("Blog.Core.Api.index.html"));

            // ↓↓↓↓↓↓ 注意下边这些中间件的顺序,很重要 ↓↓↓↓↓↓

            // CORS跨域
            app.UseCors(Appsettings.app(new string[] { "Startup", "Cors", "PolicyName" }));
            // 跳转https
            //app.UseHttpsRedirection();
            // 使用静态文件
            app.UseStaticFiles();
            // 使用cookie
            app.UseCookiePolicy();
            // 返回错误码
            app.UseStatusCodePages();
            // Routing
            app.UseRouting();
            // 这种自定义授权中间件,可以尝试,但不推荐
            // app.UseJwtTokenAuth();

            // 测试用户,用来通过鉴权
            if (Configuration.GetValue<bool>("AppSettings:UseLoadTest"))
            {
                app.UseMiddleware<ByPassAuthMidd>();
            }
            // 先开启认证
            app.UseAuthentication();
            // 然后是授权中间件
            app.UseAuthorization();
            //开启性能分析
            app.UseMiniProfilerMildd();
            // 开启异常中间件,要放到最后
            //app.UseExceptionHandlerMidd();


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapHub<ChatHub>("/api2/chatHub");
            });

            // 生成种子数据
            app.UseSeedDataMildd(myContext, Env.WebRootPath);
            // 开启QuartzNetJob调度服务
            app.UseQuartzJobMildd(tasksQzServices, schedulerCenter);
            // 服务注册
            app.UseConsulMildd(Configuration, lifetime);
            // 事件总线,订阅服务
            app.ConfigureEventBus();

        }
示例#32
0
 /// <inheritdoc />
 public async Task <Image> DecodeAsync(Configuration configuration, Stream stream, CancellationToken cancellationToken)
 => await this.DecodeAsync <Rgba32>(configuration, stream, cancellationToken)
 .ConfigureAwait(false);
示例#33
0
 /// <inheritdoc />
 public Image Decode(Configuration configuration, Stream stream)
 => this.Decode <Rgba32>(configuration, stream);
示例#34
0
        public Games(FloraRandom random, FloraDebugLogger logger, BotGameHandler botGames, WoodcuttingLocker woodcuttingLocker, Configuration config, HeartLocker heartLocker)
        {
            _random   = random;
            _logger   = logger;
            _botGames = botGames;
            _config   = config;

            _woodcuttingLocker = woodcuttingLocker;
            _healthLocker      = heartLocker;
        }
示例#35
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTestStuff();
            services.AddLogging().AddRouting(options => { options.LowercaseUrls = true; });

            services.AddMvc(options => options.AddMetricsResourceFilter());

            var reportFilter = new DefaultMetricsFilter();

            reportFilter.WithHealthChecks(false);

            services.AddMetrics(Configuration.GetSection("AppMetrics")).
            // AddJsonMetricsSerialization().
            // AddElasticsearchMetricsSerialization(ElasticSearchIndex).
            AddJsonMetricsSerialization().
            AddAsciiHealthSerialization().
            AddAsciiMetricsTextSerialization().
            // AddPrometheusPlainTextSerialization().
            // AddInfluxDBLineProtocolMetricsTextSerialization().
            // AddAsciiEnvironmentInfoSerialization().
            AddJsonEnvironmentInfoSerialization().
            AddReporting(
                factory =>
            {
                if (ReportTypes.Any(r => r == ReportType.InfluxDB))
                {
                    factory.AddInfluxDb(
                        new InfluxDBReporterSettings
                    {
                        HttpPolicy = new HttpPolicy
                        {
                            FailuresBeforeBackoff = 3,
                            BackoffPeriod         = TimeSpan.FromSeconds(30),
                            Timeout = TimeSpan.FromSeconds(10)
                        },
                        InfluxDbSettings = new InfluxDBSettings(InfluxDbDatabase, InfluxDbUri),
                        ReportInterval   = TimeSpan.FromSeconds(5)
                    },
                        reportFilter);

                    if (ReportTypes.Any(r => r == ReportType.ElasticSearch))
                    {
                        factory.AddElasticSearch(
                            new ElasticSearchReporterSettings
                        {
                            HttpPolicy = new Extensions.Reporting.ElasticSearch.HttpPolicy
                            {
                                FailuresBeforeBackoff = 3,
                                BackoffPeriod         = TimeSpan.FromSeconds(30),
                                Timeout = TimeSpan.FromSeconds(10)
                            },
                            ElasticSearchSettings = new ElasticSearchSettings(ElasticSearchUri, ElasticSearchIndex),
                            ReportInterval        = TimeSpan.FromSeconds(5)
                        },
                            reportFilter);
                    }

                    //if (ReportTypes.Any(r => r == ReportType.Graphite))
                    //{
                    //    factory.AddGraphite(
                    //        new GraphiteReporterSettings
                    //        {
                    //            HttpPolicy = new Extensions.Reporting.Graphite.HttpPolicy
                    //            {
                    //                FailuresBeforeBackoff = 3,
                    //                BackoffPeriod = TimeSpan.FromSeconds(30),
                    //                Timeout = TimeSpan.FromSeconds(3)
                    //            },
                    //            GraphiteSettings = new GraphiteSettings(GraphiteUri),
                    //            ReportInterval = TimeSpan.FromSeconds(5)
                    //        });
                    //}
                }
            }).
            AddHealthChecks(
                factory =>
            {
                factory.RegisterPingHealthCheck("google ping", "google.com", TimeSpan.FromSeconds(10));

                factory.RegisterHttpGetHealthCheck("github", new Uri("https://github.com/"), TimeSpan.FromSeconds(10));

                factory.RegisterMetricCheck(
                    name: "Database Call Duration",
                    options: SandboxMetricsRegistry.DatabaseTimer,
                    tags: new MetricTags("client_id", "client-9"),
                    passing: value => (message: $"OK. 98th Percentile < 100ms ({value.Histogram.Percentile98}{SandboxMetricsRegistry.DatabaseTimer.DurationUnit.Unit()})", result: value.Histogram.Percentile98 < 100),
                    warning: value => (message: $"WARNING. 98th Percentile > 100ms ({value.Histogram.Percentile98}{SandboxMetricsRegistry.DatabaseTimer.DurationUnit.Unit()})", result: value.Histogram.Percentile98 < 200),
                    failing: value => (message: $"FAILED. 98th Percentile > 200ms ({value.Histogram.Percentile98}{SandboxMetricsRegistry.DatabaseTimer.DurationUnit.Unit()})", result: value.Histogram.Percentile98 > 200));
            }).
            AddMetricsMiddleware(Configuration.GetSection("AspNetMetrics"));
        }
示例#36
0
 public override void OnConfigurationChanged(Configuration newConfig)
 {
     _gridViewColumnHelper.OnConfigurationChanged(newConfig);
     base.OnConfigurationChanged(newConfig);
 }
示例#37
0
 public virtual Configuration LoadFileFromIni(string location)
 {
     return(Configuration.LoadFromFile(location));
 }
示例#38
0
 public Users(Configuration configuration) : base(configuration)
 {
     BaseUri = "users";
 }
示例#39
0
 protected void Application_Start(object sender, EventArgs e)
 {
     Configuration.LoadConfiguration(new string [] {});
 }
示例#40
0
 public override void Configure(Configuration configuration)
 {
     configuration.EngineDefaults.Logging.IsEnableQueryPlan = true;
 }
示例#41
0
        public string GetCstring() {

             return Configuration.GetConnectionString("Database");
             
        }
        /// <summary>
        /// get and return the value of the configuration settings for keyname
        /// </summary>
        /// <param name="config">Configuration of the assembly</param>
        /// <param name="keyName">keyName to be found from the settings file</param>
        /// <exception cref="System.NullReferenceException">if keyname not found in the configuration file</exception>
        /// <exception cref="System.NullReferenceException">if DEFAULT_APPLICATION_ENVIRONMENT_SETTINGS not found in the configuration file</exception>
        /// <exception cref="System.NullReferenceException">if element is not found </exception>
        /// <exception cref="System.NullReferenceException">if value is not found </exception>
        /// <returns>return the value in the configuration for the keyname</returns>
        private string GetConfigurationValue(Configuration config, string keyName)
        {
            //userSettings for windows application settings/applicationSettings for webservices
            ConfigurationSectionGroup sectionGroup = config.SectionGroups[SECTION_GROUP_NAME];

            if (sectionGroup == null) // failed to get sectiongroup
            {
                //implement system exception
                MessageData messageData = new MessageData("ffce00005", Properties.Resources.ffce00005);
                logger.Error(messageData, new NullReferenceException());

                throw new SystemException(messageData, new NullReferenceException());
            }

            //read default settings file first
            SettingElement element = GetConfigurationElement(sectionGroup, DEFAULT_SETTINGS_NAME, keyName);

            if (element == null)  // if element not found in default settings file then get from applicatoin setting file
            {
                string applicationSettingsFileName = configValueMap.ContainsKey(APPLICATION_ENVIRONMENT_SETTINGS) ? (string)configValueMap[APPLICATION_ENVIRONMENT_SETTINGS] : null;

                if (applicationSettingsFileName == null) //if APPLICATION_ENVIRONMENT_SETTINGS not found in cache memory throw exception
                {
                    //temporary solution to get APPLICATION_ENVIRONMENT_SETTINGS
                    applicationSettingsFileName = GetConfigurationValue(config, APPLICATION_ENVIRONMENT_SETTINGS);

                    if (applicationSettingsFileName == null)
                    {
                        //implement system exception
                        MessageData messageData = new MessageData("ffce00030", Properties.Resources.ffce00030, keyName);
                        logger.Error(messageData, new NullReferenceException());

                        throw new SystemException(messageData, new NullReferenceException());
                    }
                }

                element = GetConfigurationElement(sectionGroup, applicationSettingsFileName, keyName);
            }

            if (element == null) // failed to get element
            {
                //implement system exception
                MessageData messageData = new MessageData("ffce00036", Properties.Resources.ffce00036, keyName);
                logger.Error(messageData, new NullReferenceException());

                throw new SystemException(messageData, new NullReferenceException());
            }

            //get the exact value from innertext of the element
            string value = element.Value.ValueXml.InnerText;

            if (value == null) //value is not available for the keyname
            {
                //implement system exception
                MessageData messageData = new MessageData("ffce00034", Properties.Resources.ffce00034, keyName);
                logger.Error(messageData, new NullReferenceException());

                throw new SystemException(messageData, new NullReferenceException());
            }

            return(value);
        }
示例#43
0
 public static string GetVerificationWaitingMessage(string mention, int profileid, string token)
 {
     return($"Thanks {mention}! The verification process has been initiated. All you have to do now is to paste the below token in your profile biography and type `/verify done` so I can have a quick look over it to verify you." +
            "\n" +
            "\n" +
            $"Profile URL: {Configuration.GetVariable("Urls.Forum.Profile")}{profileid}" +
            "\n" +
            $"Token: **{token}**" +
            "\n" +
            "\n" +
            $"You can edit profile biography here: <http://forum.sa-mp.com/profile.php?do=editprofile> in the 'Additional Information' section at the end of the page." +
            "\n" +
            $"Please make sure your \"About Me\" profile section is visible to *Everyone* so I can see it.  You can change this setting here: <{Configuration.GetVariable("Urls.Forum.Settings")}>" +
            "\n" +
            "\n" +
            "Facing trouble? Ask for help on Discord!");
 }
        /// <summary>
        /// Create a refund Creates a refund for a previously authorised or captured charge. See #model:xWJer4QQyRumRi9LD for more information.  This endpoint will return 201 or otherwise 402 if unable to perform the refund.   | Error code | Description | |- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -|- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -| | account_inoperative | The account is in arrears or closed and cannot be charged | | amount_invalid | The refund amount is greater than the remaining captured total | | invalid_state | 1. The charge is already fully refunded |
        /// </summary>
        /// <exception cref="MerchantApi.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="body"> (optional)</param>
        /// <param name="idempotencyKey">The unique idempotency key. (optional)</param>
        /// <returns>Task of ApiResponse (Refund)</returns>
        public async System.Threading.Tasks.Task<ApiResponse<RefundOrder>> RefundsCreateAsyncWithHttpInfo (CreateRefundRequest body = null, string idempotencyKey = null)
        {

            var localVarPath = "/refunds";
            var localVarPathParams = new Dictionary<String, String>();
            var localVarQueryParams = new Dictionary<String, String>();
            var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
            var localVarFormParams = new Dictionary<String, String>();
            var localVarFileParams = new Dictionary<String, FileParameter>();
            Object localVarPostBody = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/javascript"
            };
            String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
            if (localVarHttpHeaderAccept != null)
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);

            // set "format" to json by default
            // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
            localVarPathParams.Add("format", "json");
            if (idempotencyKey != null) localVarHeaderParams.Add("Idempotency-Key", Configuration.ApiClient.ParameterToString(idempotencyKey)); // header parameter
            if (body != null && body.GetType() != typeof(byte[]))
            {
                localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
            }
            else
            {
                localVarPostBody = body; // byte array
            }

            // authentication (Authorization) required
            if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization")))
            {
                localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization");
            }

            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
                Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int) localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("RefundsCreate", localVarResponse);
                if (exception != null) throw exception;
            }

            return new ApiResponse<RefundOrder>(localVarStatusCode,
                localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                (RefundOrder) Configuration.ApiClient.Deserialize(localVarResponse, typeof(RefundOrder)));
            
        }
示例#45
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Config of Context, Cors and DependencyInjection
            //inject on this class the configuration coming from my .json
            //services.AddSingleton<IWebHostEnvironment>(Environment);
            var appSettingsSection = Configuration.GetSection("AppSettings");
            services.Configure <AppSettings>(appSettingsSection);

            var appSettings = appSettingsSection.Get <AppSettings>();
            var key         = Encoding.ASCII.GetBytes(appSettings.TokenSecret); //I will get a Key of my TokenSecret

            services.AddScoped <AppFullStackDemoContext>();
            services.AddDbContext <AppFullStackDemoContext>(options =>
                                                            options.UseSqlServer(Configuration.GetConnectionString("ServerLocalConnection")));

            services.AddTransient <IUow, Uow>();
            services.AddTransient <IDeviceModelRepository, DeviceModelRepository>();
            services.AddTransient <IEquipmentRepository, EquipmentRepository>();
            services.AddTransient <IManufacturerRepository, ManufacturerRepository>();
            services.AddTransient <IUserRepository, UserRepository>();
            services.AddTransient <IUserClaimRepository, UserClaimRepository>();
            services.AddTransient <IClaimRepository, ClaimRepository>();

            services.AddTransient <DeviceModelHandler, DeviceModelHandler>();
            services.AddTransient <EquipmentHandler, EquipmentHandler>();
            services.AddTransient <ManufacturerHandler, ManufacturerHandler>();
            services.AddTransient <UserHandler, UserHandler>();
            services.AddTransient <DashBoardHandler, DashBoardHandler>();

            #endregion Config of Cors DependencyInjection

            #region Config of EF Context / ConnectionString and Json Options
            services.AddCors(options =>
                             options.AddPolicy("AppFullStackDemoCors",
                                               builder =>
            {
                builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
            }
                                               )
                             );


            services
            .AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver      = new DefaultContractResolver();
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });


            #endregion Config of EF Context / ConnectionString / Postgres and Json Options

            #region Config of JWT
            //Jwt Authentication
            //first of all i get the config in .Json and Cast to my Class AppSettings
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false; //if i set it to true, it will allow only https (secure)
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,                          //will validate my "Emiter" (needs to be the name of my system)
                    IssuerSigningKey         = new SymmetricSecurityKey(key), //my key (needs to keep it very very safe)
                    ValidateIssuer           = true,                          //will validate the name of my system backend (check in Settings.Emiter)
                    ValidateAudience         = true,                          //will check my URL (that's specific in Settings.ValidIn - default there is http://localhost)
                    ValidIssuer      = appSettings.Emiter,
                    ValidAudience    = appSettings.ValidIn,                   //Note: I can use ValidIssuers and ValidAudiences (with S) and pass a IEnumerable, setting various systems, like AngularApp, MobileApp... just configure and use
                    ClockSkew        = TimeSpan.Zero,
                    ValidateLifetime = true                                   //With this Two flags I ensure that Token will only be valid for 5 minutes (or whats configured on the JWT generation)
                                                                              //NOTE: More information about these Fields you can see on Class AppSettings.cs in Details
                };
            });
            #endregion Config of JWT

            //var dbContext = services.BuildServiceProvider().GetService<AppFullStackDemoContext>();
            //SeedMockDataCreator.CreateMockData(dbContext);
        }
示例#46
0
        public static ISessionFactory createSessionFactorie(ConnectionDB conexion = null, int tipoDb = -1)
        {
            var    cfg      = new Configuration();
            String server   = conexion == null ? "" : conexion.server;
            String database = conexion == null ? "" : conexion.nombreBd;
            String user     = conexion == null ? "" : conexion.usuario;
            String pass     = conexion == null ? "" : conexion.password;
            String port     = conexion == null ? "" : conexion.puertoServer;

            String cxn = null;

            if (conexion.tipoServer == TypeDB.SQLServer)//SQLServer
            {
                cfg.DataBaseIntegration(x =>
                {
                    cxn = "Server=" + server + ";" + "Database=" + database + ";" + "Uid=" + user + ";" + "Pwd=" + pass + ";";
                    x.ConnectionString = cxn;
                    x.Dialect <MsSql2012Dialect>();
                    x.LogSqlInConsole = true;
                    x.BatchSize       = 30;
                });

                //  cfg.SetProperty(NHibernate.Cfg.Environment.DefaultSchema, "dbo");
            }
            if (conexion.tipoServer == TypeDB.MySQL)
            {
                cfg.DataBaseIntegration(x =>
                {
                    cxn = "Server=" + server + ";" + "Port=" + port + ";" + "database=" + database + ";" + "user="******";"
                          + "password="******";" /*+ "sslmode=" + "none" + ";"*/;
                    x.ConnectionString = cxn;
                    x.Dialect <MySQL5Dialect>();
                    x.LogSqlInConsole = true;
                    x.BatchSize       = 30;
                });
            }

            cfg.SetProperty("current_session_context_class", "web");
            //Create or update for first | validate for Production
            if (conexion == null)
            {
                /* cfg.AddFile(HttpContext.Current.Server.MapPath(@"~\mapeos\ServidoresBd.hbm.xml"));*/
            }

            if (tipoDb == 1)
            {   //Master
                /*Options: create, update, validate*/
                cfg.SetProperty("hbm2ddl.auto", "validate");
                Hibernate.HBClass.AddAssemblyMaster(cfg);
            }
            else if (tipoDb == 2)
            {   //Simple
                /*Options: create, update, validate*/
                cfg.SetProperty("hbm2ddl.auto", "validate");
                Hibernate.HBClass.AddAssemblySimple(cfg);
            }
            else if (tipoDb == 3)
            {   //DBLogin
                /*Options: create, update, validate*/
                cfg.SetProperty("hbm2ddl.auto", "validate");
                Hibernate.HBClass.AddAssemblyLogin(cfg);
            }

            var sefact = createFactory(cfg, cxn);

            return(sefact);
        }
 private void OnCompilationStartAction(CompilationStartAnalysisContext context, Configuration config)
 {
     context.RegisterSyntaxNodeAction(ctx => CheckAllowHtml(ctx, VBSyntaxNodeHelper.Default), VB.SyntaxKind.PropertyBlock);
     context.RegisterSyntaxNodeAction(ctx => CheckUnvalidated(ctx, VBSyntaxNodeHelper.Default), VB.SyntaxKind.SimpleMemberAccessExpression);
     context.RegisterSyntaxNodeAction(ctx => CheckValidateInput(ctx, VBSyntaxNodeHelper.Default), VB.SyntaxKind.FunctionBlock);
     context.RegisterSyntaxNodeAction(ctx => CheckValidateInput(ctx, VBSyntaxNodeHelper.Default), VB.SyntaxKind.SubBlock);
     context.RegisterSyntaxNodeAction(ctx => CheckValidateInput(ctx, VBSyntaxNodeHelper.Default), VB.SyntaxKind.ClassBlock);
 }
示例#48
0
 static void BuildSchema(Configuration config, IDbConnection connection)
 {
     new SchemaExport(config).Execute(true, true, false, connection, null);
 }
示例#49
0
        /// <inheritdoc/>
        protected override unsafe void OnApply(ImageFrame <TPixel> source, ImageFrame <TPixel> cloned, Rectangle sourceRectangle, Configuration configuration)
        {
            // Jump out, we'll deal with that later.
            if (source.Width == cloned.Width && source.Height == cloned.Height && sourceRectangle == this.ResizeRectangle)
            {
                // the cloned will be blank here copy all the pixel data over
                source.GetPixelSpan().CopyTo(cloned.GetPixelSpan());
                return;
            }

            int width   = this.Width;
            int height  = this.Height;
            int sourceX = sourceRectangle.X;
            int sourceY = sourceRectangle.Y;
            int startY  = this.ResizeRectangle.Y;
            int endY    = this.ResizeRectangle.Bottom;
            int startX  = this.ResizeRectangle.X;
            int endX    = this.ResizeRectangle.Right;

            int minX = Math.Max(0, startX);
            int maxX = Math.Min(width, endX);
            int minY = Math.Max(0, startY);
            int maxY = Math.Min(height, endY);

            if (this.Sampler is NearestNeighborResampler)
            {
                // Scaling factors
                float widthFactor  = sourceRectangle.Width / (float)this.ResizeRectangle.Width;
                float heightFactor = sourceRectangle.Height / (float)this.ResizeRectangle.Height;

                Parallel.For(
                    minY,
                    maxY,
                    configuration.ParallelOptions,
                    y =>
                {
                    // Y coordinates of source points
                    Span <TPixel> sourceRow = source.GetPixelRowSpan((int)(((y - startY) * heightFactor) + sourceY));
                    Span <TPixel> targetRow = cloned.GetPixelRowSpan(y);

                    for (int x = minX; x < maxX; x++)
                    {
                        // X coordinates of source points
                        targetRow[x] = sourceRow[(int)(((x - startX) * widthFactor) + sourceX)];
                    }
                });

                return;
            }

            // Interpolate the image using the calculated weights.
            // A 2-pass 1D algorithm appears to be faster than splitting a 1-pass 2D algorithm
            // First process the columns. Since we are not using multiple threads startY and endY
            // are the upper and lower bounds of the source rectangle.
            // TODO: Using a transposed variant of 'firstPassPixels' could eliminate the need for the WeightsWindow.ComputeWeightedColumnSum() method, and improve speed!
            using (var firstPassPixels = new Buffer2D <Vector4>(width, source.Height))
            {
                firstPassPixels.Clear();

                Parallel.For(
                    0,
                    sourceRectangle.Bottom,
                    configuration.ParallelOptions,
                    y =>
                {
                    // TODO: Without Parallel.For() this buffer object could be reused:
                    using (var tempRowBuffer = new Buffer <Vector4>(source.Width))
                    {
                        Span <Vector4> firstPassRow = firstPassPixels.GetRowSpan(y);
                        Span <TPixel> sourceRow     = source.GetPixelRowSpan(y);
                        PixelOperations <TPixel> .Instance.ToVector4(sourceRow, tempRowBuffer, sourceRow.Length);

                        if (this.Compand)
                        {
                            for (int x = minX; x < maxX; x++)
                            {
                                WeightsWindow window = this.HorizontalWeights.Weights[x - startX];
                                firstPassRow[x]      = window.ComputeExpandedWeightedRowSum(tempRowBuffer, sourceX);
                            }
                        }
                        else
                        {
                            for (int x = minX; x < maxX; x++)
                            {
                                WeightsWindow window = this.HorizontalWeights.Weights[x - startX];
                                firstPassRow[x]      = window.ComputeWeightedRowSum(tempRowBuffer, sourceX);
                            }
                        }
                    }
                });

                // Now process the rows.
                Parallel.For(
                    minY,
                    maxY,
                    configuration.ParallelOptions,
                    y =>
                {
                    // Ensure offsets are normalised for cropping and padding.
                    WeightsWindow window    = this.VerticalWeights.Weights[y - startY];
                    Span <TPixel> targetRow = cloned.GetPixelRowSpan(y);

                    if (this.Compand)
                    {
                        for (int x = 0; x < width; x++)
                        {
                            // Destination color components
                            Vector4 destination = window.ComputeWeightedColumnSum(firstPassPixels, x, sourceY);
                            destination         = destination.Compress();

                            ref TPixel pixel = ref targetRow[x];
                            pixel.PackFromVector4(destination);
                        }
                    }
                    else
                    {
                        for (int x = 0; x < width; x++)
                        {
                            // Destination color components
                            Vector4 destination = window.ComputeWeightedColumnSum(firstPassPixels, x, sourceY);

                            ref TPixel pixel = ref targetRow[x];
                            pixel.PackFromVector4(destination);
                        }
                    }
                });
示例#50
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="context">AnalysisContext</param>
 /// <param name="configuration">Configuration</param>
 /// <param name="logger">ILogger</param>
 /// <param name="errorReporter">ErrorReporter</param>
 protected OwnershipAnalysisPass(AnalysisContext context, Configuration configuration,
                                 ILogger logger, ErrorReporter errorReporter)
     : base(context, configuration, logger, errorReporter)
 {
 }
示例#51
0
 public override void Configure(Configuration configuration)
 {
     configuration.AddEventType("Bean", typeof(SupportBean_ST0_Container));
     configuration.AddEventType("SupportCollection", typeof(SupportCollection));
 }
 private void OnCompilationStartAction(CompilationStartAnalysisContext context, Configuration config)
 {
     context.RegisterSyntaxNodeAction(ctx => CheckAllowHtml(ctx, CSharpSyntaxNodeHelper.Default), CSharp.SyntaxKind.PropertyDeclaration);
     context.RegisterSyntaxNodeAction(ctx => CheckUnvalidated(ctx, CSharpSyntaxNodeHelper.Default), CSharp.SyntaxKind.SimpleMemberAccessExpression);
     context.RegisterSyntaxNodeAction(ctx => CheckValidateInput(ctx, CSharpSyntaxNodeHelper.Default), CSharp.SyntaxKind.MethodDeclaration);
     context.RegisterSyntaxNodeAction(ctx => CheckValidateInput(ctx, CSharpSyntaxNodeHelper.Default), CSharp.SyntaxKind.ClassDeclaration);
 }
 public PlatformImageLoaderTask(ITarget <WriteableBitmap, TImageView> target, TaskParameter parameters, IImageService imageService, Configuration configuration, IMainThreadDispatcher mainThreadDispatcher)
     : base(ImageCache.Instance, configuration.DataResolverFactory ?? DataResolvers.DataResolverFactory.Instance, target, parameters, imageService, configuration, mainThreadDispatcher, false)
 {
 }
示例#54
0
 public ScanJobApi(Configuration configuration) : base(configuration)
 {
 }
示例#55
0
        /// <summary>
        /// Handles the DoWorker event for the worker
        /// </summary>
        /// <param name="sender">Object that fired the event</param>
        /// <param name="e">.NET supplied event parameters</param>
        private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            lock (syncLock)
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                this.Dispatcher.BeginInvoke(new SimpleCallback(SetGadgetToProcessingState));
                this.Dispatcher.BeginInvoke(new SimpleCallback(ClearResults));

                AddLineListGridDelegate addGrid = new AddLineListGridDelegate(AddLineListGrid);

                Configuration config   = DashboardHelper.Config;
                string        yesValue = config.Settings.RepresentationOfYes;
                string        noValue  = config.Settings.RepresentationOfNo;

                try
                {
                    DataTable dictionaryTable = DashboardHelper.FieldTable.Copy();

                    foreach (KeyValuePair <string, string> kvp in DashboardHelper.TableColumnNames)
                    {
                        DataRow row = dictionaryTable.Rows.Find(kvp.Key);
                        if (row == null)
                        {
                            dictionaryTable.Rows.Add(kvp.Key, kvp.Value);
                        }
                    }

                    if (DashboardHelper.IsUsingEpiProject)
                    {
                        dictionaryTable.Columns.Add("Page", typeof(int));
                        dictionaryTable.Columns.Add("Tab", typeof(int));
                        dictionaryTable.Columns.Add("Prompt", typeof(string));
                        dictionaryTable.Columns.Add("Items", typeof(string));
                        dictionaryTable.Columns.Add("FieldType", typeof(string));

                        foreach (DataRow fieldRow in dictionaryTable.Rows)
                        {
                            if (fieldRow["epifieldtype"] is RenderableField)
                            {
                                RenderableField renderableField = fieldRow["epifieldtype"] as RenderableField;
                                fieldRow["Page"]      = renderableField.Page.Position + 1;
                                fieldRow["Tab"]       = renderableField.TabIndex;
                                fieldRow["Prompt"]    = renderableField.PromptText;
                                fieldRow["FieldType"] = fieldRow["epifieldtype"].ToString().Replace("Epi.Fields.", String.Empty);
                                if (renderableField is GroupField)
                                {
                                    GroupField groupField = renderableField as GroupField;
                                    fieldRow["Items"] = groupField.ChildFieldNames;
                                }
                                else if (renderableField is OptionField)
                                {
                                    OptionField optionField = renderableField as OptionField;
                                    fieldRow["Items"] = optionField.GetOptionsString();
                                }
                            }
                            fieldRow["datatype"] = fieldRow["datatype"].ToString().Replace("System.", String.Empty);
                        }

                        dictionaryTable.Columns["columnname"].SetOrdinal(0);
                        dictionaryTable.Columns["Prompt"].SetOrdinal(1);
                        dictionaryTable.Columns["formname"].SetOrdinal(2);
                        dictionaryTable.Columns["Page"].SetOrdinal(3);
                        dictionaryTable.Columns["Tab"].SetOrdinal(4);
                        dictionaryTable.Columns["datatype"].SetOrdinal(5);
                        dictionaryTable.Columns["FieldType"].SetOrdinal(6);
                        dictionaryTable.Columns["tablename"].SetOrdinal(7);
                        dictionaryTable.Columns["Items"].SetOrdinal(8);
                    }

                    if (dictionaryTable == null || dictionaryTable.Rows.Count == 0)
                    {
                        this.Dispatcher.BeginInvoke(new RenderFinishWithErrorDelegate(RenderFinishWithError), "There are no valid fields to display.");
                    }
                    else if (worker.CancellationPending)
                    {
                        this.Dispatcher.BeginInvoke(new RenderFinishWithErrorDelegate(RenderFinishWithError), SharedStrings.DASHBOARD_GADGET_STATUS_OPERATION_CANCELLED);
                        this.Dispatcher.BeginInvoke(new SimpleCallback(SetGadgetToFinishedState));
                        Debug.Print("Data dictionary thread cancelled");
                        return;
                    }
                    else
                    {
                        this.Dispatcher.BeginInvoke(addGrid, dictionaryTable.AsDataView());
                        string formatString = string.Empty;
                    }

                    this.Dispatcher.BeginInvoke(new SimpleCallback(RenderFinish));
                    this.Dispatcher.BeginInvoke(new SimpleCallback(SetGadgetToFinishedState));
                }
                catch (Exception ex)
                {
                    this.Dispatcher.BeginInvoke(new RenderFinishWithErrorDelegate(RenderFinishWithError), ex.Message);
                    this.Dispatcher.BeginInvoke(new SimpleCallback(SetGadgetToFinishedState));
                }
                finally
                {
                    stopwatch.Stop();
                    Debug.Print("Data dictionary gadget took " + stopwatch.Elapsed.ToString() + " seconds to complete with " + DashboardHelper.RecordCount.ToString() + " records and the following filters:");
                    Debug.Print(DashboardHelper.DataFilters.GenerateDataFilterString());
                }
            }
        }
示例#56
0
 public SettingsVRMenu(QMNestedButton parent, MClientVRButton config) : base(parent, config.X, config.Y, config.Name, config.Tooltip, GeneralUtils.GetColor(config.ColorScheme.Colors[0]), GeneralUtils.GetColor(config.ColorScheme.Colors[1]), GeneralUtils.GetColor(config.ColorScheme.Colors[2]), GeneralUtils.GetColor(config.ColorScheme.Colors[3]))
 {
     new QMToggleButton(this, 1, 0, "Enable\nMenu RGB", delegate
     {
         Configuration.GetConfig().MenuRGB = true;
         Configuration.SaveConfiguration();
     }, "Disable\nMenu RGB", delegate
     {
         Configuration.GetConfig().MenuRGB = false;
         Configuration.SaveConfiguration();
     }, "Toggle whether you want your UI to change colors consistently (Rainbow UI mode basically)", Color.red, Color.white).setToggleState(Configuration.GetConfig().MenuRGB);
     new QMToggleButton(this, 2, 0, "Clear\nConsole", delegate
     {
         Configuration.GetConfig().CleanConsole = true;
         Configuration.SaveConfiguration();
     }, "Don't Clear\nConsole", delegate
     {
         Configuration.GetConfig().CleanConsole = false;
         Configuration.SaveConfiguration();
     }, "Decide whether you want your console to be spammed by useless game information or not.", Color.red, Color.white).setToggleState(Configuration.GetConfig().CleanConsole);
     new QMToggleButton(this, 3, 0, "Log\nTo Console", delegate
     {
         Configuration.GetConfig().DefaultLogToConsole = true;
     }, "Log\nTo HUD", delegate
     {
         Configuration.GetConfig().DefaultLogToConsole = false;
     }, "Decide whether you want to log all moderation/other client information to your console or your hud ingame.", Color.red, Color.white).setToggleState(Configuration.GetConfig().DefaultLogToConsole);
     new QMToggleButton(this, 4, 0, "Enable\nDiscord RPC", delegate
     {
         Configuration.GetConfig().UseRichPresence = true;
     }, "Disable\nDiscord RPC", delegate
     {
         Configuration.GetConfig().UseRichPresence = false;
     }, "Enable/Disable the discord rich presence.", Color.red, Color.white).setToggleState(Configuration.GetConfig().UseRichPresence);
 }
示例#57
0
        protected void Reload()
        {
            Encryption.RNG.Reload();
            // some logic in configuration updated the config when saving, we need to read it again
            _config = Configuration.Load();
            StatisticsConfiguration = StatisticsStrategyConfiguration.Load();

            if (_pacServer == null)
            {
                _pacServer = new PACServer();
                _pacServer.PACFileChanged      += pacServer_PACFileChanged;
                _pacServer.UserRuleFileChanged += pacServer_UserRuleFileChanged;
            }
            _pacServer.UpdateConfiguration(_config);
            if (gfwListUpdater == null)
            {
                gfwListUpdater = new GFWListUpdater();
                gfwListUpdater.UpdateCompleted += pacServer_PACUpdateCompleted;
                gfwListUpdater.Error           += pacServer_PACUpdateError;
            }

            availabilityStatistics.UpdateConfiguration(this);

            if (_listener != null)
            {
                _listener.Stop();
            }

            try
            {
                var strategy = GetCurrentStrategy();
                if (strategy != null)
                {
                    strategy.ReloadServers();
                }

                TCPRelay tcpRelay = new TCPRelay(this, _config);
                UDPRelay udpRelay = new UDPRelay(this);
                List <Listener.IService> services = new List <Listener.IService>();
                services.Add(_pacServer);
                services.Add(tcpRelay);
                services.Add(udpRelay);
                _listener = new Listener(services);
                _listener.Start(_config);
            }
            catch (Exception e)
            {
                // translate Microsoft language into human language
                // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use
                if (e is SocketException)
                {
                    SocketException se = (SocketException)e;
                    if (se.SocketErrorCode == SocketError.AccessDenied)
                    {
                        e = new Exception(I18N.GetString("Port already in use"), e);
                    }
                }
                Logging.LogUsefulException(e);
                ReportError(e);
            }

            if (ConfigChanged != null)
            {
                ConfigChanged(this, new EventArgs());
            }

            UpdateSystemProxy();
            Utils.ReleaseMemory(true);
        }
示例#58
0
 public static Org.Apache.Hadoop.Hdfs.ClientContext GetFromConf(Configuration conf
                                                                )
 {
     return(Get(conf.Get(DFSConfigKeys.DfsClientContext, DFSConfigKeys.DfsClientContextDefault
                         ), new DFSClient.Conf(conf)));
 }
示例#59
0
 public void SaveServers(List <Server> servers, int localPort)
 {
     _config.configs   = servers;
     _config.localPort = localPort;
     Configuration.Save(_config);
 }
示例#60
0
 protected void SaveConfig(Configuration newConfig)
 {
     Configuration.Save(newConfig);
     Reload();
 }