//[TestCase(false)] public void CreateDataWithBackupServer(bool useServerSession) { int loops = 30000; UInt16 objectsPerPage = 300; UInt16 pagesPerDatabase = 65000; int j; if (Directory.Exists(backupDir)) Directory.Delete(backupDir, true); // remove systemDir from prior runs and all its databases. Directory.CreateDirectory(backupDir); using (SessionBase session = useServerSession ? (SessionBase)new ServerClientSession(systemDir) : (SessionBase)new SessionNoServer(systemDir)) { Placement place = new Placement(11, 1, 1, objectsPerPage, pagesPerDatabase); Man aMan = null; Woman aWoman = null; const bool isBackupLocation = true; session.BeginUpdate(); // we need to have backup locations special since server is not supposed to do encryption or compression DatabaseLocation backupLocation = new DatabaseLocation(Dns.GetHostName(), backupDir, backupLocationStartDbNum, UInt32.MaxValue, session, PageInfo.compressionKind.None, PageInfo.encryptionKind.noEncryption, isBackupLocation, session.DatabaseLocations.Default()); session.NewLocation(backupLocation); for (j = 1; j <= loops; j++) { aMan = new Man(null, aMan, DateTime.Now); aMan.Persist(place, session); aWoman = new Woman(aMan, aWoman); aWoman.Persist(place, session); aMan.m_spouse = new WeakIOptimizedPersistableReference<VelocityDbSchema.Person>(aWoman); if (j % 1000000 == 0) Console.WriteLine("Loop # " + j); } UInt64 id = aWoman.Id; Console.WriteLine("Commit, done Loop # " + j); session.Commit(); } }
public void hashCodeComparerStringTest() { Oid id; using (SessionNoServer session = new SessionNoServer(systemDir)) { Placement place = new Placement(223, 1, 1, UInt16.MaxValue, UInt16.MaxValue); session.Compact(); session.BeginUpdate(); HashCodeComparer<string> hashCodeComparer = new HashCodeComparer<string>(); BTreeSet<string> bTree = new BTreeSet<string>(hashCodeComparer, session); bTree.Persist(place, session); id = bTree.Oid; for (int i = 0; i < 100000; i++) { bTree.Add(i.ToString()); } session.Commit(); } using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginRead(); BTreeSet<string> bTree= (BTreeSet<string>)session.Open(id); int count = 0; foreach (string str in bTree) { count++; } Assert.True(100000 == count); session.Commit(); } }
public void schemaUpdateMultipleSessions() { using (ServerClientSession session = new ServerClientSession(systemDir)) { session.BeginUpdate(); Placement place = new Placement(555, 1, 1, 10, 10); Simple1 s1 = new Simple1(1); s1.Persist(place, session); s1 = null; using (ServerClientSession session2 = new ServerClientSession(systemDir)) { Placement place2 = new Placement(556, 1, 1, 10, 10); session2.BeginUpdate(); Simple2 s2 = new Simple2(2); s2.Persist(place2, session2); s2 = null; session.Commit(); session2.Commit(); // optemistic locking will fail due to session2 working with a stale schema (not the one updated by session 1) session.BeginUpdate(); s1 = (Simple1)session.Open(555, 1, 1, false); s2 = (Simple2)session.Open(556, 1, 1, false); session.Commit(); session2.BeginUpdate(); s1 = (Simple1)session2.Open(555, 1, 1, false); s2 = (Simple2)session2.Open(556, 1, 1, false); session2.Commit(); } } }
public void TestCreatePlacements() { TestUtils utils = new TestUtils(); Placement placement1 = new Placement(); placement1.name = string.Format("Medium Square AdUnit Placement #{0}", utils.GetTimeStamp()); placement1.description = "Contains ad units that can hold creatives of size 300x250"; placement1.targetedAdUnitIds = new string[] {adUnit1.id, adUnit2.id}; Placement placement2 = new Placement(); placement2.name = string.Format("Medium Square AdUnit Placement #{0}", utils.GetTimeStamp()); placement2.description = "Contains ad units that can hold creatives of size 300x250"; placement2.targetedAdUnitIds = new string[] {adUnit1.id, adUnit2.id}; Placement[] newPlacements = null; Assert.DoesNotThrow(delegate() { newPlacements = placementService.createPlacements(new Placement[] {placement1, placement2}); }); Assert.NotNull(newPlacements); Assert.AreEqual(newPlacements.Length, 2); Assert.NotNull(newPlacements[0]); Assert.AreEqual(newPlacements[0].name, placement1.name); Assert.AreEqual(newPlacements[0].description, placement1.description); Assert.Contains(adUnit1.id, newPlacements[0].targetedAdUnitIds); Assert.Contains(adUnit2.id, newPlacements[0].targetedAdUnitIds); Assert.NotNull(newPlacements[1]); Assert.AreEqual(newPlacements[1].name, placement2.name); Assert.AreEqual(newPlacements[1].description, placement2.description); Assert.Contains(adUnit1.id, newPlacements[1].targetedAdUnitIds); Assert.Contains(adUnit2.id, newPlacements[1].targetedAdUnitIds); }
public void aaaFakeLicenseDatabase() { Assert.Throws<NoValidVelocityDBLicenseFoundException>(() => { using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginUpdate(); Database database; License license = new License("Mats", 1, null, null, null, 99999, DateTime.MaxValue, 9999, 99, 9999); Placement placer = new Placement(License.PlaceInDatabase, 1, 1, 1); license.Persist(placer, session); for (uint i = 10; i < 20; i++) { database = session.NewDatabase(i); Assert.NotNull(database); } session.Commit(); File.Copy(Path.Combine(systemDir, "20.odb"), Path.Combine(systemDir, "4.odb")); session.BeginUpdate(); for (uint i = 21; i < 30; i++) { database = session.NewDatabase(i); Assert.NotNull(database); } session.RegisterClass(typeof(VelocityDbSchema.Samples.Sample1.Person)); Graph g = new Graph(session); session.Persist(g); session.Commit(); } }); }
public void Init() { TestUtils utils = new TestUtils(); placementService = (PlacementService) user.GetService(DfpService.v201511.PlacementService); adUnit1 = utils.CreateAdUnit(user); adUnit2 = utils.CreateAdUnit(user); placement = utils.CreatePlacement(user, new string[] {adUnit1.id, adUnit2.id}); }
public MainWindow() { InitializeComponent(); if (Directory.Exists(systemDir)) Directory.Delete(systemDir, true); // remove systemDir from prior runs and all its databases. try { session = new SessionBase[4]; thread = new Thread[4]; session[0] = new SessionNoServer(systemDir, int.Parse(session1LockTimeout.Text)); session[1] = new SessionNoServer(systemDir, int.Parse(session2LockTimeout.Text)); session[2] = new SessionNoServer(systemDir, int.Parse(session3LockTimeout.Text)); session[3] = new SessionNoServer(systemDir, int.Parse(session4LockTimeout.Text)); session[0].BeginUpdate(); Placement place = new Placement(10); Number number = new Number(); session[0].Persist(place, number); number = new Number(2); place = new Placement(11); session[0].Persist(place, number); number = new Number(3); place = new Placement(12); session[0].Persist(place, number); session[0].Commit(); } catch (Exception ex) { session1messages.Content = ex.Message; } }
public void UpdateTowerGUI(Placement selectedTower = null) { Color col; float blorbAmount = BlorbManager.Instance.BlorbAmount; Placement[] placements = GUIManager.instance.towers.gameObject.GetComponentsInChildren<Placement>(); foreach (Placement placement in placements) { if (placement.cost > blorbAmount) { col = new Color(0.3f, 0f, 0f); } else if (placement == selectedTower) { continue; } else { col = new Color(1f, 1f, 1f); } placement.GetComponent<SpriteRenderer>().color = col; placement.transform.parent.GetComponent<SpriteRenderer>().color = col; } // add health button if (blorbAmount < AddHealthButton.cost || Center.Instance.health > 90f) { addHealthButton.GetComponent<SpriteRenderer>().color = new Color(0.3f, 0f, 0f); } else { addHealthButton.GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f); } }
public Equipment(string _name, int a, int d, Placement p, PlayerCharacter pc, string desc) : base(_name, pc, desc) { addAtk = a; addDef = d; part = p; description = desc; }
/// <summary> /// Creates new monster group. /// </summary> /// <param name="name"></param> /// <param name="puzzle"></param> /// <param name="place"></param> /// <param name="spawnPosition"></param> public MonsterGroup(string name, Puzzle puzzle, PuzzlePlace place, Placement spawnPosition = Placement.Random) { _monsters = new List<NPC>(); this.Name = name; this.Puzzle = puzzle; this.Place = place; _spawnPosition = spawnPosition; }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to which placements are added. /// </param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupCriterionService. AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService) user.GetService(AdWordsService.v201509.AdGroupCriterionService); // Create the placement. Placement placement1 = new Placement(); placement1.url = "http://mars.google.com"; // Create biddable ad group criterion. AdGroupCriterion placementCriterion1 = new BiddableAdGroupCriterion(); placementCriterion1.adGroupId = adGroupId; placementCriterion1.criterion = placement1; // Create the placement. Placement placement2 = new Placement(); placement2.url = "http://venus.google.com"; // Create biddable ad group criterion. AdGroupCriterion placementCriterion2 = new BiddableAdGroupCriterion(); placementCriterion2.adGroupId = adGroupId; placementCriterion2.criterion = placement2; // Create the operations. AdGroupCriterionOperation placementOperation1 = new AdGroupCriterionOperation(); placementOperation1.@operator = Operator.ADD; placementOperation1.operand = placementCriterion1; AdGroupCriterionOperation placementOperation2 = new AdGroupCriterionOperation(); placementOperation2.@operator = Operator.ADD; placementOperation2.operand = placementCriterion2; try { // Create the placements. AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate( new AdGroupCriterionOperation[] {placementOperation1, placementOperation2}); // Display the results. if (retVal != null && retVal.value != null) { foreach (AdGroupCriterion adGroupCriterion in retVal.value) { // If you are adding multiple type of criteria, then you may need to // check for // // if (adGroupCriterion is Placement) { ... } // // to identify the criterion type. Console.WriteLine("Placement with ad group id = '{0}, placement id = '{1}, url = " + "'{2}' was created.", adGroupCriterion.adGroupId, adGroupCriterion.criterion.id, (adGroupCriterion.criterion as Placement).url); } } else { Console.WriteLine("No placements were added."); } } catch (Exception e) { throw new System.ApplicationException("Failed to create placements.", e); } }
protected override void OnPanelClick (Gdk.EventButton e, Placement placement) { if (e.TriggersContextMenu ()) { CommandEntrySet opset = new CommandEntrySet (); opset.AddItem (CommandSystemCommands.ToolbarList); Gtk.Menu menu = manager.CreateMenu (opset); menu.Popup (null, null, null, 0, e.Time); } base.OnPanelClick (e, placement); }
/// <summary> /// Default constructor. /// </summary> public Legend() { xAttach_ = PlotSurface2D.XAxisPosition.Top; yAttach_ = PlotSurface2D.YAxisPosition.Right; xOffset_ = 10; yOffset_ = 1; verticalEdgePlacement_ = Placement.Outside; horizontalEdgePlacement_ = Placement.Inside; neverShiftAxes_ = false; }
/// <summary> /// Constructor containing info for unpinning a tile. /// </summary> /// <param name="tileId">The Id of the tile to pin.</param> /// <param name="anchorElement">The anchor element that the pin request dialog will display next to.</param> /// <param name="requestPlacement">The Placement value that tells where the pin request dialog displays in relation to anchorElement.</param> public TileInfo( string tileId, Windows.UI.Xaml.FrameworkElement anchorElement, Placement requestPlacement) { this.TileId = tileId; this.AnchorElement = anchorElement; this.RequestPlacement = requestPlacement; }
protected override void OnTapped(TappedRoutedEventArgs e) { base.OnTapped(e); if (this.ContextMenu != null) { this.ContextMenu.PlacementTarget = this; this.ContextMenu.Placement = this.Placement; this.ContextMenu.DataContext = this.DataContext; this.ContextMenu.IsOpen = true; } }
public void Create1Root() { using (SessionNoServer session = new SessionNoServer(systemDir)) { session.BeginUpdate(); Placement placementRoot = new Placement(IssueTracker.PlaceInDatabase); IssueTracker issueTracker = new IssueTracker(10, session); User user = new User(null, "*****@*****.**", "Mats", "Persson", "matspca"); user.Persist(session, user); PermissionScheme permissions = new PermissionScheme(user); issueTracker.Permissions = permissions; issueTracker.Persist(placementRoot, session); session.Commit(); } }
public override UInt64 Persist(Placement place, SessionBase session, bool persistRefs = true, bool disableFlush = false, Queue<IOptimizedPersistable> toPersist = null) { if (IsPersistent == false) { session.RegisterClass(typeof(AspNetIdentity)); session.RegisterClass(typeof(UserLoginInfoAdapter)); session.RegisterClass(typeof(IdentityUser)); session.RegisterClass(typeof(IdentityRole)); session.RegisterClass(typeof(BTreeMap<string, UserLoginInfoAdapter>)); session.RegisterClass(typeof(BTreeMap<string, UInt64>)); session.RegisterClass(typeof(BTreeSet<IdentityUser>)); session.RegisterClass(typeof(BTreeSet<IdentityRole>)); return base.Persist(place, session, persistRefs, disableFlush, toPersist); } return Id; }
/// <summary> /// Constructor containing info for pinning a tile. /// </summary> /// <param name="tileId">The Id of the tile to pin.</param> /// <param name="displayName">The display name for the tile.</param> /// <param name="logoUri">The Uri to the tile logo.</param> /// <param name="anchorElement">The anchor element that the pin request dialog will display next to.</param> /// <param name="requestPlacement">The Placement value that tells where the pin request dialog displays in relation to anchorElement.</param> /// <param name="arguments">Optional arguments to provide for when the tile is activated.</param> public TileInfo( string tileId, string displayName, Uri logoUri, Windows.UI.Xaml.FrameworkElement anchorElement, Placement requestPlacement, string arguments = null) { this.TileId = tileId; this.DisplayName = displayName; this.Arguments = arguments; this.LogoUri = logoUri; this.AnchorElement = anchorElement; this.RequestPlacement = requestPlacement; this.Arguments = arguments; }
public float Transaction(int diff, Vector3 position, Placement selectedTower = null) { blorbAmount += diff; blorbAmountText.text = ((int)blorbAmount).ToString(); GUIManager.Instance.UpdateTowerGUI(selectedTower); if (Mathf.Abs(diff) > 0f) { // Add blorb indicator GameObject g = ObjectPool.instance.GetObjectForType("BlorbIndicator", true); g.transform.position = position; g.transform.parent = map; BlorbIndicator b = g.GetComponent<BlorbIndicator>(); b.SetDiff(diff); } return blorbAmount; }
public static UIPopoverArrowDirection ToArrowDirection(Placement placement) { switch(placement) { case Placement.Above: return UIPopoverArrowDirection.Down; case Placement.Below: return UIPopoverArrowDirection.Up; case Placement.Left: return UIPopoverArrowDirection.Right; case Placement.Right: return UIPopoverArrowDirection.Left; default: return UIPopoverArrowDirection.Any; } }
public DockToolbarPanel (DockToolbarFrame parentFrame, Placement placement) { // ResizeMode = ResizeMode.Immediate; Placement = placement; switch (placement) { case Placement.Top: this.orientation = Orientation.Horizontal; break; case Placement.Bottom: this.orientation = Orientation.Horizontal; break; case Placement.Left: this.orientation = Orientation.Vertical; break; case Placement.Right: this.orientation = Orientation.Vertical; break; } this.parentFrame = parentFrame; }
/// <summary> /// Run the code example. /// </summary> /// <param name="service">An initialized Dfa Reporting service object /// </param> public override void Run(DfareportingService service) { long campaignId = long.Parse(_T("INSERT_CAMPAIGN_ID_HERE")); long dfaSiteId = long.Parse(_T("INSERT_SITE_ID_HERE")); long sizeId = long.Parse(_T("INSERT_SIZE_ID_HERE")); long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE")); string placementName = _T("INSERT_PLACEMENT_NAME_HERE"); // Retrieve the campaign. Campaign campaign = service.Campaigns.Get(profileId, campaignId).Execute(); // Create the placement. Placement placement = new Placement(); placement.Name = placementName; placement.CampaignId = campaignId; placement.Compatibility = "DISPLAY"; placement.PaymentSource = "PLACEMENT_AGENCY_PAID"; placement.SiteId = dfaSiteId; placement.TagFormats = new List<string>() { "PLACEMENT_TAG_STANDARD" }; // Set the size of the placement. Size size = new Size(); size.Id = sizeId; placement.Size = size; // Set the pricing schedule for the placement. PricingSchedule pricingSchedule = new PricingSchedule(); pricingSchedule.EndDate = campaign.EndDate; pricingSchedule.PricingType = "PRICING_TYPE_CPM"; pricingSchedule.StartDate = campaign.StartDate; placement.PricingSchedule = pricingSchedule; // Insert the placement. Placement result = service.Placements.Insert(placement, profileId).Execute(); // Display the new placement ID. Console.WriteLine("Placement with ID {0} was created.", result.Id); }
/// <summary> /// Constructor /// </summary> /// <param name="config">The XPath navigator containing the configuration</param> public ComponentPosition(XPathNavigator config) { string attrValue; if(config == null) throw new ArgumentNullException("config"); attrValue = config.GetAttribute("placement", String.Empty); if(!String.IsNullOrEmpty(attrValue)) place = (Placement)Enum.Parse(typeof(Placement), attrValue, true); attrValue = config.GetAttribute("instance", String.Empty); if(String.IsNullOrEmpty(attrValue)) instance = 1; else { instance = Convert.ToInt32(attrValue, CultureInfo.InvariantCulture); if(instance < 1) throw new InvalidOperationException("The instance " + "attribute cannot be less than one"); } attrValue = config.GetAttribute("id", String.Empty); if(!String.IsNullOrEmpty(attrValue)) id = attrValue; else typeName = config.GetAttribute("type", String.Empty); if((place == Placement.Before || place == Placement.After || place == Placement.Replace) && String.IsNullOrEmpty(id) && String.IsNullOrEmpty(typeName)) throw new InvalidOperationException("An ID or type name " + "must be specified if Before, After, or Replace is used " + "for the Placement option"); }
/// <summary> /// Constructor containing info for pinning a tile. /// </summary> /// <param name="tileId">The Id of the tile to pin.</param> /// <param name="shortName">The short name for the tile.</param> /// <param name="displayName">The display name for the tile.</param> /// <param name="tileOptions">The TileOptions for the tile.</param> /// <param name="logoUri">The Uri to the tile logo.</param> /// <param name="wideLogoUri">The Uri to the wide tile logo.</param> /// <param name="anchorElement">The anchor element that the pin request dialog will display next to.</param> /// <param name="requestPlacement">The Placement value that tells where the pin request dialog displays in relation to anchorElement.</param> /// <param name="arguments">Optional arguments to provide for when the tile is activated.</param> public TileInfo( string tileId, string shortName, string displayName, Windows.UI.StartScreen.TileOptions tileOptions, Uri logoUri, Uri wideLogoUri, Windows.UI.Xaml.FrameworkElement anchorElement, Placement requestPlacement, string arguments = null) { this.TileId = tileId; this.ShortName = shortName; this.DisplayName = displayName; this.Arguments = arguments; this.TileOptions = tileOptions; this.LogoUri = logoUri; this.WideLogoUri = wideLogoUri; this.AnchorElement = anchorElement; this.RequestPlacement = requestPlacement; this.Arguments = arguments; }
public void AppendFile() { Placement place = new Placement(798, 1, 1, 1, UInt16.MaxValue); using (ServerClientSession session = new ServerClientSession(systemDir)) { session.BeginUpdate(); ObjWithArray a = new ObjWithArray(10); a.Persist(place, session); session.Commit(); // commit Database 798 } place = new Placement(798, 2, 1, 100, UInt16.MaxValue); for (int i = 0; i < 25; i++) { using (ServerClientSession session = new ServerClientSession(systemDir)) { //session.SetTraceAllDbActivity(); session.BeginUpdate(); for (int j = 0; j < 1000; j++) { ObjWithArray a = new ObjWithArray(j * 10); a.Persist(place, session); } session.FlushUpdates(); session.FlushUpdatesServers(); // check if this will cause file to be appended Database db = session.NewDatabase(3567); using (ServerClientSession session2 = new ServerClientSession(systemDir)) { session2.BeginUpdate(); ObjWithArray a = new ObjWithArray(10); a.Persist(place, session2); session2.Commit(); } session.Abort(); // appended page space now unused? Need tidy? } } }
public MainWindow() { const ushort btreeNodeSize = 5000; GCSettings.LatencyMode = GCLatencyMode.Batch;// try to keep the WeakIOptimizedPersistableReference objects around longer dataGridList = new List<DataGrid>(); dataTableList = new List<DataTable>(); InitializeComponent(); session = new SessionNoServer(s_systemDir); Placement placerIndexRoot = new Placement(IndexRoot.PlaceInDatabase); session.BeginUpdate(); Console.WriteLine("Running with databases in directory: " + session.SystemDirectory); File.Copy(s_licenseDbFile, Path.Combine(session.SystemDirectory, "4.odb"), true); IndexRoot indexRoot; Database db = session.OpenDatabase(IndexRoot.PlaceInDatabase, false, false); if (db == null) { session.NewDatabase(IndexRoot.PlaceInDatabase, 0, "IndexRoot"); session.NewDatabase(Lexicon.PlaceInDatabase, 0, "Lexicon"); session.NewDatabase(Document.PlaceInDatabase, 0, "Document"); session.NewDatabase(Repository.PlaceInDatabase, 0, "Repository"); session.NewDatabase(DocumentText.PlaceInDatabase, 0, "DocumentText"); session.NewDatabase(Word.PlaceInDatabase, 0, "Word"); indexRoot = new IndexRoot(btreeNodeSize, session); if (Directory.Exists(s_booksDir)) { string[] directoryTextFiles = Directory.GetFiles(s_booksDir, "*.txt"); foreach (string fileName in directoryTextFiles) { listBoxPagesToAdd.Items.Add(fileName); } } else { wordMinCt.Text = 1.ToString(); listBoxPagesToAdd.Items.Add("http://www.VelocityDB.com/"); // other database products listBoxPagesToAdd.Items.Add("https://foundationdb.com/"); listBoxPagesToAdd.Items.Add("http://www.oracle.com/us/products/database/index.html"); listBoxPagesToAdd.Items.Add("http://www-01.ibm.com/software/data/db2/"); listBoxPagesToAdd.Items.Add("http://www.versant.com/"); listBoxPagesToAdd.Items.Add("http://web.progress.com/en/objectstore/"); listBoxPagesToAdd.Items.Add("https://www.mongodb.org/"); listBoxPagesToAdd.Items.Add("http://cassandra.apache.org/"); listBoxPagesToAdd.Items.Add("http://www.sybase.com/"); listBoxPagesToAdd.Items.Add("http://www.mcobject.com/perst"); listBoxPagesToAdd.Items.Add("http://www.marklogic.com/what-is-marklogic/"); listBoxPagesToAdd.Items.Add("http://hamsterdb.com/"); listBoxPagesToAdd.Items.Add("http://www.firebirdsql.org/"); listBoxPagesToAdd.Items.Add("http://www.h2database.com/"); listBoxPagesToAdd.Items.Add("http://www.oracle.com/technology/products/berkeley-db"); listBoxPagesToAdd.Items.Add("http://www.scimore.com/"); listBoxPagesToAdd.Items.Add("http://www.stsdb.com/"); listBoxPagesToAdd.Items.Add("http://www.sqlite.org/about.html"); listBoxPagesToAdd.Items.Add("http://www.mysql.com/products/enterprise/techspec.html"); listBoxPagesToAdd.Items.Add("http://www.objectivity.com"); listBoxPagesToAdd.Items.Add("http://vistadb.net/"); listBoxPagesToAdd.Items.Add("http://www.google.com/search?q=object+database&sourceid=ie7&rls=com.microsoft:en-us:IE-SearchBox&ie=&oe="); } indexRoot.Persist(session, indexRoot); } else indexRoot = (IndexRoot)session.Open(Oid.Encode(IndexRoot.PlaceInDatabase, 1, 1)); if (indexRoot.repository.documentSet.Count > 0) { List<Document> docs = indexRoot.repository.documentSet.ToList<Document>().Take(50).ToList<Document>(); inDbListBox.ItemsSource = docs; } updateDataGrids(indexRoot); session.Commit(); //verify(); }
public void SimpleApiServer() { long ssn = 555555; UInt16 age = 1; VelocityDbSchema.Person mats; Placement place; using (ServerClientSession session = new ServerClientSession(systemDir)) { // skip delete database since it invalidates indices session.BeginUpdate(); Database db = session.OpenDatabase(10, true, false); if (db != null) { session.DeleteDatabase(db); } session.Commit(); session.BeginUpdate(); place = new Placement(10, 2, 1, 1, 10); DateTime birthday = new DateTime(1960, 6, 13); mats = new Man("Mats", "Persson", age++, ssn++, birthday); mats.Persist(place, session); session.Commit(); session.ClearServerCache(); } UInt64 mOid1 = Oid.Encode(10, 2, 1); using (ServerClientSession session = new ServerClientSession(systemDir)) { session.BeginUpdate(); UInt32 dbNum = Oid.DatabaseNumber(mOid1); mats = (VelocityDbSchema.Person)session.Open(mOid1); Woman kinga = null; mats = new Man("Mats", "Persson", age++, ssn++, new DateTime(1960, 6, 13)); Cat cat = new Cat("Boze", 8); mats.m_pets.Add(cat); Bird bird = new Bird("Pippi", 1); cat.friends.Add(bird); mats.Persist(place, session); kinga = new Woman("Kinga", "Persson", age, ssn, mats, mats); kinga.Persist(place, session); VelocityDbSchema.Person robin = new VelocityDbSchema.Person("Robin", "Persson", 13, 1, mats, null); robin.Persist(place, session); mOid1 = mats.Id; mats = null; mats = (VelocityDbSchema.Person)session.Open(mOid1); session.Commit(); session.ClearServerCache(); } using (ServerClientSession session = new ServerClientSession(systemDir)) { session.BeginUpdate(); mats = (VelocityDbSchema.Person)session.Open(mOid1); session.Commit(); session.ClearServerCache(); } using (ServerClientSession session = new ServerClientSession(systemDir)) { session.BeginRead(); ulong mOid2 = mats.Id; mats = (VelocityDbSchema.Person)session.Open(mOid2); session.Commit(); session.ClearServerCache(); } }
public MarkerPosition(float position, double value, Placement placement) { this.position = position; this.value = value; this.placement = placement; }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to which placements are added. /// </param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupCriterionService. AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService)user.GetService(AdWordsService.v201409.AdGroupCriterionService); // Create the placement. Placement placement1 = new Placement(); placement1.url = "http://mars.google.com"; // Create biddable ad group criterion. AdGroupCriterion placementCriterion1 = new BiddableAdGroupCriterion(); placementCriterion1.adGroupId = adGroupId; placementCriterion1.criterion = placement1; // Create the placement. Placement placement2 = new Placement(); placement2.url = "http://venus.google.com"; // Create biddable ad group criterion. AdGroupCriterion placementCriterion2 = new BiddableAdGroupCriterion(); placementCriterion2.adGroupId = adGroupId; placementCriterion2.criterion = placement2; // Create the operations. AdGroupCriterionOperation placementOperation1 = new AdGroupCriterionOperation(); placementOperation1.@operator = Operator.ADD; placementOperation1.operand = placementCriterion1; AdGroupCriterionOperation placementOperation2 = new AdGroupCriterionOperation(); placementOperation2.@operator = Operator.ADD; placementOperation2.operand = placementCriterion2; try { // Create the placements. AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate( new AdGroupCriterionOperation[] { placementOperation1, placementOperation2 }); // Display the results. if (retVal != null && retVal.value != null) { foreach (AdGroupCriterion adGroupCriterion in retVal.value) { // If you are adding multiple type of criteria, then you may need to // check for // // if (adGroupCriterion is Placement) { ... } // // to identify the criterion type. Console.WriteLine("Placement with ad group id = '{0}, placement id = '{1}, url = " + "'{2}' was created.", adGroupCriterion.adGroupId, adGroupCriterion.criterion.id, (adGroupCriterion.criterion as Placement).url); } } else { Console.WriteLine("No placements were added."); } } catch (Exception ex) { Console.WriteLine("Failed to create placements.", ex); } }
DockToolbarPanel GetPanel(Placement o) { return(panels [(int)o]); }
public Tooltip Placement(Placement value) { Options["placement"] = string.Format("'{0}'", value.ToString().ToLower()); SetScript(); return(this); }
/// <summary> /// Gets all assignments from a placement for the specified dates. /// </summary> /// <param name="placement">The placement.</param> /// <param name="type">The type of assignments to load.</param> /// <param name="startDate">The start date.</param> /// <param name="endDate">The end date.</param> /// <returns>All assignments from the placement for the specified week.</returns> private IList <Assignment> GetAssignmentsInternal(Placement placement, IEnumerable <Timesheet> timesheets, IEnumerable <Notification> updateNotifications, DateTime startDate, DateTime endDate) { List <Assignment> assignments = new List <Assignment>(); foreach (Schedule schedule in placement.Schedules) { AdvanceSchedule advSchedule = new AdvanceSchedule(schedule); DateTime? nextOccurrence = advSchedule.NextOccurrence(startDate.AddMinutes(-1)); while (nextOccurrence.HasValue && nextOccurrence.Value <= endDate) { // Determine if the assignment is canceled. bool isCanceled = placement.IsCanceled || schedule.IsCanceled; foreach (DateRange cancelDate in placement.CancelDates) { isCanceled = isCanceled || (nextOccurrence.Value >= cancelDate.Start && nextOccurrence.Value <= cancelDate.End); } // Save the start time and get the next occurrence now so we can continue if we need to. DateTime start = nextOccurrence.Value.AddSeconds(schedule.Time.Start); nextOccurrence = advSchedule.NextOccurrence(nextOccurrence.Value); // If a "break off" of the new assignment is already in our assignments list, skip this assignment (it is the parent and the "break off" has priority). Assignment child = assignments.FirstOrDefault(a => a.ScheduleParentId == schedule.Id && a.Start.Date == start.Date); if (child != null) { // If the "break off" is canceled, remove it so it can be replaced by the parent. if (child.Status == AssignmentStatus.Canceled) { assignments.Remove(child); } else { continue; } } // If we have a "break off" assignment and the parent is already in our assignments list, remove the parent so it can be replaced with the "break off" one. Assignment parent = assignments.FirstOrDefault(a => a.ScheduleId == schedule.ParentId && a.Start.Date == start.Date && !isCanceled); if (parent != null) { assignments.Remove(parent); } bool isCompleted = start.AddSeconds(schedule.Time.Duration) < DateTime.Now; List <Timesheet> timesheetList = new List <Timesheet> (timesheets); bool hasTimesheet = (timesheets != null) && timesheets.Any(t => t.Start.Date == start.Date && DateHelper.DateDiff(DatePart.Second, t.Start, t.End) == schedule.Time.Duration); bool hasUpdates = (updateNotifications != null) && (updateNotifications.Count() > 0); AssignmentStatus status; if (isCompleted) { if (hasTimesheet) { status = AssignmentStatus.NoTimesheetRequired; } else { status = AssignmentStatus.TimesheetRequired; } } else { if (isCanceled) { status = AssignmentStatus.Canceled; } else if (placement.SubServiceCategory == 1 && !placement.IsConfirmed) { status = AssignmentStatus.New; } else if (hasUpdates) { status = AssignmentStatus.Updated; } else { status = AssignmentStatus.Confirmed; } } assignments.Add(new Assignment() { Start = start, Duration = schedule.Time.Duration, Status = status, Placement = placement, ScheduleId = schedule.Id, ScheduleParentId = schedule.ParentId }); } } return(assignments); }
private void UpdateToolButtons(Placement newPlacement) { _tsbDelete.Enabled = _placement.IsCustom; _tsbAdd.Enabled = !_placement.Name.Equals(_name.Text); _tsbSave.Enabled = !_tsbAdd.Enabled && _tsbDelete.Enabled && !_placement.SizeMatches(newPlacement); }
/// <summary> /// Constructs a controller for a new computation. /// </summary> /// <param name="config">Controller configuration</param> public BaseController(Configuration config) { this.activated = false; this.configuration = config; this.SerializationFormat = SerializationFactory.GetCodeGeneratorForVersion(config.SerializerVersion.First, config.SerializerVersion.Second); // set up an initial endpoint to try starting the server listening on. If endpoint is null // when we call the server constructor, it will choose one by picking an available port to listen on IPEndPoint endpoint = null; if (this.configuration.Endpoints != null) { endpoint = this.configuration.Endpoints[this.configuration.ProcessID]; } // if we pass in a null endpoint the server will pick one and return it in the ref arg this.server = new NaiadServer(ref endpoint); this.localEndpoint = endpoint; this.workerGroup = new BaseWorkerGroup(this, config.WorkerCount); this.workerGroup.Start(); this.workerGroup.Activate(); if (this.configuration.ReadEndpointsFromPPM || this.configuration.Processes > 1) { this.server.Start(); if (this.configuration.ReadEndpointsFromPPM) { int pId; this.configuration.Endpoints = RegisterAndWaitForPPM(out pId); this.configuration.ProcessID = pId; } if (this.configuration.Processes > 1) { TcpNetworkChannel networkChannel = new TcpNetworkChannel(0, this, config); this.networkChannel = networkChannel; this.server.RegisterNetworkChannel(networkChannel); this.server.AcceptPeerConnections(); this.networkChannel.WaitForAllConnections(); Logging.Info("Network channel activated"); } else { Logging.Info("Configured for single-process operation"); } } this.defaultPlacement = new Placement.RoundRobin(this.configuration.Processes, this.workerGroup.Count); #if DEBUG Logging.Progress("Warning: DEBUG build. Not for performance measurements."); #endif if (this.workerGroup.Count < Environment.ProcessorCount) { Logging.Progress("Warning: Using fewer threads than available processors (use -t to set number of threads)."); } Logging.Progress("Initializing {0} {1}", this.workerGroup.Count, this.workerGroup.Count == 1 ? "thread" : "threads"); Logging.Progress("Server GC = {0}", System.Runtime.GCSettings.IsServerGC); Logging.Progress("GC settings latencymode={0}", System.Runtime.GCSettings.LatencyMode); Logging.Progress("Using CLR {0}", System.Environment.Version); if (this.NetworkChannel != null) { this.NetworkChannel.StartMessageDelivery(); } this.graphsManaged = 0; this.baseComputations = new List <BaseComputation>(); }
private static void GetPlacementLocation(WorldObject item, EquipMask wieldedLocation, out Placement placement, out ParentLocation parentLocation) { switch (wieldedLocation) { case EquipMask.MeleeWeapon: case EquipMask.Held: case EquipMask.TwoHanded: placement = ACE.Entity.Enum.Placement.RightHandCombat; parentLocation = ACE.Entity.Enum.ParentLocation.RightHand; break; case EquipMask.Shield: if (item.ItemType == ItemType.Armor) { placement = ACE.Entity.Enum.Placement.Shield; parentLocation = ACE.Entity.Enum.ParentLocation.Shield; } else { placement = ACE.Entity.Enum.Placement.RightHandNonCombat; parentLocation = ACE.Entity.Enum.ParentLocation.LeftWeapon; } break; case EquipMask.MissileWeapon: if (item.DefaultCombatStyle == CombatStyle.Bow || item.DefaultCombatStyle == CombatStyle.Crossbow) { placement = ACE.Entity.Enum.Placement.LeftHand; parentLocation = ACE.Entity.Enum.ParentLocation.LeftHand; } else { placement = ACE.Entity.Enum.Placement.RightHandCombat; parentLocation = ACE.Entity.Enum.ParentLocation.RightHand; } break; default: placement = ACE.Entity.Enum.Placement.Default; parentLocation = ACE.Entity.Enum.ParentLocation.None; break; } }
/// <summary> /// Creates mob in puzzle, in this place. /// </summary> /// <param name="mobGroupName">Name of the mob, for reference.</param> /// <param name="mobToSpawn">Mob to spawn (Mob1-3), leave as null for auto select.</param> /// <param name="placement"></param> public void SpawnSingleMob(string mobGroupName, string mobToSpawn = null, Placement placement = Placement.Random) { DungeonMonsterGroupData data; if (mobToSpawn == null) data = this.Puzzle.GetMonsterData("Mob3") ?? this.Puzzle.GetMonsterData("Mob2") ?? this.Puzzle.GetMonsterData("Mob1"); else data = this.Puzzle.GetMonsterData(mobToSpawn); if (data == null) throw new Exception("No monster data found."); this.Puzzle.AllocateAndSpawnMob(this, mobGroupName, data, placement); }
/// <summary> /// Adds prop to place. /// </summary> /// <param name="prop"></param> /// <param name="positionType"></param> public void AddProp(DungeonProp prop, Placement positionType) { this.Puzzle.AddProp(this, prop, positionType); }
/// <summary> /// Calculates the best position to place an object in AR based on screen position. /// Could be used for tapping a location on the screen, dragging an object, or using a fixed /// cursor in the center of the screen for placing and moving objects. /// /// Objects are placed along the x/z of the grounding plane. When placed on an AR plane /// below the grounding plane, the object will drop straight down onto it in world space. /// This prevents the object from being pushed deeper into the scene when moving from a /// higher plane to a lower plane. When moving from a lower plane to a higher plane, this /// function returns a new groundingPlane to replace the old one. /// </summary> /// <returns>The best placement position.</returns> /// <param name="currentAnchorPosition">Position of the parent anchor, i.e., where the /// object is before translation starts.</param> /// <param name="screenPos">Location on the screen in pixels to place the object at.</param> /// <param name="groundingPlaneHeight">The starting height of the plane that the object is /// being placed along.</param> /// <param name="hoverOffset">How much should the object hover above the groundingPlane /// before it has been placed.</param> /// <param name="maxTranslationDistance">The maximum distance that the object can be /// translated.</param> /// <param name="translationMode">The translation mode, indicating the plane types allowed. /// </param> public static Placement GetBestPlacementPosition( Vector3 currentAnchorPosition, Vector2 screenPos, float groundingPlaneHeight, float hoverOffset, float maxTranslationDistance, TranslationMode translationMode) { Placement result = new Placement(); result.UpdatedGroundingPlaneHeight = groundingPlaneHeight; // Get the angle between the camera and the object's down direction. float angle = Vector3.Angle(Camera.main.transform.forward, Vector3.down); angle = 90.0f - angle; float touchOffsetRatio = Mathf.Clamp01(angle / 90.0f); float screenTouchOffset = touchOffsetRatio * _maxScreenTouchOffset; screenPos.y += GestureTouchesUtility.InchesToPixels(screenTouchOffset); float hoverRatio = Mathf.Clamp01(angle / 45.0f); hoverOffset *= hoverRatio; float distance = (Camera.main.transform.position - currentAnchorPosition).magnitude; float distanceHoverRatio = Mathf.Clamp01(distance / _hoverDistanceThreshold); hoverOffset *= distanceHoverRatio; // The best estimate of the point in the plane where the object will be placed: Vector3 groundingPoint; // Get the ray to cast into the scene from the perspective of the camera. TrackableHit hit; if (Frame.Raycast( screenPos.x, screenPos.y, TrackableHitFlags.PlaneWithinBounds, out hit)) { if (hit.Trackable is DetectedPlane) { DetectedPlane plane = hit.Trackable as DetectedPlane; if (IsPlaneTypeAllowed(translationMode, plane.PlaneType)) { // Avoid detecting the back of existing planes. if ((hit.Trackable is DetectedPlane) && Vector3.Dot(Camera.main.transform.position - hit.Pose.position, hit.Pose.rotation * Vector3.up) < 0) { Debug.Log("Hit at back of the current DetectedPlane"); return(result); } // Don't allow hovering for vertical or horizontal downward facing planes. if (plane.PlaneType == DetectedPlaneType.Vertical || plane.PlaneType == DetectedPlaneType.HorizontalDownwardFacing) { // Limit the translation to maxTranslationDistance. groundingPoint = LimitTranslation( hit.Pose.position, currentAnchorPosition, maxTranslationDistance); result.PlacementPlane = hit; result.PlacementPosition = groundingPoint; result.HoveringPosition = groundingPoint; result.UpdatedGroundingPlaneHeight = groundingPoint.y; result.PlacementRotation = hit.Pose.rotation; return(result); } // Allow hovering for horizontal upward facing planes. if (plane.PlaneType == DetectedPlaneType.HorizontalUpwardFacing) { // Return early if the camera is pointing upwards. if (angle < 0f) { return(result); } // Limit the translation to maxTranslationDistance. groundingPoint = LimitTranslation( hit.Pose.position, currentAnchorPosition, maxTranslationDistance); // Find the hovering position by casting from the camera onto the // grounding plane and offsetting the result by the hover offset. result.HoveringPosition = groundingPoint + (Vector3.up * hoverOffset); // If the AR Plane is above the grounding plane, then the hit plane's // position is used to replace the current groundingPlane. Otherwise, // the hit is ignored because hits are only detected on lower planes by // casting straight downwards in world space. if (groundingPoint.y > groundingPlaneHeight) { result.PlacementPlane = hit; result.PlacementPosition = groundingPoint; result.UpdatedGroundingPlaneHeight = hit.Pose.position.y; result.PlacementRotation = hit.Pose.rotation; return(result); } } else { // Not supported plane type. return(result); } } else { // Plane type not allowed. return(result); } } else { // Hit is not a plane. return(result); } } // Return early if the camera is pointing upwards. if (angle < 0f) { return(result); } // If the grounding point is lower than the current gorunding plane height, or if the // raycast did not return a hit, then we extend the grounding plane to infinity, and do // a new raycast into the scene from the perspective of the camera. Ray cameraRay = Camera.main.ScreenPointToRay(screenPos); Plane groundingPlane = new Plane(Vector3.up, new Vector3(0.0f, groundingPlaneHeight, 0.0f)); // Find the hovering position by casting from the camera onto the grounding plane // and offsetting the result by the hover offset. float enter; if (groundingPlane.Raycast(cameraRay, out enter)) { groundingPoint = LimitTranslation( cameraRay.GetPoint(enter), currentAnchorPosition, maxTranslationDistance); result.HoveringPosition = groundingPoint + (Vector3.up * hoverOffset); } else { // If we can't successfully cast onto the groundingPlane, just return early. return(result); } // Cast straight down onto AR planes that are lower than the current grounding plane. if (Frame.Raycast( groundingPoint + (Vector3.up * _downRayOffset), Vector3.down, out hit, Mathf.Infinity, TrackableHitFlags.PlaneWithinBounds)) { result.PlacementPosition = hit.Pose.position; result.PlacementPlane = hit; result.PlacementRotation = hit.Pose.rotation; return(result); } return(result); }
private void SetPlacement(Placement placement) { BindPlacement = placement; }
public static string ToDescriptionString(this Placement val) { var attributes = (DescriptionAttribute[])val.GetType().GetField(val.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false); return(attributes.Length > 0 ? attributes[0].Description : string.Empty); }
/// <summary> /// Run the code example. /// </summary> /// <param name="user">The DFP user object running the code example.</param> public override void Run(DfpUser user) { // Get the InventoryService. InventoryService inventoryService = (InventoryService)user.GetService(DfpService.v201605.InventoryService); // Get the PlacementService. PlacementService placementService = (PlacementService)user.GetService(DfpService.v201605.PlacementService); // Create local placement object to store skyscraper ad units. Placement skyscraperAdUnitPlacement = new Placement(); skyscraperAdUnitPlacement.name = string.Format("Skyscraper AdUnit Placement #{0}", this.GetTimeStamp()); skyscraperAdUnitPlacement.description = "Contains ad units that can hold creatives " + "of size 120x600"; // Create local placement object to store medium square ad units. Placement mediumSquareAdUnitPlacement = new Placement(); mediumSquareAdUnitPlacement.name = string.Format("Medium Square AdUnit Placement #{0}", this.GetTimeStamp()); mediumSquareAdUnitPlacement.description = "Contains ad units that can hold creatives " + "of size 300x250"; // Create local placement object to store banner ad units. Placement bannerAdUnitPlacement = new Placement(); bannerAdUnitPlacement.name = string.Format("Banner AdUnit Placement #{0}", this.GetTimeStamp()); bannerAdUnitPlacement.description = "Contains ad units that can hold creatives " + "of size 468x60"; List <Placement> placementList = new List <Placement>(); // Get the first 500 ad units. StatementBuilder statementBuilder = new StatementBuilder() .OrderBy("id ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); List <string> mediumSquareTargetedUnitIds = new List <string>(); List <string> skyscraperTargetedUnitIds = new List <string>(); List <string> bannerTargetedUnitIds = new List <string>(); try { AdUnitPage page = inventoryService.getAdUnitsByStatement(statementBuilder.ToStatement()); // Separate the ad units by size. if (page.results != null) { foreach (AdUnit adUnit in page.results) { if (adUnit.parentId != null && adUnit.adUnitSizes != null) { foreach (AdUnitSize adUnitSize in adUnit.adUnitSizes) { Size size = adUnitSize.size; if (size.width == 300 && size.height == 250) { if (!mediumSquareTargetedUnitIds.Contains(adUnit.id)) { mediumSquareTargetedUnitIds.Add(adUnit.id); } } else if (size.width == 120 && size.height == 600) { if (!skyscraperTargetedUnitIds.Contains(adUnit.id)) { skyscraperTargetedUnitIds.Add(adUnit.id); } } else if (size.width == 468 && size.height == 60) { if (!bannerTargetedUnitIds.Contains(adUnit.id)) { bannerTargetedUnitIds.Add(adUnit.id); } } } } } } mediumSquareAdUnitPlacement.targetedAdUnitIds = mediumSquareTargetedUnitIds.ToArray(); skyscraperAdUnitPlacement.targetedAdUnitIds = skyscraperTargetedUnitIds.ToArray(); bannerAdUnitPlacement.targetedAdUnitIds = bannerTargetedUnitIds.ToArray(); // Only create placements with one or more ad unit. if (mediumSquareAdUnitPlacement.targetedAdUnitIds.Length != 0) { placementList.Add(mediumSquareAdUnitPlacement); } if (skyscraperAdUnitPlacement.targetedAdUnitIds.Length != 0) { placementList.Add(skyscraperAdUnitPlacement); } if (bannerAdUnitPlacement.targetedAdUnitIds.Length != 0) { placementList.Add(bannerAdUnitPlacement); } Placement[] placements = placementService.createPlacements(placementList.ToArray()); // Display results. if (placements != null) { foreach (Placement placement in placements) { Console.Write("A placement with ID = '{0}', name ='{1}', and containing " + "ad units {{", placement.id, placement.name); foreach (string adUnitId in placement.targetedAdUnitIds) { Console.Write("{0}, ", adUnitId); } Console.WriteLine("} was created."); } } else { Console.WriteLine("No placements created."); } } catch (Exception e) { Console.WriteLine("Failed to create placements. Exception says \"{0}\"", e.Message); } }
public PlacementChangedEventArgs(Placement placement, PlacementChangeType changeType) { Placement = placement; ChangeType = changeType; }
public void Recover1(SessionBase session) { Database db = null; session.BeginUpdate(); db = session.OpenDatabase(88, true, false); if (db != null) { session.DeleteDatabase(db); } db = session.OpenDatabase(89, true, false); if (db != null) { session.DeleteDatabase(db); } session.Commit(); session.BeginUpdate(); db = session.NewDatabase(88); session.FlushUpdates(); session.Abort(); session.BeginUpdate(); db = session.NewDatabase(88); SortedSetAny <float> floatSet; Oid floatSetOid; string dbPath = System.IO.Path.Combine(systemDir, "89.odb"); Placement place = new Placement(88); for (int i = 0; i < 10; i++) { floatSet = new SortedSetAny <float>(); floatSet.Persist(place, session); floatSetOid = floatSet.Oid; } db = session.NewDatabase(89); session.Commit(); File.Delete(dbPath); session.BeginUpdate(); db = session.NewDatabase(89); session.Commit(); FileInfo info = new FileInfo(dbPath); info.CopyTo(dbPath + "X"); session.BeginUpdate(); SortedSetAny <int> intSet; place = new Placement(89); for (int i = 0; i < 10; i++) { intSet = new SortedSetAny <int>(); intSet.Persist(place, session); } db = session.OpenDatabase(88); var list = db.AllObjects <SortedSetAny <float> >(); foreach (SortedSetAny <float> set in list) { set.Unpersist(session); } db = session.OpenDatabase(89); session.Commit(); intSet = null; db = null; // release refs so that cached data isn't stale File.Delete(dbPath); info = new FileInfo(dbPath + "X"); info.MoveTo(dbPath); session.BeginUpdate(); intSet = (SortedSetAny <int>)session.Open(89, 1, 1, false); Debug.Assert(intSet == null); object o = session.Open(88, 1, 1, false); floatSet = (SortedSetAny <float>)o; Debug.Assert(floatSet != null); session.Commit(); session.BeginUpdate(); db = session.OpenDatabase(88); session.DeleteDatabase(db); db = session.OpenDatabase(89); session.DeleteDatabase(db); session.Commit(); }
public void CreateDataAndIterateDb(int numObj) { using (SessionNoServer session = new SessionNoServer(s_systemDir)) { session.Verify(); session.BeginUpdate(); UInt32 dbNum = session.DatabaseNumberOf(typeof(NotSharingPage)); Database db = session.OpenDatabase(dbNum, true, false); if (db != null) { session.DeleteDatabase(db); } dbNum = session.DatabaseNumberOf(typeof(SharingPageTypeA)); db = session.OpenDatabase(dbNum, true, false); if (db != null) { session.DeleteDatabase(db); } dbNum = session.DatabaseNumberOf(typeof(SharingPageTypeB)); db = session.OpenDatabase(dbNum, true, false); if (db != null) { session.DeleteDatabase(db); } session.Commit(); } using (var session = new SessionNoServerShared(s_systemDir)) { session.Verify(); session.BeginUpdate(); UInt32 dbNum = session.DatabaseNumberOf(typeof(SharingPageTypeB)); Placement place = new Placement(dbNum, 100); for (int i = 0; i < numObj; i++) { NotSharingPage ns = new NotSharingPage(); session.Persist(ns); SharingPageTypeA sA = new SharingPageTypeA(); session.Persist(sA); SharingPageTypeB sB = new SharingPageTypeB(); if (i % 5 == 0) { sB.Persist(session, place); } else if (i % 1001 == 0) { sB.Persist(session, sA); } else if (i % 3001 == 0) { sB.Persist(session, ns); } else { session.Persist(sB); } } session.Commit(); } using (SessionNoServer session = new SessionNoServer(s_systemDir)) { session.BeginRead(); session.Verify(); UInt32 dbNum = session.DatabaseNumberOf(typeof(NotSharingPage)); Database db = session.OpenDatabase(dbNum); AllObjects <NotSharingPage> all = db.AllObjects <NotSharingPage>(); ulong ct = all.Count(); dbNum = session.DatabaseNumberOf(typeof(SharingPageTypeA)); OfType ofType = db.OfType(typeof(NotSharingPage)); ulong ct2 = ofType.Count(); Assert.AreEqual(ct, ct2); Database dbA = session.OpenDatabase(dbNum); dbNum = session.DatabaseNumberOf(typeof(SharingPageTypeB)); Database dbB = session.OpenDatabase(dbNum); AllObjects <SharingPageTypeA> allA = dbA.AllObjects <SharingPageTypeA>(); AllObjects <SharingPageTypeB> allB = dbB.AllObjects <SharingPageTypeB>(); OfType allA2 = dbA.OfType(typeof(SharingPageTypeA)); int start = numObj / 2; NotSharingPage ns = all.ElementAt(numObj); SharingPageTypeA sA = allA.ElementAt(numObj); SharingPageTypeA sA2 = (SharingPageTypeA)allA2.ElementAt(numObj); Assert.AreEqual(sA, sA2); sA = allA.ElementAt(10); sA2 = (SharingPageTypeA)allA2.ElementAt(10); Assert.AreEqual(sA, sA2); //MethodInfo method = typeof(Database).GetMethod("AllObjects"); //MethodInfo generic = method.MakeGenericMethod(sA.GetType()); //dynamic itr = generic.Invoke(dbA, new object[]{ true }); //SharingPageTypeA sAb = itr.ElementAt(numObj); //Assert.AreEqual(sA, sAb); //SharingPageTypeA sAc = itr.ElementAt(numObj); SharingPageTypeB sB = allB.ElementAt(numObj); List <NotSharingPage> notSharingPageList = all.Skip(100).ToList(); List <SharingPageTypeA> sharingPageTypeA = allA.Take(5).Skip(100).ToList(); for (int i = start; i < numObj; i++) { sA = allA.ElementAt(i); } for (int i = start; i < numObj; i += 5) { ns = all.ElementAt(i); } for (int i = start; i < numObj; i += 5) { sB = allB.ElementAt(i); } for (int i = 0; i < numObj; i += 45000) { ns = all.ElementAt(i); } int allB_count = (int)allB.Count(); for (int i = 0; i < allB_count - 1; i++) { Assert.NotNull(allB.ElementAt(i)); } session.Commit(); session.BeginUpdate(); session.DeleteDatabase(db); session.DeleteDatabase(dbA); session.DeleteDatabase(dbB); session.Commit(); } }
protected virtual void OnPanelClick(Gdk.EventButton e, Placement placement) { }
public void CreateDataAndIterateSession(int numObj) { using (SessionNoServer session = new SessionNoServer(s_systemDir)) { session.BeginUpdate(); UInt32 dbNum = session.DatabaseNumberOf(typeof(NotSharingPage)); Database db = session.OpenDatabase(dbNum, true, false); if (db != null) { session.DeleteDatabase(db); } dbNum = session.DatabaseNumberOf(typeof(SharingPageTypeA)); db = session.OpenDatabase(dbNum, true, false); if (db != null) { session.DeleteDatabase(db); } dbNum = session.DatabaseNumberOf(typeof(SharingPageTypeB)); db = session.OpenDatabase(dbNum, true, false); if (db != null) { session.DeleteDatabase(db); } session.Commit(); } using (SessionNoServer session = new SessionNoServer(s_systemDir)) { session.BeginUpdate(); UInt32 dbNum = session.DatabaseNumberOf(typeof(SharingPageTypeB)); Placement place = new Placement(dbNum, 100); for (int i = 0; i < numObj; i++) { NotSharingPage ns = new NotSharingPage(); session.Persist(ns); SharingPageTypeA sA = new SharingPageTypeA(); session.Persist(sA); SharingPageTypeB sB = new SharingPageTypeB(); if (i % 5 == 0) { sB.Persist(session, place); } else if (i % 1001 == 0) { sB.Persist(session, sA); } else if (i % 3001 == 0) { sB.Persist(session, ns); } else { session.Persist(sB); } } session.Commit(); } using (var session = new SessionNoServer(s_systemDir, 5000, true, false, CacheEnum.No)) { session.BeginRead(); UInt32 dbNum = session.DatabaseNumberOf(typeof(NotSharingPage)); var db = session.OpenDatabase(dbNum); long ct = 0; var all = session.AllObjects <NotSharingPage>(true, false); foreach (var obj in all) { // loads objects one at a time ct++; } OfType all2 = session.OfType(typeof(NotSharingPage), true, false); dbNum = session.DatabaseNumberOf(typeof(SharingPageTypeA)); Database dbA = session.OpenDatabase(dbNum); dbNum = session.DatabaseNumberOf(typeof(SharingPageTypeB)); Database dbB = session.OpenDatabase(dbNum); AllObjects <SharingPageTypeA> allA = session.AllObjects <SharingPageTypeA>(true, false); AllObjects <SharingPageTypeB> allB = session.AllObjects <SharingPageTypeB>(true, false); int start = numObj / 2; NotSharingPage ns = all.ElementAt(numObj - 1); // zero based index so deduct one NotSharingPage ns2 = (NotSharingPage)all2.ElementAt(numObj - 1); Assert.AreEqual(ns, ns2); SharingPageTypeA sA = allA.ElementAt(15); SharingPageTypeB sB = allB.ElementAt(10); for (int i = start; i < numObj; i++) { ns = all.ElementAt(i); } //for (int i = start; i < numObj; i++) // ns = all.Skip(i).T //for (int i = start; i < numObj; i++) // sA = allA.ElementAt(i); all.Skip(100); all2.Skip(100); for (int i = start; i < numObj; i += 5) { ns = all.ElementAt(i); ns2 = (NotSharingPage)all2.ElementAt(i); Assert.AreEqual(ns, ns2); } for (int i = 5; i < 100; i += 5) { sB = allB.ElementAt(i); } for (int i = 0; i < numObj; i += 45000) { ns = all.ElementAt(i); } session.Commit(); session.BeginUpdate(); session.DeleteDatabase(db); session.DeleteDatabase(dbA); session.DeleteDatabase(dbB); session.Commit(); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">Id of the campaign to which targeting criteria /// are added.</param> public void Run(AdWordsUser user, long campaignId) { // Get the CampaignCriterionService. CampaignCriterionService campaignCriterionService = (CampaignCriterionService)user.GetService( AdWordsService.v201409.CampaignCriterionService); // Create language criteria. // See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html // for a detailed list of language codes. Language language1 = new Language(); language1.id = 1002; // French CampaignCriterion languageCriterion1 = new CampaignCriterion(); languageCriterion1.campaignId = campaignId; languageCriterion1.criterion = language1; Language language2 = new Language(); language2.id = 1005; // Japanese CampaignCriterion languageCriterion2 = new CampaignCriterion(); languageCriterion2.campaignId = campaignId; languageCriterion2.criterion = language2; // Create location criteria. // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html // for a detailed list of country codes. Location location1 = new Location(); location1.id = 2840; // USA CampaignCriterion locationCriterion1 = new CampaignCriterion(); locationCriterion1.campaignId = campaignId; locationCriterion1.criterion = location1; Location location2 = new Location(); location2.id = 2392; // Japan CampaignCriterion locationCriterion2 = new CampaignCriterion(); locationCriterion2.campaignId = campaignId; locationCriterion2.criterion = location2; // Add a negative campaign placement. NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion(); negativeCriterion.campaignId = campaignId; Placement placement = new Placement(); placement.url = "http://mars.google.com"; negativeCriterion.criterion = placement; CampaignCriterion[] criteria = new CampaignCriterion[] { languageCriterion1, languageCriterion2, locationCriterion1, locationCriterion2, negativeCriterion }; List <CampaignCriterionOperation> operations = new List <CampaignCriterionOperation>(); foreach (CampaignCriterion criterion in criteria) { CampaignCriterionOperation operation = new CampaignCriterionOperation(); operation.@operator = Operator.ADD; operation.operand = criterion; operations.Add(operation); } try { // Set the campaign targets. CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(operations.ToArray()); if (retVal != null && retVal.value != null) { // Display campaign targets. foreach (CampaignCriterion criterion in retVal.value) { Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" + " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId); } } } catch (Exception ex) { throw new System.ApplicationException("Failed to set Campaign criteria.", ex); } }
public void MergeFrom(SharedCriterion other) { if (other == null) { return; } if (other.ResourceName.Length != 0) { ResourceName = other.ResourceName; } if (other.sharedSet_ != null) { if (sharedSet_ == null || other.SharedSet != "") { SharedSet = other.SharedSet; } } if (other.criterionId_ != null) { if (criterionId_ == null || other.CriterionId != 0L) { CriterionId = other.CriterionId; } } if (other.Type != global::Google.Ads.GoogleAds.V4.Enums.CriterionTypeEnum.Types.CriterionType.Unspecified) { Type = other.Type; } switch (other.CriterionCase) { case CriterionOneofCase.Keyword: if (Keyword == null) { Keyword = new global::Google.Ads.GoogleAds.V4.Common.KeywordInfo(); } Keyword.MergeFrom(other.Keyword); break; case CriterionOneofCase.YoutubeVideo: if (YoutubeVideo == null) { YoutubeVideo = new global::Google.Ads.GoogleAds.V4.Common.YouTubeVideoInfo(); } YoutubeVideo.MergeFrom(other.YoutubeVideo); break; case CriterionOneofCase.YoutubeChannel: if (YoutubeChannel == null) { YoutubeChannel = new global::Google.Ads.GoogleAds.V4.Common.YouTubeChannelInfo(); } YoutubeChannel.MergeFrom(other.YoutubeChannel); break; case CriterionOneofCase.Placement: if (Placement == null) { Placement = new global::Google.Ads.GoogleAds.V4.Common.PlacementInfo(); } Placement.MergeFrom(other.Placement); break; case CriterionOneofCase.MobileAppCategory: if (MobileAppCategory == null) { MobileAppCategory = new global::Google.Ads.GoogleAds.V4.Common.MobileAppCategoryInfo(); } MobileAppCategory.MergeFrom(other.MobileAppCategory); break; case CriterionOneofCase.MobileApplication: if (MobileApplication == null) { MobileApplication = new global::Google.Ads.GoogleAds.V4.Common.MobileApplicationInfo(); } MobileApplication.MergeFrom(other.MobileApplication); break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); }
public bool Highlight(Range range, bool highlight) { ThreadHelper.ThrowIfNotOnUIThread(); if (!highlight) { _highlightAdornmentLayer.RemoveAllAdornments(); return(false); } CreateLineInfos(_textView, _textView.TextViewLines); try { var brush = CreateBrush(); range = range.Normalize(); var lineStart = range.Start.Line; var lineEnd = range.End.Line; for (var i = range.Start.Line; i <= range.End.Line; i++) { var isInnerOrLastLine = i > range.Start.Line && i <= range.End.Line; if (!_lineInfos.TryGetValue(i, out ITextViewLine lineInfo)) { if (Log.IsVerboseEnabled()) { try { var visible = _textView.TextViewLines.AsQueryable().Select(_ => _textView.TextSnapshot.GetLineNumberFromPosition(_.Extent.Start.Position) ).ToList(); if (visible.Count() >= 1) { Log.Verbose($"Could not find lineInfo for line={i}, only lines {visible.First()}-{visible.Last()} are visible"); } } catch (Exception ex) { Log.Verbose(ex, $"Problem with logging message for line={i}"); } } continue; } Placement placement; if (lineStart == lineEnd) { //single line var length = range.End.Character == int.MaxValue ? lineInfo.Extent.End.Position - lineInfo.Extent.Start.Position : range.End.Character - range.Start.Character; if (length == 0) { //highlight whole line placement = new Placement(_textView.ViewportLeft, _textView.ViewportWidth); } else { placement = _textView .GetGeometryPlacement(new SnapshotSpan(lineInfo.Extent.Snapshot, new Span(lineInfo.Extent.Start + range.Start.Character, length))); } } else { if (i == lineStart) { var startPosition = range.Start.Character + lineInfo.Extent.Start; var endLength = startPosition >= lineInfo.Extent.End.Position ? 1 : lineInfo.Extent.End.Position - Math.Max(startPosition, 0); placement = _textView .GetGeometryPlacement(new SnapshotSpan(lineInfo.Extent.Snapshot, new Span(startPosition, endLength))); } else if (i == lineEnd) { var endLength = range.End.Character == int.MaxValue ? lineInfo.Extent.End.Position - lineInfo.Extent.Start.Position : range.End.Character; placement = _textView .GetGeometryPlacement(new SnapshotSpan(lineInfo.Extent.Snapshot, new Span(lineInfo.Extent.Start, endLength))); } else { // some middle line placement = _textView.GetGeometryPlacement(lineInfo.Extent); } } var rectangleHeight = lineInfo.TextHeight + 1.35; //buffer ;) if (lineInfo.Height > rectangleHeight) { // height _might_ be taller than line height because of codelenses if (isInnerOrLastLine) { rectangleHeight = lineInfo.Height + 0.5; //buffer :) } } var element = new Rectangle { Height = rectangleHeight, Width = placement.Width, Fill = brush }; Canvas.SetLeft(element, range.Start.Character == 0 ? (int)_textView.ViewportLeft : placement.Left); Canvas.SetTop(element, isInnerOrLastLine ? lineInfo.Top : lineInfo.TextTop); _highlightAdornmentLayer.AddAdornment(lineInfo.Extent, null, element); } return(true); } catch (ArgumentException ex) { Log.Debug(ex, $"{range?.ToJson()}"); } catch (Exception ex) { Log.Warning(ex, $"{range?.ToJson()}"); } return(false); }
public void MergeFrom(CustomerNegativeCriterion other) { if (other == null) { return; } if (other.ResourceName.Length != 0) { ResourceName = other.ResourceName; } if (other.id_ != null) { if (id_ == null || other.Id != 0L) { Id = other.Id; } } if (other.Type != global::Google.Ads.GoogleAds.V3.Enums.CriterionTypeEnum.Types.CriterionType.Unspecified) { Type = other.Type; } switch (other.CriterionCase) { case CriterionOneofCase.ContentLabel: if (ContentLabel == null) { ContentLabel = new global::Google.Ads.GoogleAds.V3.Common.ContentLabelInfo(); } ContentLabel.MergeFrom(other.ContentLabel); break; case CriterionOneofCase.MobileApplication: if (MobileApplication == null) { MobileApplication = new global::Google.Ads.GoogleAds.V3.Common.MobileApplicationInfo(); } MobileApplication.MergeFrom(other.MobileApplication); break; case CriterionOneofCase.MobileAppCategory: if (MobileAppCategory == null) { MobileAppCategory = new global::Google.Ads.GoogleAds.V3.Common.MobileAppCategoryInfo(); } MobileAppCategory.MergeFrom(other.MobileAppCategory); break; case CriterionOneofCase.Placement: if (Placement == null) { Placement = new global::Google.Ads.GoogleAds.V3.Common.PlacementInfo(); } Placement.MergeFrom(other.Placement); break; case CriterionOneofCase.YoutubeVideo: if (YoutubeVideo == null) { YoutubeVideo = new global::Google.Ads.GoogleAds.V3.Common.YouTubeVideoInfo(); } YoutubeVideo.MergeFrom(other.YoutubeVideo); break; case CriterionOneofCase.YoutubeChannel: if (YoutubeChannel == null) { YoutubeChannel = new global::Google.Ads.GoogleAds.V3.Common.YouTubeChannelInfo(); } YoutubeChannel.MergeFrom(other.YoutubeChannel); break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); }
private void ResetAlignment() { this._alignment = Placement.BottomCenter; }
public void DeleteObjectsTestCreate(bool standalone, int count, UInt32 dbNumber) { SessionBase session; if (standalone) { session = new SessionNoServer(systemDir); } else { session = new ServerClientSession(systemDir); } VelocityDbSchema.Samples.Sample1.Person person; session.BeginUpdate(); //session.SetTraceDbActivity(7676); var tw = new Stopwatch(); tw.Start(); UInt64[] ids = new UInt64[count]; Placement place = new Placement(dbNumber); for (int i = 0; i < count; i++) { person = new VelocityDbSchema.Samples.Sample1.Person("Bill" + i, "Gates", 56); person.Persist(place, session); ids[i] = person.Id; } tw.Stop(); Console.WriteLine("{0} records created in {1} ms.", count, tw.ElapsedMilliseconds); session.Commit(); tw.Reset(); tw.Start(); session.BeginUpdate(); for (int i = 0; i < count; i++) { session.DeleteObject(ids[i]); } session.Commit(); tw.Stop(); Console.WriteLine("{0} records deleted by Id in {1} ms.", count, tw.ElapsedMilliseconds); session.BeginRead(); Database db = session.OpenDatabase(dbNumber); AllObjects <VelocityDbSchema.Samples.Sample1.Person> allPersons = db.AllObjects <VelocityDbSchema.Samples.Sample1.Person>(); ulong ct = allPersons.Count(); List <VelocityDbSchema.Samples.Sample1.Person> personList = db.AllObjects <VelocityDbSchema.Samples.Sample1.Person>().ToList(); Assert.IsEmpty(personList); session.Commit(); tw.Reset(); tw.Start(); session.BeginUpdate(); for (int i = 0; i < count; i++) { person = new VelocityDbSchema.Samples.Sample1.Person("Bill" + i, "Gates", 56); person.Persist(place, session); ids[i] = person.Id; } session.Commit(); tw.Stop(); Console.WriteLine("{0} records created in {1} ms.", count, tw.ElapsedMilliseconds); tw.Reset(); tw.Start(); session.BeginUpdate(); db = session.OpenDatabase(dbNumber); foreach (VelocityDbSchema.Samples.Sample1.Person p in db.AllObjects <VelocityDbSchema.Samples.Sample1.Person>()) { p.Unpersist(session); } session.Commit(); tw.Stop(); Console.WriteLine("{0} records deleted in {1} ms.", count, tw.ElapsedMilliseconds); session.BeginRead(); db = session.OpenDatabase(dbNumber); allPersons = db.AllObjects <VelocityDbSchema.Samples.Sample1.Person>(); ct = allPersons.Count(); personList = allPersons.ToList(); Assert.IsEmpty(personList); //session.Verify(); session.Commit(); session.Dispose(); }
public override void Handle(User usr, Room room) { if (!room.gameactive || !usr.IsAlive() || usr.Health <= 0) { return; } int plantingId = int.Parse(getBlock(8)); string item = getBlock(27); /* Todo - land status for disable land*/ if (!room.Placements.ContainsKey(plantingId)) { return; } Placement placement = room.getPlacement(plantingId); if (placement.Used) { return; } User planter = room.getPlacementOwner(plantingId); if (planter == null) { return; } int planterSide = room.GetSide(planter); int mySide = room.GetSide(usr); switch (item) { case "DV01": // Medic Box { usr.Health += 500; if (planter != null) { if (usr.Equals(planter) == false && mySide == planterSide && planter.droppedMedicBox < 10) { planter.droppedMedicBox++; planter.rPoints += Configs.Server.Experience.OnNormalPlaceUse; } } break; } case "DU01": // Ammo Box { if (planter != null) { if (usr.Equals(planter) == false && mySide == planterSide && planter.droppedAmmo < 10) { planter.droppedAmmo++; planter.rPoints += Configs.Server.Experience.OnLandPlaceUse; switch (usr.Class) { case 3: // Assault { usr.throwNades = 0; break; } case 4: // Heavy { usr.throwRockets = 0; break; } } } } break; } case "DU02": // M14 { usr.Health -= 100; if (usr.Health < 1) { usr.Health = 1; } if (planter != null) { if (usr.Equals(planter) == false && mySide != planterSide && planter.droppedM14 < 8) { planter.droppedM14++; planter.rPoints += Configs.Server.Experience.OnLandPlaceUse; } } break; } case "DS05": // Flash { if (planter != null) { if (usr.Equals(planter) == false && mySide != planterSide && planter.droppedFlash < 6) { planter.droppedFlash++; planter.rPoints += Configs.Server.Experience.OnNormalPlaceUse; } } break; } case "DZ01": // Heavy Ammo Box { if (usr.Class == 4) { usr.throwRockets = 0; } break; } } if (usr.Health > 1000) { usr.Health = 1000; } sendBlocks[10] = usr.Health; room.RemovePlacement(plantingId); /* Important */ sendPacket = true; }
// 该示例要运行成功,需要修改一些网络和安全组的设置。 // 请慎重运行该示例,因为创建成功后会产生扣费。 static void Main1(string[] args) { try { // 必要步骤: // 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。 // 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。 // 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人, // 以免泄露密钥对危及你的财产安全。 Credential cred = new Credential { SecretId = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID"), SecretKey = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY") }; // 实例化一个client选项,可选的,没有特殊需求可以跳过 ClientProfile clientProfile = new ClientProfile(); // 非必要步骤 // 实例化一个客户端配置对象,可以指定超时时间等配置 HttpProfile httpProfile = new HttpProfile(); // 代理服务器,当你的环境下有代理服务器时设定 httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY"); clientProfile.HttpProfile = httpProfile; // 实例化要请求产品(以cvm为例)的client对象 // 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量,clientProfile是可选的 CvmClient client = new CvmClient(cred, "ap-guangzhou", clientProfile); // 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数 // 你可以直接查询SDK源码确定DescribeZonesRequest有哪些属性可以设置, // 属性可能是基本类型,也可能引用了另一个数据结构。 // 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明。 RunInstancesRequest req = new RunInstancesRequest(); Placement placement = new Placement(); placement.Zone = "ap-guangzhou-3"; req.Placement = placement; req.ImageId = "img-8toqc6s3"; req.InstanceChargeType = "POSTPAID_BY_HOUR"; req.InstanceName = "DOTNET_SDK_TEST"; req.InstanceType = "S2.SMALL1"; InternetAccessible ia = new InternetAccessible(); ia.InternetChargeType = "BANDWIDTH_POSTPAID_BY_HOUR"; ia.InternetMaxBandwidthOut = 10; ia.PublicIpAssigned = true; req.InternetAccessible = ia; LoginSettings ls = new LoginSettings(); ls.Password = "******"; req.LoginSettings = ls; req.SecurityGroupIds = new string[] { "sg-icy671l9" }; SystemDisk sd = new SystemDisk(); sd.DiskSize = 50; sd.DiskType = "CLOUD_BASIC"; req.SystemDisk = sd; VirtualPrivateCloud vpc = new VirtualPrivateCloud(); vpc.VpcId = "vpc-8ek64x3d"; vpc.SubnetId = "subnet-b1wk8b10"; req.VirtualPrivateCloud = vpc; // 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的 // 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应 RunInstancesResponse resp = client.RunInstances(req). ConfigureAwait(false).GetAwaiter().GetResult(); // 输出json格式的字符串回包 Console.WriteLine(AbstractModel.ToJsonString(resp)); } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.Read(); }
/// <summary> /// Gets the shared criteria in a shared set. /// </summary> /// <param name="user">The user that owns the shared set.</param> /// <param name="sharedSetIds">The shared criteria IDs.</param> /// <returns>The list of shared criteria.</returns> private List <SharedCriterion> GetSharedCriteria(AdWordsUser user, List <string> sharedSetIds) { using (SharedCriterionService sharedCriterionService = (SharedCriterionService)user.GetService( AdWordsService.v201708.SharedCriterionService)) { Selector selector = new Selector() { fields = new string[] { SharedSet.Fields.SharedSetId, Criterion.Fields.Id, Keyword.Fields.KeywordText, Keyword.Fields.KeywordMatchType, Placement.Fields.PlacementUrl }, predicates = new Predicate[] { Predicate.In(SharedSet.Fields.SharedSetId, sharedSetIds) }, paging = Paging.Default }; List <SharedCriterion> sharedCriteria = new List <SharedCriterion>(); SharedCriterionPage page = new SharedCriterionPage(); try { do { // Get the campaigns. page = sharedCriterionService.get(selector); // Display the results. if (page != null && page.entries != null) { int i = selector.paging.startIndex; foreach (SharedCriterion sharedCriterion in page.entries) { switch (sharedCriterion.criterion.type) { case CriterionType.KEYWORD: Keyword keyword = (Keyword)sharedCriterion.criterion; Console.WriteLine("{0}) Shared negative keyword with ID {1} and text '{2}' " + "was found.", i + 1, keyword.id, keyword.text); break; case CriterionType.PLACEMENT: Placement placement = (Placement)sharedCriterion.criterion; Console.WriteLine("{0}) Shared negative placement with ID {1} and URL '{2}' " + "was found.", i + 1, placement.id, placement.url); break; default: Console.WriteLine("{0}) Shared criteria with ID {1} was found.", i + 1, sharedCriterion.criterion.id); break; } i++; sharedCriteria.Add(sharedCriterion); } } selector.paging.IncreaseOffset(); } while (selector.paging.startIndex < page.totalNumEntries); return(sharedCriteria); } catch (Exception e) { throw new Exception("Failed to get shared criteria.", e); } } }
/// <summary> /// Returns position and direction for placement. /// </summary> /// <param name="placement"></param> /// <param name="border"></param> /// <returns>3 values, X, Y, and Direction (in degree).</returns> public int[] GetPosition(Placement placement, int border = -1) { if (this.PlaceIndex == -1) throw new PuzzleException("Place hasn't been declared anything or it wasn't reserved."); // todo: check those values var radius = 0; if (border >= 0) { radius = (_room.RoomType == RoomType.Alley ? 200 - border : 800 - border); if (radius < 0) radius = 0; } else radius = (_room.RoomType == RoomType.Alley ? 200 : 800); if (!_placementProviders.ContainsKey(placement)) _placementProviders[placement] = new PlacementProvider(placement, radius); var pos = _placementProviders[placement].GetPosition(); if (pos == null) { if (!_placementProviders.ContainsKey(Placement.Random)) _placementProviders[Placement.Random] = new PlacementProvider(Placement.Random, radius); pos = _placementProviders[Placement.Random].GetPosition(); } pos[0] += this.X; pos[1] += this.Y; return pos; }
private void OnMouseWheel(object sender, MouseWheelEventArgs e) { Point mousePos = e.GetPosition(listeningPanel); Rect listeningPanelBounds = new Rect(listeningPanel.RenderSize); if (!listeningPanelBounds.Contains(mousePos)) { return; } var foundActivePlotter = UpdateActivePlotter(e); if (!foundActivePlotter) { return; } int delta = -e.Delta; Point zoomTo = mousePos.ScreenToViewport(activePlotter.Transform); double zoomSpeed = Math.Abs(delta / Mouse.MouseWheelDeltaForOneLine); zoomSpeed *= wheelZoomSpeed; if (delta < 0) { zoomSpeed = 1 / zoomSpeed; } DataRect visible; if (activePlotter.Viewport.LockZoomX && activePlotter.Viewport.LockZoomY) { e.Handled = true; return; } else if (activePlotter.Viewport.LockZoomX) { visible = activePlotter.Viewport.Visible.ZoomY(zoomTo, zoomSpeed); } else if (activePlotter.Viewport.LockZoomY) { visible = activePlotter.Viewport.Visible.ZoomX(zoomTo, zoomSpeed); } else { visible = activePlotter.Viewport.Visible.Zoom(zoomTo, zoomSpeed); } DataRect oldVisible = activePlotter.Viewport.Visible; if (Placement.IsBottomOrTop()) { visible.YMin = oldVisible.YMin; visible.Height = oldVisible.Height; } else { visible.XMin = oldVisible.XMin; visible.Width = oldVisible.Width; } activePlotter.Viewport.Visible = visible; e.Handled = true; }
/// <summary> /// Creates mob in puzzle, in place. /// </summary> /// <param name="mobGroupName">Name of the mob, for reference.</param> /// <param name="raceId">Race to spawn.</param> /// <param name="amount">Number of monsters to spawn.</param> /// <param name="placement"></param> public void SpawnSingleMob(string mobGroupName, int raceId, int amount, Placement placement = Placement.Random) { if (amount < 1) amount = 1; var group = new DungeonMonsterGroupData(); group.Add(new DungeonMonsterData() { RaceId = raceId, Amount = amount }); this.Puzzle.AllocateAndSpawnMob(this, mobGroupName, group, placement); }
private void OnMouseMove(object sender, MouseEventArgs e) { if (lmbPressed) { // panning: if (e.LeftButton == MouseButtonState.Released) { lmbPressed = false; RevertChanges(); return; } Point screenMousePos = e.GetPosition(listeningPanel); Point dataMousePos = screenMousePos.ScreenToViewport(activePlotter.Transform); DataRect visible = activePlotter.Viewport.Visible; double delta; if (Placement.IsBottomOrTop()) { delta = (dataMousePos - dragStartInViewport).X; visible.XMin -= delta; } else { delta = (dataMousePos - dragStartInViewport).Y; visible.YMin -= delta; } if (screenMousePos != lmbInitialPosition) { listeningPanel.Cursor = Placement.IsBottomOrTop() ? Cursors.ScrollWE : Cursors.ScrollNS; } activePlotter.Viewport.Visible = visible; e.Handled = true; } else if (rmbPressed) { // one direction zooming: if (e.RightButton == MouseButtonState.Released) { rmbPressed = false; RevertChanges(); return; } Point screenMousePos = e.GetPosition(listeningPanel); DataRect visible = activePlotter.Viewport.Visible; double delta; bool isHorizontal = Placement.IsBottomOrTop(); if (isHorizontal) { delta = (screenMousePos - rmbInitialPosition).X; } else { delta = (screenMousePos - rmbInitialPosition).Y; } if (delta < 0) { delta = 1 / Math.Exp(-delta / RmbZoomScale); } else { delta = Math.Exp(delta / RmbZoomScale); } Point center = dragStartInViewport; if (isHorizontal) { visible = rmbDragStartRect.ZoomX(center, delta); } else { visible = rmbDragStartRect.ZoomY(center, delta); } if (screenMousePos != lmbInitialPosition) { listeningPanel.Cursor = Placement.IsBottomOrTop() ? Cursors.ScrollWE : Cursors.ScrollNS; } activePlotter.Viewport.Visible = visible; //e.Handled = true; } }