/// <summary> /// Initializes a new instance of the <see cref="ShardService"/> class. /// </summary> /// <param name="nodeRepository">Concrete Node repository</param> /// <param name="hashingFunction">Concrete Hashsing function</param> /// <param name="vNodes">Number of virtual nodes - default = 10</param> public ShardService(INodeRepository nodeRepository, IHashing hashingFunction, int vNodes = 10) { this.nodeRepository = nodeRepository; var nodes = nodeRepository.GetAllNode(); if (nodes == null || nodes.Count == 0) throw new Exception("No available node, check your connection string or database"); ClusterManager = new ClusterManager(nodes, hashingFunction, vNodes); }
// Use this for initialization void Start () { for (int i = 0; i < 11; i++) { GameObject c = Instantiate(clusterCircle); c.SetActive(false); clusterCircles[i] = c; } cm = ClusterManager.Instance; }
public void SetupMapClustingDemo() { if (_googleMap == null || _currentLocation == null) // Do we have a map and location avaialble? { return; } _clusterManager = new ClusterManager(this, _googleMap); _clusterManager.SetOnClusterClickListener(this); _clusterManager.SetOnClusterItemClickListener(this); _googleMap.SetOnCameraChangeListener(_clusterManager); _googleMap.SetOnMarkerClickListener(_clusterManager); SetViewPoint(_googleMap, new LatLng(_currentLocation.Latitude, _currentLocation.Longitude), true); AddClusterItems(_currentLocation); }
protected override void StartMap() { googleMap.MoveCamera(CameraUpdateFactory.NewLatLngZoom(new LatLng(51.503186, -0.126446), 10)); clusterManager = new ClusterManager(this, googleMap); googleMap.SetOnCameraIdleListener(clusterManager); try { ReadJson(); } catch (Exception) { Toast.MakeText(this, "Problem reading list of markers.", ToastLength.Long).Show(); } }
public void UpsertUser_Returns_True_When_Response_Is_Success(HttpStatusCode responseHttpCode) { var handler = FakeHttpMessageHandler.Create(request => new HttpResponseMessage(responseHttpCode)); var client = new HttpClient(handler); var clientConfig = new ClientConfiguration(); var serverConfigMock = new Mock <IServerConfig>(); var dataMapper = new JsonDataMapper(clientConfig); var manager = new ClusterManager(clientConfig, serverConfigMock.Object, dataMapper, client, "username", "password"); var result = manager.UpsertUser("alice", "secure123", "Alice Liddell", new Role { Name = "Admin" }); Assert.AreEqual(responseHttpCode == HttpStatusCode.OK, result.Success); }
// Start is called before the first frame update void Start() { // get _cMamnager = transform.parent.gameObject.GetComponent <ClusterManager>(); // minor _thisRender = this.GetComponent <SpriteRenderer>(); _color = _thisRender.color; _opacity = _color.a; transform = this.GetComponent <Transform>(); initialPosition = transform.localPosition; shakeDuration = 0; }
static int Remove(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); ClusterManager obj = (ClusterManager)ToLua.CheckObject(L, 1, typeof(ClusterManager)); PositionObject arg0 = (PositionObject)ToLua.CheckUnityObject(L, 2, typeof(PositionObject)); obj.Remove(arg0); return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static int IsEnd(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); ClusterManager obj = (ClusterManager)ToLua.CheckObject(L, 1, typeof(ClusterManager)); bool o = obj.IsEnd(); LuaDLL.lua_pushboolean(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
public DefaultClusterRenderer(Context context, GoogleMap map, ClusterManager <T> clusterManager) { if (!InstanceFieldsInitialized) { InitializeInstanceFields(); InstanceFieldsInitialized = true; } mMap = map; mDensity = context.Resources.DisplayMetrics.Density; mIconGenerator = new IconGenerator(context); mIconGenerator.SetContentView(makeSquareTextView(context)); //ContentView = makeSquareTextView(context); mIconGenerator.SetTextAppearance(Resource.Styleable.ClusterIcon.TextAppearance); //TextAppearance = R.style.ClusterIcon_TextAppearance; mIconGenerator.SetBackground(makeClusterBackground()); // Background = makeClusterBackground(); mClusterManager = clusterManager; }
internal override void Register(GoogleMap oldNativeMap, Map oldMap, GoogleMap newNativeMap, Map newMap) { //---------------------------------------- // Base registration //---------------------------------------- base.Register(oldNativeMap, oldMap, newNativeMap, newMap); //---------------------------------------- // Instanciate a new cluster manager //---------------------------------------- /* Initialize the manager */ this._clusterManager = new ClusterManager(Xamarin.Forms.Forms.Context, this.NativeMap); this._clusterHandler = new ClusterLogicHandler(this.Map, this._clusterManager, this); /* Choose the right algorithm */ switch (this.Map.ClusterOptions.Algorithm) { case ClusterAlgorithm.GridBased: this._clusterManager.SetAlgorithm(new GridBasedAlgorithm()); break; case ClusterAlgorithm.NonHierarchicalDistanceBased: default: this._clusterManager.SetAlgorithm(new NonHierarchicalDistanceBasedAlgorithm()); break; } //---------------------------------------- // Register //---------------------------------------- if (newNativeMap != null) { /* Handle the cluster request by forwarding it to clusterManager.Cluster() */ this.Map.OnCluster = HandleClusterRequest; this.NativeMap.SetOnCameraChangeListener(this._clusterManager); this.NativeMap.SetOnMarkerClickListener(this._clusterManager); //this.NativeMap.SetOnInfoWindowClickListener(this._clusterManager); this._clusterManager.SetRenderer(new XamarinClusterRenderer(Xamarin.Forms.Forms.Context, this.Map, this.NativeMap, this._clusterManager)); this._clusterManager.SetOnClusterClickListener(this._clusterHandler); this._clusterManager.SetOnClusterInfoWindowClickListener(this._clusterHandler); this._clusterManager.SetOnClusterItemClickListener(this._clusterHandler); this._clusterManager.SetOnClusterItemInfoWindowClickListener(this._clusterHandler); } }
public override async Task <string> ProceedRequestAsync(string query, TimeSpan timeout) { var mappingTaskToUriGuidTuple = new ConcurrentDictionary <Task <string>, (string, Guid)>( ClusterManager.EnumerateWhiteReplica().Select(uri => { var guid = Guid.NewGuid(); var task = Task.Run(async() => { var requestTask = WebRequestTask(uri, query, guid); await Task.WhenAny(requestTask, Task.Delay(timeout)); if (requestTask.IsCompleted && !requestTask.IsFaulted) { return(requestTask.Result); } ClusterManager.MarkGrey(uri, query, TimeSpan.FromMilliseconds(500)); throw new TimeoutException(); }); return(new KeyValuePair <Task <string>, (string, Guid)>(task, (uri, guid))); })); var parallelTasks = new HashSet <Task <string> >(mappingTaskToUriGuidTuple.Keys); while (parallelTasks.Any()) { var completedTask = await Task.WhenAny(parallelTasks); if (completedTask.IsFaulted) { parallelTasks.Remove(completedTask); Log.Info($"Task [{query}] faulted with [{completedTask.Exception?.GetBaseException().Message}]."); } else { foreach (var task in parallelTasks.Where(t => !t.IsCompleted)) { var(uri, guid) = mappingTaskToUriGuidTuple[task]; ProceedCancelRequest(uri, guid); } return(completedTask.Result); } } throw new TimeoutException(); }
public void Dispose() { if (server != null) { server.Dispose(); server = null; } if (config != null) { config.Dispose(); config = null; } ClusterManager.Shutdown(clusterName); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private void reelectTheSameMasterMakingItGoToPendingAndBack(org.neo4j.kernel.impl.ha.ClusterManager.ManagedCluster cluster) throws Throwable private void ReelectTheSameMasterMakingItGoToPendingAndBack(ClusterManager.ManagedCluster cluster) { HighlyAvailableGraphDatabase master = cluster.Master; // Fail master and wait for master to go to pending, since it detects it's partitioned away ClusterManager.RepairKit masterRepair = cluster.Fail(master, false, ClusterManager.NetworkFlag.IN, ClusterManager.NetworkFlag.OUT); cluster.Await(memberThinksItIsRole(master, UNKNOWN)); // Then Immediately repair masterRepair.Repair(); // Wait for this instance to go to master again, since the other instances are slave only cluster.Await(memberThinksItIsRole(master, MASTER)); cluster.Await(ClusterManager.masterAvailable()); assertEquals(master, cluster.Master); }
public HttpResponseMessage RemoveClustering() { if (ClusterManager.Engine.CurrentTopology.AllNodes.Count() > 1) { return(GetMessageWithString("Remove clustering is available on single node clusters only.", HttpStatusCode.BadRequest)); } // delete Raft persistent storage and init new one ClusterManager.CleanupAllClusteringData(SystemDatabase); var newClusterManager = ClusterManagerFactory.Create(SystemDatabase, DatabasesLandlord); ((Reference <ClusterManager>)Configuration.Properties[typeof(ClusterManager)]).Value = newClusterManager; return(GetEmptyMessage(HttpStatusCode.NoContent)); }
static int GetPositionObjectListByGraphics(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); ClusterManager obj = (ClusterManager)ToLua.CheckObject(L, 1, typeof(ClusterManager)); ICollisionGraphics arg0 = (ICollisionGraphics)ToLua.CheckObject(L, 2, typeof(ICollisionGraphics)); System.Collections.Generic.IList <PositionObject> o = obj.GetPositionObjectListByGraphics(arg0); ToLua.PushObject(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
protected override void StartMap() { googleMap.MoveCamera(CameraUpdateFactory.NewLatLngZoom(new LatLng(51.503186, -0.126446), 9.5f)); clusterManager = new ClusterManager(this, googleMap); clusterManager.Renderer = new PersonRenderer(this, googleMap, clusterManager); googleMap.SetOnCameraIdleListener(clusterManager); googleMap.SetOnMarkerClickListener(clusterManager); googleMap.SetOnInfoWindowClickListener(clusterManager); clusterManager.SetOnClusterClickListener(this); clusterManager.SetOnClusterItemClickListener(this); clusterManager.SetOnClusterInfoWindowClickListener(this); clusterManager.SetOnClusterItemInfoWindowClickListener(this); AddItems(); clusterManager.Cluster(); }
private void addClusterItems(ClusterManager clusterManager) { Stream inputStream = Resources.OpenRawResource(Resource.Raw.radar_search); List <MyItem> items; try { items = new MyItemReader().read(inputStream); clusterManager.AddItems(items); } catch (JSONException e) { Toast.MakeText(this, "Problem reading list of markers.", ToastLength.Long).Show(); e.PrintStackTrace(); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void slaveMustConnectLockManagerToNewMasterAfterTwoOtherClusterMembersRoleSwitch() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void SlaveMustConnectLockManagerToNewMasterAfterTwoOtherClusterMembersRoleSwitch() { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.kernel.ha.HighlyAvailableGraphDatabase initialMaster = cluster.getMaster(); HighlyAvailableGraphDatabase initialMaster = _cluster.Master; HighlyAvailableGraphDatabase firstSlave = _cluster.AnySlave; HighlyAvailableGraphDatabase secondSlave = _cluster.getAnySlave(firstSlave); // Run a transaction on the slaves, to make sure that a master connection has been initialised in all // internal pools. using (Transaction tx = firstSlave.BeginTx()) { firstSlave.CreateNode(); tx.Success(); } using (Transaction tx = secondSlave.BeginTx()) { secondSlave.CreateNode(); tx.Success(); } _cluster.sync(); ClusterManager.RepairKit failedMaster = _cluster.fail(initialMaster); _cluster.await(ClusterManager.masterAvailable(initialMaster)); failedMaster.Repair(); _cluster.await(ClusterManager.masterAvailable(initialMaster)); _cluster.await(ClusterManager.allSeesAllAsAvailable()); // The cluster has now switched the master role to one of the slaves. // The slave that didn't switch, should still have done the work to reestablish the connection to the new // master. HighlyAvailableGraphDatabase slave = _cluster.getAnySlave(initialMaster); using (Transaction tx = slave.BeginTx()) { slave.CreateNode(); tx.Success(); } // We assert that the transaction above does not throw any exceptions, and that we have now created 3 nodes. HighlyAvailableGraphDatabase master = _cluster.Master; using (Transaction tx = master.BeginTx()) { assertThat(Iterables.count(master.AllNodes), @is(3L)); } }
public bool DeleteCluster(int clusterID) { using (var dataContext = MISD.Server.Database.DataContextFactory.CreateDataContext()) { try { var cl = (from ms in dataContext.ClusterCredential where ms.ID == clusterID select ms).FirstOrDefault(); if (cl != null) { ClusterManager clusterm = null; foreach (var current in MetaClusterManager.Instance.clusterManagers) { if (current.ID.Equals(cl.ID)) { clusterm = current; } } if (clusterm != null) { MISD.Server.Manager.MetaClusterManager.Instance.RemoveCluster(clusterm); } dataContext.ClusterCredential.DeleteOnSubmit(cl); dataContext.SubmitChanges(); return(true); } else { return(false); } } catch (Exception e) { //logging exception var messageEx = new StringBuilder(); messageEx.Append("ClientWebService_DeleteCluster: "); messageEx.Append("Can't delete Cluster" + clusterID + ". " + e.ToString()); MISD.Core.Logger.Instance.WriteEntry(messageEx.ToString(), LogType.Exception); return(false); } } }
public override async Task <string> ProceedRequestAsync(string query, TimeSpan timeout) { var whiteReplica = ClusterManager.EnumerateWhiteReplica().ToArray(); var uri = whiteReplica[randomGenerator.Next(whiteReplica.Length)]; var guid = Guid.NewGuid(); var requestTask = WebRequestTask(uri, query, guid); await Task.WhenAny(requestTask, Task.Delay(timeout)); if (requestTask.IsCompleted && !requestTask.IsFaulted) { return(requestTask.Result); } ClusterManager.MarkGrey(uri, query, TimeSpan.FromMilliseconds(500)); throw new TimeoutException(); }
static int get_CollisionWeight(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); ClusterManager obj = (ClusterManager)o; float ret = obj.CollisionWeight; LuaDLL.lua_pushnumber(L, ret); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index CollisionWeight on a nil value" : e.Message)); } }
void Awake() { clusterManager = GetComponent <ClusterManager>(); clusterManager.RegisterClusterCallback(OnUpdateClusters); physicsScenes = new List <PhysicsScene>(); scenes = new List <Scene>(); CreateSceneParameters csp = new CreateSceneParameters(LocalPhysicsMode.Physics3D); for (int i = 0; i < 5; i++) { Scene s = SceneManager.CreateScene("Physics Scene " + (i + 1), csp); scenes.Add(s); physicsScenes.Add(s.GetPhysicsScene()); } }
static int get_UnitWidth(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); ClusterManager obj = (ClusterManager)o; int ret = obj.UnitWidth; LuaDLL.lua_pushinteger(L, ret); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index UnitWidth on a nil value" : e.Message)); } }
static int set_CollisionWeight(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); ClusterManager obj = (ClusterManager)o; float arg0 = (float)LuaDLL.luaL_checknumber(L, 2); obj.CollisionWeight = arg0; return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index CollisionWeight on a nil value" : e.Message)); } }
static int set_UnitWidth(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); ClusterManager obj = (ClusterManager)o; int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); obj.UnitWidth = arg0; return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index UnitWidth on a nil value" : e.Message)); } }
public void Run() { Console.WriteLine("======================================================="); Console.WriteLine("== RUNNING {0}", _name); Console.WriteLine("======================================================="); try { XmlConfigurator.Configure(); using (ICluster cluster = ClusterManager.GetCluster("TestCassandra")) { try { DropKeyspace(cluster); } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { } CreateKeyspace(cluster); try { InternalRun(cluster); DropKeyspace(cluster); } catch (Exception ex) { string msg = string.Format("== FAILED with error\n{0}", ex); Console.WriteLine("======================================================="); Console.WriteLine(msg); Console.WriteLine("======================================================="); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); } } finally { ClusterManager.Shutdown(); } }
protected override void startDemo(bool isRestore) { if (!isRestore) { getMap().MoveCamera(CameraUpdateFactory.NewLatLngZoom(new LatLng(51.503186, -0.126446), 10)); } DisplayMetrics metrics = new DisplayMetrics(); WindowManager.DefaultDisplay.GetMetrics(metrics); //mViewModel.getAlgorithm().UpdateViewSize(metrics.WidthPixels, metrics.HeightPixels); mClusterManager = new ClusterManager(this, getMap()); mClusterManager.Algorithm = mViewModel.getAlgorithm(); getMap().SetOnCameraIdleListener(mClusterManager); }
void UpdateUsingClusters() { // force cluster manager to update now (ensures we have most up to date finger state) ClusterManager.Update(); foreach (FingerClusterManager.Cluster cluster in ClusterManager.Clusters) { ProcessCluster(cluster); } foreach (T g in gestures) { FingerClusterManager.Cluster cluster = ClusterManager.FindClusterById(g.ClusterId); FingerGestures.IFingerList touches = (cluster != null) ? cluster.Fingers : EmptyFingerList; UpdateGesture(g, touches); } }
/// <summary> /// Get job details for a specific job id from Job manager /// </summary> /// <param name="jobName">jobName</param> /// <returns></returns> public async Task<SparkJobConfig> SyncJobState(string jobName) { Ensure.NotNull(jobName, "jobName"); Logger.LogInformation($"sync'ing job '{jobName}'"); // Get the job config data from internal data and ensure job is in Idle state var job = await JobData.GetByName(jobName); Ensure.NotNull(job, "job"); var state = job.SyncResult; if (state == null) { state = new SparkJobSyncResult(); } if (state.ClientCache != null && state.ClientCache.Type != JTokenType.Null) { var sparkJobClient = await ClusterManager.GetSparkJobClient(job.Cluster); var newResult = await sparkJobClient.GetJobInfo(state.ClientCache); state = newResult; Logger.LogInformation($"got state for job '{jobName}'"); } else { state.JobState = JobState.Idle; Logger.LogInformation($"no client cache for job '{jobName}', set state to '{state.JobState}'"); } if (!state.Equals(job.SyncResult)) { var updateResult = await JobData.UpdateSyncResultByName(jobName, state); if (!updateResult.IsSuccess) { throw new GeneralException($"Failed to update job client cache for name '{jobName}': returned message '{updateResult.Message}'"); } job.SyncResult = state; Logger.LogInformation($"done sync'ing the state for job '{jobName}', state updated"); } else { Logger.LogInformation($"done sync'ing the state for job '{jobName}', no changes"); } return job; }
// https://www.codeproject.com/Articles/758803/DotNet-Programming-using-Cassandra public static ICluster GetCluster(int myPort, string[] myClusters) { CassandraSharpConfig config = new CassandraSharpConfig(); ClusterConfig clusterConfig = new ClusterConfig(); TransportConfig transConfig = new TransportConfig(); clusterConfig.Name = "Test Cluster"; transConfig.Port = myPort; clusterConfig.Transport = new TransportConfig(); EndpointsConfig endPointConfig = new EndpointsConfig(); endPointConfig.Servers = myClusters; // endPointConfig.Snitch = SnitchType.Simple; // endPointConfig.Strategy = EndpointStrategy.Nearest; //BehaviorConfig behaveConfig = new BehaviorConfig(); //behaveConfig.KeySpace = ConfigEntries.DefaultDatabase; //if (!String.IsNullOrWhiteSpace(ConfigEntries.UserName)) behaveConfig.User = ConfigEntries.UserName; //if (!String.IsNullOrWhiteSpace(ConfigEntries.Password)) behaveConfig.Password = ConfigEntries.Password; //behaveConfig.ReadConsistencyLevel = Apache.Cassandra.ConsistencyLevel.ONE; //behaveConfig.WriteConsistencyLevel = Apache.Cassandra.ConsistencyLevel.ONE; clusterConfig.Transport = transConfig; clusterConfig.Endpoints = endPointConfig; // KeyspaceConfig ksc = new KeyspaceConfig(); // ksc.Name = ""; // clusterConfig.DefaultKeyspace = ksc; config.Clusters = new ClusterConfig[] { clusterConfig }; //We need to ensure that the connection is not initialized before configuring... ClusterManager.Shutdown(); ClusterManager.Configure(config); ICluster cluster = ClusterManager.GetCluster("Test Cluster"); return(cluster); }
public LoginServer() { Console.WriteLine("Test if port 23000 is in use..."); if (PortChecker.IsPortAvailable(23000)) { Console.WriteLine("Port 23000 is already in use - You can only run one cluster on one computer"); return; } Config = new LoginServerConfig("Resources/Config/Login.ini"); int loginPort = (int)Config.GetSetting("LoginPort"); Console.WriteLine("Test if port {0} is in use...", loginPort.ToString()); if (PortChecker.IsPortAvailable(loginPort)) { Console.WriteLine("Port {0} is already in use - You can only run one login server on one computer", loginPort); return; } LoginDatabase = new LoginDatabase(Config); if (LoginDatabase.Connection.CheckConnection()) { Rijndael.Initiate(); this.m_ClusterConnector = new ClusterConnector(loginPort.ToString()); this.m_ClusterConnector.StartListening(); ClusterManager = new ClusterManager(); Console.WriteLine("Listening for cluster servers..."); this.m_ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this.m_ClientSocket.Bind(new IPEndPoint(IPAddress.Any, 23000)); this.m_ClientSocket.Listen(100); ClientManager = new ClientManager(); Thread acceptClientsThread = new Thread(() => ClientManager.AcceptUsers(this.m_ClientSocket)); acceptClientsThread.Start(); Thread processClientsThread = new Thread(() => ClientManager.ProcessUsers()); processClientsThread.Start(); Console.WriteLine("Listening for clients..."); } }
/// <summary> /// Initializes the application. /// </summary> public static void Initialize() { //Initialize configuration Config.Initialize(); //Initialize Counters CPU.GetUsage(); Memory.GetTotalSize(); DPI.CalculateDPI(); //Initialize subsystems ClusterManager.Initialize(); Loader.Initialize(); Executor.Initialize(); //Start the server listening thread ControlServer.Start(); ControlServer.RegisterDispatchAction(MessageType.STATUS_TERMINAL, status); //Initialize the Node Listing Nodes.Initialize(); }
public StationRenderer(Context context, GoogleMap map, ClusterManager clusterManager) : base(context, map, clusterManager) { _context = context; _map = map; _clusterManager = clusterManager; _contractService = SimpleIoc.Default.GetInstance<IContractService>(); _settingsService = SimpleIoc.Default.GetInstance<ISettingsService>(); _iconGenRed = new IconGenerator(_context); _iconGenGreen = new IconGenerator(_context); _iconGenOrange = new IconGenerator(_context); _iconGenGrey = new IconGenerator(_context); _iconGenGreyLowAlpha = new IconGenerator(_context); //// Define the size you want from dimensions file //var shapeDrawable = ResourcesCompat.GetDrawable(_context.Resources, Resource.Drawable.station, null); //iconGen.SetBackground(shapeDrawable); ////// Create a view container to set the size _iconGenRed.SetBackground(ResourcesCompat.GetDrawable(_context.Resources, Resource.Drawable.stationRed, null)); _iconGenOrange.SetBackground(ResourcesCompat.GetDrawable(_context.Resources, Resource.Drawable.stationOrange, null)); _iconGenGreen.SetBackground(ResourcesCompat.GetDrawable(_context.Resources, Resource.Drawable.stationGreen, null)); _iconGenGrey.SetBackground(ResourcesCompat.GetDrawable(_context.Resources, Resource.Drawable.stationGrey, null)); _iconGenGreyLowAlpha.SetBackground(ResourcesCompat.GetDrawable(_context.Resources, Resource.Drawable.stationGreyAlpha, null)); _iconRed = _iconGenRed.MakeIcon(); _iconGreen = _iconGenGreen.MakeIcon(); _iconOrange = _iconGenOrange.MakeIcon(); _iconGrey = _iconGenGrey.MakeIcon(); _iconGreyLowAlpha = _iconGenGreyLowAlpha.MakeIcon(); var textView = new TextView(context); textView.SetTextAppearance(_context, Resource.Style.iconGenText); _textPaint.AntiAlias = true; _textPaint.SetARGB(255, 0, 0, 0); _textPaint.TextSize = textView.TextSize; _textPaint.TextAlign = Paint.Align.Center; //_textPaint.SetTypeface(textView.Typeface); _textPaint.SetTypeface(Typeface.CreateFromAsset(_context.Assets, "fonts/Roboto-Bold.ttf")); }
public GetClusterBrokerStatusInfoListRequestHandler(NameServerController nameServerController) { _clusterManager = nameServerController.ClusterManager; _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>(); }
/// <seealso cref="IJobStore.SchedulerStarted()" /> public virtual void SchedulerStarted() { if (Clustered) { clusterManagementThread = new ClusterManager(this); clusterManagementThread.Initialize(); } else { try { RecoverJobs(); } catch (SchedulerException se) { throw new SchedulerConfigException("Failure occured during job recovery.", se); } } misfireHandler = new MisfireHandler(this); misfireHandler.Initialize(); schedulerRunning = true; }
public GetTopicAccumulateInfoListRequestHandler(NameServerController nameServerController) { _clusterManager = nameServerController.ClusterManager; _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>(); }
public GetAllClustersRequestHandler(NameServerController nameServerController) { _clusterManager = nameServerController.ClusterManager; _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>(); }
public async void OnMapReady(GoogleMap googleMap) { _gettingMap = false; // TODO TO HELP DEBUG auto download paris to help dev on performances //var contractToTest = "Paris"; //var contractService = SimpleIoc.Default.GetInstance<IContractService>(); //var contract = contractService.GetCountries().First(country => country.Contracts.Any(c => c.Name == contractToTest)).Contracts.First(c => c.Name == contractToTest); //await SimpleIoc.Default.GetInstance<ContractsViewModel>().AddOrRemoveContract(contract); _contractService = SimpleIoc.Default.GetInstance<IContractService>(); _contractService.ContractRefreshed += OnContractRefreshed; _contractService.StationRefreshed += OnStationRefreshed; // set the initial visual state of the bike/parking buttons SwitchModeStationParkingVisualState(); _map = googleMap; _maxZoom = _map.MaxZoomLevel; LoadPreviousTile(); //Setup and customize your Google Map _map.UiSettings.CompassEnabled = true; _map.UiSettings.MyLocationButtonEnabled = false; _map.UiSettings.MapToolbarEnabled = false; _map.MyLocationEnabled = true; // add padding to prevent action bar to hide the position button //var dp = (int)(48 * Resources.DisplayMetrics.Xdpi / Resources.DisplayMetrics.Density); //_map.SetPadding(0, dp, 0, 0); //_map.vie //View locationButton = suppormanagerObj.getView().findViewById(2); //var rlp = (RelativeLayout.LayoutParams)locationButton.getLayoutParams(); //// position on right bottom //rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0); rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE); // Initialize the camera position SetViewPoint(await GetStartingCameraPosition(), false); // Initialize the marker with the stations _clusterManager = new ClusterManager(this, _map); _clusterRender = new StationRenderer(this, _map, _clusterManager); _clusterManager.SetRenderer(_clusterRender); _map.SetOnCameraChangeListener(_clusterManager); // this disable the rest of the event handlers // so there is no way to distinct a click on a cluster and a marker _map.MarkerClick += _map_MarkerClick; //_map.SetOnMarkerClickListener(new OnMarkerClickListener()); //_clusterManager.SetOnClusterClickListener(this); //_clusterManager.SetOnClusterItemClickListener(this); // check if the app contains a least one city, otherwise, tells the user to download one MainViewModel.MainPageLoadedCommand.Execute(null); // On long click, display the address on a info window Observable.FromEventPattern<GoogleMap.MapLongClickEventArgs>(_map, "MapLongClick") .Subscribe(e => { AddPlaceMarker(e.EventArgs.Point, null, null); SelectItem(e.EventArgs.Point); //IList<Address> addresses = new List<Address>(); //try //{ // // Convert latitude and longitude to an address (GeoCoder) // addresses = await (new Geocoder(this).GetFromLocationAsync(currentMarkerPosition.Latitude, currentMarkerPosition.Longitude, 1)); //} //catch (Exception ex) //{ // Log.Debug("MyActivity", "Geocoder crashed: " + ex.Message); //} //return new AddressesFromLocationDTO { Addresses = addresses, Location = FormatLatLng(e.EventArgs.Point) }; }); _map.MapClick += _map_MapClick; if (_parameterLat != 0 && _parameterLon != 0) { ShowIntentLocation(); } else { // center the map on last user location GetPreviousLastUserLocation(); } // Initialize the behavior when long clicking somewhere on the map //_map.MapLongClick += async (sender, e) => //{ // // On long click, display the address on a info window // if (longClickMarker != null) // { // // Remove a previously created marker // longClickMarker.Remove(); // } // IList<Address> addresses = new List<Address>(); // currentMarkerPosition = e.Point; // var latLongString = $"(latitude: { Math.Round(currentMarkerPosition.Latitude)}, longitude: { Math.Round(currentMarkerPosition.Longitude, 4)})"; // try // { // // Resolve the addresses (can throw an exception) // var task = new Geocoder(this).GetFromLocationAsync(currentMarkerPosition.Latitude, currentMarkerPosition.Longitude, 1); // AddressesFromLocationStream.OnNext(new AddressesFromLocationDTO { AddressesTask = task, Location = currentMarkerPosition }); // } // catch (Exception) // { // // Ignore // } // finally // { // AddressesFromLocationStream.OnNext(new AddressesFromLocationDTO { Addresses = addresses, Location = currentMarkerPosition }); // } //}; _contractService = SimpleIoc.Default.GetInstance<IContractService>(); var mapObserver = Observable.FromEventPattern(_map, "CameraChange"); TaskCompletionSource<bool> tcs; mapObserver .Do((e) => { if (_map.CameraPosition.Zoom > _maxZoom) { _map.MoveCamera(CameraUpdateFactory.ZoomTo(_maxZoom)); } cts.Cancel(); cts = new CancellationTokenSource(); }).Throttle(throttleTime) .Select(async x => { var stations = _contractService.GetStations(); // some services can provide wrong values in lat or lon... just take care of it foreach (var station in stations.Where(s => s.Location == null)) { station.Location = new LatLng(station.Latitude, station.Longitude); } LatLngBounds bounds = null; tcs = new TaskCompletionSource<bool>(); RunOnUiThread(() => { try { // can return null bounds = _map.Projection.VisibleRegion.LatLngBounds; } catch { } tcs.SetResult(true); }); await tcs.Task; var collection = new AddRemoveCollection(); if (bounds != null) { // extends slightly the bound view // to provide a better experience //bounds = MapHelper.extendLimits(bounds, 1); collection.ToRemove = Items.Where(t => !bounds.Contains((LatLng)t.Location)).ToList(); collection.ToAdd = stations.Where(t => !Items.Contains(t) && bounds.Contains((LatLng)t.Location)).Take(MAX_CONTROLS).ToList(); if (Items.Count > MAX_CONTROLS + collection.ToRemove.Count) collection.ToAdd.Clear(); } // precalculate the items offset (that deffer well calculation) //foreach (var velib in collection.ToAdd) //{ // velib.GetOffsetLocation2(leftCornerLocation, zoomLevel); //} return collection; }) .Switch() .Subscribe(x => { if (x == null) return; RunOnUiThread(() => { RefreshView(x, cts.Token); }); }); }
private void SetupMapIfNeeded() { if (_map == null) { _map = _mapFragment.Map; if (_map != null) { SetViewPoint (new LatLng(63.430515, 10.395053), false); _clusterManager = new ClusterManager (this, _map); _clusterManager.SetOnClusterClickListener (this); _clusterManager.SetOnClusterItemClickListener (this); _map.SetOnCameraChangeListener (_clusterManager); _map.SetOnMarkerClickListener (_clusterManager); AddClusterItems (); } } }