public string Name(Job j) { if (HasTag(j.MetaData.Id)) return _ids[j.MetaData.Id]; else return "#" + j.MetaData.Id.ToString(); }
public void AddJobTile(Job job) { JobTile tile = new JobTile(job); shellTileService.Create(tile.NavigationUri, tile.CreateTileData(new Job[] { job }, applicationSettings)); }
public override bool AssignPreemptiveJob(Job job) { var assigned = false; if (job.NodeIdList.Count == 0) { // ask for 1 time slot each time var nodeList = this.Cluster.GetFitNodeList(job.RequiredNodes, this.CurrentTime, 1); if (nodeList.Count < job.RequiredNodes) return false; assigned = true; job.NodeIdList = nodeList; } else { assigned = this.Cluster.IsAviable(this.CurrentTime, job.NodeIdList); } if (assigned) { UpdateResouce(job, this.CurrentTime); this.Cluster.FillBitMap(job, this.CurrentTime); job.AssignedTimeSlots++; } if (job.AssignedTimeSlots == job.ProcessingTime) job.Scheduled = true; return true; }
private void StartRunningJob(Job job) { Logger.Info("Starting WorkerProcess for job {0}", job.Id); Process process = new Process { StartInfo = { FileName = ConfigurationManager.AppSettings["WorkerProcessLocation"], Arguments = string.Format("-i {0}", job.Id), UseShellExecute = false, CreateNoWindow = true, ErrorDialog = false, RedirectStandardError = true } }; process.Start(); process.WaitForExit(); if (process.ExitCode != 0) { Logger.Error("Worker process for job ID: {0} exited with error.", job.Id); //using (var repo = new JobRepository()) //{ // //repo.UpdateStateForJob(job, JobState.CompletedWithError, "Unspecified error"); //} } else { Logger.Info("Worker process for job ID: {0} completed.", job.Id); } }
/// <summary> /// 创建步骤 2 ,开始Billing /// </summary> /// <param name="jb">Job 实例</param> /// <param name="databaseName">数据库名</param> /// <param name="strSQl">SQL命令</param> public void CreateStartBilling(Job jb, string databaseName, string strSQl) { try { JobStep jbstp = new JobStep(jb, "开始Billing"); //数据库 jbstp.DatabaseName = databaseName; //计划执行的SQL命令 jbstp.Command = strSQl; //* 制定执行步骤 //成功时执行的操作 jbstp.OnSuccessAction = StepCompletionAction.QuitWithSuccess; //jbstp.OnSuccessAction = StepCompletionAction.GoToStep; //jbstp.OnSuccessStep = 3; //失败时执行的操作 jbstp.OnFailAction = StepCompletionAction.QuitWithFailure; //创建 SQL 代理实例的作业步骤. jbstp.Create(); } catch (Exception) { throw; } }
public Job Change(Job job, JobStatus newStatus, Activity activity = null) { switch (newStatus) { case JobStatus.Ready: return CheckStatusAndInvoke(job, new[] {JobStatus.Created}, () => _jobMutator.Mutate<StatusChanger>(job, status: newStatus)); case JobStatus.Running: return CheckStatusAndInvoke(job, RunnableStatuses, () => _runningTransition.Transit(job)); case JobStatus.Completed: return CheckStatusAndInvoke(job, CompletableStatus, () => _endTransition.Transit(job, JobStatus.Completed)); case JobStatus.Failed: return CheckStatusAndInvoke(job, FallibleStatuses, () => _failedTransition.Transit(job)); case JobStatus.WaitingForChildren: return CheckStatusAndInvoke(job, AwaitableStatus, () => _waitingForChildrenTransition.Transit(job, activity)); case JobStatus.Poisoned: return CheckStatusAndInvoke(job, PoisonableStatus, () => _endTransition.Transit(job, JobStatus.Poisoned)); case JobStatus.Cancelling: return _jobMutator.Mutate<StatusChanger>(job, status: newStatus); case JobStatus.Cancelled: return _endTransition.Transit(job, JobStatus.Cancelled); } return job; }
public async Task CreateAndSendSignatureJob() { ClientConfiguration clientConfiguration = null; //As initialized earlier var directClient = new DirectClient(clientConfiguration); var documentToSign = new Document( "Subject of Message", "This is the content", FileType.Pdf, @"C:\Path\ToDocument\File.pdf"); var exitUrls = new ExitUrls( new Uri("http://redirectUrl.no/onCompletion"), new Uri("http://redirectUrl.no/onCancellation"), new Uri("http://redirectUrl.no/onError") ); var job = new Job( documentToSign, new Signer(new PersonalIdentificationNumber("12345678910")), "SendersReferenceToSignatureJob", exitUrls ); var directJobResponse = await directClient.Create(job); }
public override string Update(Job job, Phase phase, string body = null, string contentType = null, string accept = null) { job.UpdateState(JobStateType.INPROGRESS, "UPDATE to " + phase.Name); string response; if (!contentType.ToLower().Equals("application/xml")) { response = "Invalid Content-Type, expecting application/xml"; job.UpdatePhaseState(phase.Name, PhaseStateType.FAILED, response); throw new RejectedException(response); } LearnerPersonal data; try { data = SerialiserFactory.GetXmlSerialiser<LearnerPersonal>().Deserialise(body); } catch(Exception e) { response = "Error decoding xml data: " + e.Message; job.UpdatePhaseState(phase.Name, PhaseStateType.FAILED, response); throw new RejectedException(response, e); } NameType name = data.PersonalInformation.Name; job.UpdatePhaseState(phase.Name, PhaseStateType.COMPLETED, "UPDATE"); response = "Got UPDATE message for " + phase.Name + "@" + job.Id + " with content type " + contentType + " and accept " + accept + ".\nGot record for learner:" + name.GivenName + " " + name.FamilyName; return response; }
Job RetrieveVacancy() { var objJobId = Request.QueryString["jobid"]; var isInvalid = false; var j = new Job(); if (objJobId != null && objJobId.IsNumeric() && int.Parse(objJobId) > 0) { var jobId = int.Parse(objJobId); //retrieve vacancy object j = new Jobs().GetJob(jobId); //validate if (j == null || j.JobId <= 0) { isInvalid = true; } //******** NEED TO IMPLEMENT CHECK CLIENT USERS PERMISSIONS ****** } else isInvalid = true; if (isInvalid) //invalid request redirect Response.Redirect("/404.aspx"); return j; }
protected override Job TryGiveTerminalJob(Pawn pawn) { Pawn mindStateTarget = pawn.mindState.enemyTarget as Pawn; if (mindStateTarget == null) { return null; } // Check if target is still valid if (mindStateTarget.Destroyed || mindStateTarget.Downed || Find.TickManager.TicksGame - pawn.mindState.lastEngageTargetTick > EnemyForgetTime || (pawn.Position - mindStateTarget.Position).LengthHorizontalSquared > (MaxSearchDistance * MaxSearchDistance) || !GenSight.LineOfSight(pawn.Position, mindStateTarget.Position, false)) { pawn.mindState.enemyTarget = null; return null; } if (pawn.story != null && pawn.story.WorkTagIsDisabled(WorkTags.Violent)) { return null; } Job job = new Job(JobDefOf.AttackMelee, mindStateTarget) { maxNumMeleeAttacks = 1, expiryInterval = Rand.Range(EnemyForgetTime, MaxMeleeChaseTicksMax) }; return job; }
/// <summary> /// Engages autopilot execution to FinalDestination either by direct /// approach or following a course. /// </summary> public void Engage(Vector3 destination) { if (_job != null && _job.IsRunning) { _job.Kill(); } Destination = destination; _job = new Job(Engage(), true); }
private void GenerateButton_Click(object sender, EventArgs e) { string filename; InitialiseSaveDialog(); if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { filename = saveFileDialog.FileName; string dstLang = destinationLanguage.SelectedItem.ToString(); string queryType = queryTypeComboBox.SelectedItem.ToString(); Job job = new Job( connectionStringTextBox.Text, dstTableTextBox.Text, filename, sqlTextBox.Text, () => QueryWriterFactory.Instance.Get(dstLang), () => QueryFactory.Instance.Get(queryType), (j,c) => HandleKeysRequired(j,c), (j, ex) => HandleException(j, ex), (j) => HandleComplete(j)); StartScriptGeneration(); job.Process(); } else { statusLabel.Text = "Cancelled."; } }
public override Job JobOnThing( Pawn pawn, Thing t ) { var warden = pawn; var slave = t as Pawn; if( ( slave == null )|| ( slave.guest == null )|| ( slave.guest.interactionMode != Data.PIM.FreeSlave )|| ( slave.Downed )|| ( !slave.Awake() )|| ( !warden.CanReserveAndReach( slave, PathEndMode.ClosestTouch, warden.NormalMaxDanger(), 1 ) ) ) { return null; } var collar = slave.WornCollar(); if( collar == null ) { // Slave isn't wearing a collar, wut? return null; } IntVec3 result; if( !RCellFinder.TryFindPrisonerReleaseCell( slave, warden, out result ) ) { return null; } var job = new Job( Data.JobDefOf.FreeSlave, slave, collar, result ); job.maxNumToCarry = 1; return job; }
public object Deserialize(JsonValue json, JsonMapper mapper) { var job = new Job(); var clientJson = json.GetValue("client"); job.Id = json.GetValueOrDefault<string>("id", ""); job.Title = json.GetValueOrDefault<string>("title", ""); job.Snippet = json.GetValueOrDefault<string>("snippet", ""); job.Skills = deserializeSkills(json.GetValues("skills")); job.Category = json.GetValueOrDefault<string>("category", ""); job.Subcategory = json.GetValueOrDefault<string>("subcategory", ""); job.JobType = json.GetValueOrDefault<string>("job_type", ""); job.Duration = json.GetValueOrDefault<string>("duration", ""); job.Budget = json.GetValueOrDefault<string>("budget", ""); job.Workload = json.GetValueOrDefault<string>("workload", ""); job.Status = json.GetValueOrDefault<string>("job_status", ""); job.Url = json.GetValueOrDefault<string>("url", ""); job.DateCreated = json.GetValueOrDefault<DateTime>("date_created", DateTime.MinValue); if (clientJson != null) { job.Client.Country = clientJson.GetValueOrDefault<string>("country", ""); job.Client.FeedbackRating = clientJson.GetValueOrDefault<float>("feedback", 0); job.Client.ReviewCount = clientJson.GetValueOrDefault<int>("reviews_count", 0); job.Client.JobCount = clientJson.GetValueOrDefault<int>("jobs_posted", 0); job.Client.HireCount = clientJson.GetValueOrDefault<int>("past_hires", 0); job.Client.PaymentVerificationStatus = clientJson.GetValueOrDefault<string>("payment_verification_status", ""); } return job; }
Job EndTree(Job job, JobStatus endStatus) { // If this is the root, mutate to completed status. if (job.ParentId == null) return _jobMutator.Mutate<EndTransition>(job, status: JobStatus.Completed); job = _jobMutator.Mutate<EndTransition>(job, PendingEndStatus[endStatus]); /* * First, load the parent, find the await record for this job and * update its status to end status. */ // ReSharper disable once PossibleInvalidOperationException var parent = _jobRepository.Load(job.ParentId.Value); var @await = parent.Continuation.Find(job); @await.Status = endStatus; /* * After we set the await's status, invoke ContinuationDispatcher to * ensure any pending await for parent is dispatched. * If ContinuationDispatcher returns any awaits, that means parent job is not * ready for completion. */ var pendingAwaits = _continuationDispatcher.Dispatch(parent); if (!pendingAwaits.Any()) EndTree(parent, JobStatus.Completed); return _jobMutator.Mutate<EndTransition>(job, endStatus); }
public static IEnumerable<IExpectation> Expectations(Job job) { var files = new string[] { }; try { files = Directory.GetFiles(job.JobDirectory, job.Id + MetaPattern, SearchOption.TopDirectoryOnly); } catch(DirectoryNotFoundException e) { _log.Error("TracksExpectation: Directory not found", e); } if (!files.Any()) { yield return new FailExpectation(String.Format("MP3 meta.xml files does not exist yet for Job ID {0}", job.Id)); yield break; } foreach (var file in files) { foreach (var track in EnumerateTracks(job, file)) { yield return track; } } }
public void Play(float itemRadius) { D.Assert(itemRadius > Constants.ZeroF); float currentScale = itemRadius * _radiusToScaleNormalizeFactor; if (currentScale != _prevScale) { float relativeScale = currentScale / _prevScale; ScaleParticleSystem(_primaryParticleSystem, relativeScale); foreach (ParticleSystem pSystem in _childParticleSystems) { ScaleParticleSystem(pSystem, relativeScale); } _prevScale = currentScale; } _primaryParticleSystem.Play(withChildren: true); D.AssertNull(_waitForExplosionFinishedJob); bool includeChildren = true; string jobName = "WaitForExplosionFinishedJob"; _waitForExplosionFinishedJob = _jobMgr.WaitForParticleSystemCompletion(_primaryParticleSystem, includeChildren, jobName, isPausable: true, waitFinished: (jobWasKilled) => { if (jobWasKilled) { // 12.12.16 An AssertNull(_jobRef) here can fail as the reference can refer to a new Job, created // right after the old one was killed due to the 1 frame delay in execution of jobCompleted(). My attempts at allowing // the AssertNull to occur failed. I believe this is OK as _jobRef is nulled from KillXXXJob() and, if // the reference is replaced by a new Job, then the old Job is no longer referenced which is the objective. Jobs Kill()ed // centrally by JobManager won't null the reference, but this only occurs during scene transitions. } else { _waitForExplosionFinishedJob = null; HandleExplosionFinished(); } MyPoolManager.Instance.DespawnEffect(transform); }); }
public async Task Dispatch(Job job, ActivityConfiguration configuration) { if (job == null) throw new ArgumentNullException("job"); if (configuration == null) throw new ArgumentNullException("configuration"); switch (job.Status) { case JobStatus.Ready: case JobStatus.Running: case JobStatus.Failed: await Run(job); break; case JobStatus.Cancelling: await Run(job, true); break; case JobStatus.WaitingForChildren: _jobCoordinator.Run(job, () => _continuationLiveness.Verify(job.Id)); break; case JobStatus.ReadyToComplete: _jobCoordinator.Run(job, () => _statusChanger.Change(job, JobStatus.Completed)); break; case JobStatus.ReadyToPoison: _jobCoordinator.Run(job, () => _statusChanger.Change(job, JobStatus.Poisoned)); break; case JobStatus.CancellationInitiated: _jobCoordinator.Run(job, () => _statusChanger.Change(job, JobStatus.Cancelled)); break; default: _eventStream.Publish<Dispatcher>(EventType.JobAbandoned, EventProperty.Named("Reason", "UnexpectedStatus"), EventProperty.JobSnapshot(job)); break; } }
public Tuple<Job, bool> Testmodus_ermitteln(Job job) { var parameters = Environment.GetCommandLineArgs(); if (parameters.Length > 1 && parameters[1].ToLower() == "/test") { return new Tuple<Job, bool>(job, true); } return new Tuple<Job, bool>(job, false); }
public override Job JobOnThing(Pawn pawn, Thing t) { Building_RepairStation rps = ListerDroids.ClosestRepairStationFor(pawn,t); Job job = new Job(ReactivateDroidJobDef, t, rps); job.maxNumToCarry = 1; return job; }
public JobStatusUpdate(Job job) { Job = job; StartTime = DateTime.UtcNow; CurrentTime = DateTime.UtcNow; Status = JobStatus.New; }
public async Task<Job> CreateJob(CreateJobInput input) { //We can use Logger, it's defined in ApplicationService class. Logger.Info("Creating a job for input: " + input); //Creating a new Task entity with given input's properties var job = new Job { Description = input.Description, Detail = input.Detail, AccountId = input.AccountId, Type = input.Type, AssignedUserId = input.AssignedUserId , PrimaryContactId = input.PrimaryContactId, Source = input.Source, Priority = input.Priority}; job.PrimaryContact = _contactRepository.Get((long)job.PrimaryContactId); job.Account = _accountRepository.Get((long)job.AccountId); job.AssignedUser = await _userManager.FindByIdAsync((long)job.AssignedUserId); //TODO: Complete creating an external Job in SLX string createdUserId = (await _userManager.FindByIdAsync((long)AbpSession.UserId)).ExternalId; ///Update in External System (Saleslogix if enabled) String result = CreateExternal(job.Account.ExternalId,job.PrimaryContact.ExternalId,createdUserId,job.AssignedUser.ExternalId,job.Description,job.Detail,"",job.Priority.ToString(),job.Source.ToString()); job.ExternalId = result; //Saving entity with standard Insert method of repositories. return await _jobRepository.InsertAsync(job); }
public void TestDontRunAtFirstIfCoresNotAvailable() { BenchmarkSystem Bs = new BenchmarkSystem(); //jobs that needs in all 27 cpus, should execute with no problems. Job job1 = new Job((string[] arg) => { return arg.Length.ToString(); }, new Owner("morten12"), 9, 10000); Job job2 = new Job((string[] arg) => { return arg.Length.ToString(); }, new Owner("morten22"), 9, 10000); Job job3 = new Job((string[] arg) => { return arg.Length.ToString(); }, new Owner("morten32"), 9, 10000); Bs.Submit(job1); Bs.Submit(job2); Bs.Submit(job3); //this job requires too many cores and should therefore not run immediately Job job4 = new Job((string[] arg) => { return arg.Length.ToString(); }, new Owner("morten4"), 9, 10000); Bs.Submit(job4); Task task = Task.Factory.StartNew(() => Bs.ExecuteAll()); Thread.Sleep(1000); Assert.AreEqual(State.Running, job1.State); Assert.AreEqual(State.Running, job2.State); Assert.AreEqual(State.Running, job3.State); // this job should not be running as there aren't enough cores for it to run. Assert.AreEqual(State.Submitted, job4.State); //it should run after the cores become available Thread.Sleep(12000); Assert.AreEqual(State.Running, job4.State); // NOTE: this test fails because the first three submitted jobs dont run simultaneusly. The factory method of Task should run them in separate threads, but somehow choses to // run them chronological instead. Maybe you can explain why? Thank you in advance. }
public void Ctor_ShouldInitializeAllProperties() { var job = new Job(_methodData, _arguments); Assert.Same(_methodData, job.MethodData); Assert.Same(_arguments, job.Arguments); }
public void nextLevel() { contractshown = false; if(currentJob>=jobs.Count){ Application.LoadLevel("End"); } else{ job = jobs[currentJob]; CVGenerator cvGenerator = new CVGenerator(); cvList = new List<CV>(); int numberOfCVs = Random.Range(4, 7); for (int num = 0; num < numberOfCVs; num++) { Candidate candidate = new Candidate(ref maleSprites, ref femaleSprites); cvList.Add(cvGenerator.generateCV(candidate)); } currentCV = 0; renderCV(); showJob(); refreshHUD(); } }
public async Task<ReplaceOneResult> UpdateOrder(Job job, OrderModel orderModel) { if (job.Order.Type != orderModel.Type) { throw new InvalidOperationException("Updating with a different ordermodel for this job"); } // FIXME: Finding a resolver here would help here dude switch (orderModel.Type) { case OrderTypes.Delivery: case OrderTypes.ClassifiedDelivery: { var orderCalculationService = new DefaultOrderCalculationService(); var serviceChargeCalculationService = new DefaultDeliveryServiceChargeCalculationService(); var orderProcessor = new DeliveryOrderProcessor( orderCalculationService, serviceChargeCalculationService); orderProcessor.ProcessOrder(orderModel); var jobUpdater = new DeliveryJobUpdater(job); jobUpdater.UpdateJob(orderModel); job = jobUpdater.Job; break; } } var result = await UpdateJob(job); return result; }
private static LogItem postprocess(MainForm mainForm, Job ajob) { if (!(ajob is D2VIndexJob)) return null; D2VIndexJob job = (D2VIndexJob)ajob; if (job.PostprocessingProperties != null) return null; StringBuilder logBuilder = new StringBuilder(); VideoUtil vUtil = new VideoUtil(mainForm); Dictionary<int, string> audioFiles = vUtil.getAllDemuxedAudio(job.AudioTracks, job.Output, 8); if (job.LoadSources) { if (job.DemuxMode != 0 && audioFiles.Count > 0) { string[] files = new string[audioFiles.Values.Count]; audioFiles.Values.CopyTo(files, 0); Util.ThreadSafeRun(mainForm, new MethodInvoker( delegate { mainForm.Audio.openAudioFile(files); })); } // if the above needed delegation for openAudioFile this needs it for openVideoFile? // It seems to fix the problem of ASW dissapearing as soon as it appears on a system (Vista X64) Util.ThreadSafeRun(mainForm, new MethodInvoker( delegate { AviSynthWindow asw = new AviSynthWindow(mainForm, job.Output); asw.OpenScript += new OpenScriptCallback(mainForm.Video.openVideoFile); asw.Show(); })); } return null; }
public override void Execute(string filename, bool testModus, Job job) { Console.WriteLine(" Delete '{0}'", filename); if (testModus) { return; } File.Delete(filename); }
public void Initialize() { scheduler = Scheduler.getInstance(); job1 = new Job((string[] args) => { foreach (string s in args) { Console.Out.WriteLine(s); } return ""; }, new Owner("owner1"), 2, 3); job2 = new Job((string[] args) => { foreach (string s in args) { Console.Out.WriteLine(s); } return ""; }, new Owner("owner2"), 2, 45); job3 = new Job((string[] args) => { foreach (string s in args) { Console.Out.WriteLine(s); } return ""; }, new Owner("owner3"), 2, 200); }
static void Main(string[] args) { Server server = new Server("."); // Get instance of SQL Agent SMO object JobServer jobServer = server.JobServer; Job job = null; JobStep step = null; JobSchedule schedule = null; // Create a schedule schedule = new JobSchedule(jobServer, "Schedule_1"); schedule.FrequencyTypes = FrequencyTypes.OneTime; schedule.ActiveStartDate = DateTime.Today; schedule.ActiveStartTimeOfDay = new TimeSpan(DateTime.Now.Hour, (DateTime.Now.Minute + 2), 0); schedule.Create(); // Create Job job = new Job(jobServer, "Job_1"); job.Create(); job.AddSharedSchedule(schedule.ID); job.ApplyToTargetServer(server.Name); // Create JobStep step = new JobStep(job, "Step_1"); step.Command = "SELECT 1"; step.SubSystem = AgentSubSystem.TransactSql; step.Create(); }
internal static IEnumerable <Toil> _MakeNewToils(this JobDriver_FoodDeliver obj) { yield return(Toils_Reserve.Reserve(TargetIndex.B, 1)); var targetThingA = obj.TargetThingA(); if (targetThingA is Building) { yield return(Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell)); if (targetThingA is Building_NutrientPasteDispenser) { yield return(Toils_Ingest.TakeMealFromDispenser(TargetIndex.A, obj.pawn)); } if (targetThingA is Building_AutomatedFactory) { yield return(Toils_FoodSynthesizer.TakeMealFromSynthesizer(TargetIndex.A, obj.pawn)); } } else { var deliveree = (Pawn)obj.pawn.CurJob.targetB.Thing; yield return(Toils_Reserve.Reserve(TargetIndex.A, 1)); yield return(Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch)); yield return(Toils_Ingest.PickupIngestible(TargetIndex.A, deliveree)); } var pathToTarget = new Toil(); pathToTarget.defaultCompleteMode = ToilCompleteMode.PatherArrival; pathToTarget.initAction = new Action(() => { Pawn pawn = obj.pawn; Job job = pawn.jobs.curJob; pawn.pather.StartPath(job.targetC, PathEndMode.OnCell); } ); pathToTarget.FailOnDestroyedNullOrForbidden(TargetIndex.B); pathToTarget.AddFailCondition(() => { Pawn pawn = (Pawn)obj.pawn.jobs.curJob.targetB.Thing; return ((pawn.Downed) || (!pawn.IsPrisonerOfColony) || (!pawn.guest.ShouldBeBroughtFood)); }); yield return(pathToTarget); var dropFoodAtTarget = new Toil(); dropFoodAtTarget.initAction = new Action(() => { Thing resultingThing; obj.pawn.carrier.TryDropCarriedThing(obj.pawn.jobs.curJob.targetC.Cell, ThingPlaceMode.Direct, out resultingThing); } ); dropFoodAtTarget.defaultCompleteMode = ToilCompleteMode.Instant; yield return(dropFoodAtTarget); }
public static List <Operation> GenerateSmallScaleProductionFor(List <Machine> allMachines, List <Material> allMaterials, Batch currentBatch, Job currentJob, int quantity) { return(GenerateFor(allMachines, allMaterials, currentBatch, currentJob, quantity, false)); }
public override IEnumerable <Toil> MakeNewToils() { this.FailOnDestroyedOrNull(TargetIndex.A); //this.FailOnBurningImmobile(TargetIndex.B); if (!forbiddenInitially) { this.FailOnForbidden(TargetIndex.A); } var ZTracker = ZUtils.ZTracker; if (pawn.Map == this.job.targetA.Thing.Map && pawn.Map == ZTracker.jobTracker[pawn].targetDest.Map) { ZLogger.Message("pawn map and thing map and dest map are same, yield breaking in JobDriver_HaulThingToDest"); yield break; } ZLogger.Message($"JobDriver HaulThingToDestAndCell1 About to call findRouteWithStairs, with pawn {GetActor()}, dest {new TargetInfo(TargetA.Thing)}, instance {this}"); Log.Message("1 - pawn.Map: " + pawn.Map + " - dest: " + new TargetInfo(TargetA.Thing).Map, true); foreach (var toil in Toils_ZLevels.GoToMap(GetActor(), new TargetInfo(TargetA.Thing).Map, this)) { yield return(toil); } Toil reserveTargetA = Toils_Reserve.Reserve(TargetIndex.A); Toil toilGoto = null; toilGoto = Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch).FailOnSomeonePhysicallyInteracting(TargetIndex.A).FailOn((Func <bool>) delegate { Pawn actor = toilGoto.actor; Job curJob = actor.jobs.curJob; if (curJob.haulMode == HaulMode.ToCellStorage) { Thing thing = curJob.GetTarget(TargetIndex.A).Thing; if (!actor.jobs.curJob.GetTarget(TargetIndex.B).Cell.IsValidStorageFor(base.Map, thing)) { return(true); } } return(false); }); yield return(new Toil { initAction = delegate() { ZLogger.Message("JobDriver_HaulThingToDestAndToCell 1: " + pawn + " trying to reserve: " + TargetA, true); } }); yield return(reserveTargetA); yield return(toilGoto); yield return(new Toil { initAction = delegate() { this.savedThing = TargetA.Thing; } }); yield return(Toils_Haul.StartCarryThing(TargetIndex.A, putRemainderInQueue: false, subtractNumTakenFromJobCount: true)); if (job.haulOpportunisticDuplicates) { yield return(new Toil { initAction = delegate() { ZLogger.Message("JobDriver_HaulThingToDestAndToCell 2: " + pawn + " trying to reserve other things: " + TargetA, true); } }); yield return(Toils_Haul.CheckForGetOpportunityDuplicate(reserveTargetA, TargetIndex.A, TargetIndex.B)); } ZLogger.Message($"JobDriver HaulThingToDestAndCell2 About to call findRouteWithStairs, with pawn {GetActor()}, dest {ZTracker.jobTracker[pawn].targetDest}, instance {this}"); Log.Message("2 - pawn.Map: " + pawn.Map + " - dest: " + ZTracker.jobTracker[pawn].targetDest.Map, true); foreach (var toil in Toils_ZLevels.GoToMap(GetActor(), ZTracker.jobTracker[pawn].targetDest.Map, this)) { yield return(toil); } Toil carryToCell = Toils_Haul.CarryHauledThingToCell(TargetIndex.B); yield return(carryToCell); yield return(new Toil { initAction = delegate() { if (TargetB.Cell.GetFirstItem(pawn.Map) != null) { IntVec3 newPosition = IntVec3.Invalid; IntVec3 center = (from x in GenRadial.RadialCellsAround(pawn.Position, 3f, useCenter: true) where x.InBounds(pawn.Map) && x.GetFirstItem(pawn.Map) == null select x).FirstOrDefault(); if (center != null) { job.targetB = new LocalTargetInfo(center); } else if (CellFinder.TryFindRandomCellNear(TargetB.Cell, pawn.Map, 3, (IntVec3 c) => c.GetFirstItem(pawn.Map)?.def != TargetA.Thing.def, out newPosition)) { job.targetB = new LocalTargetInfo(newPosition); } } } }); yield return(Toils_Haul.PlaceHauledThingInCell(TargetIndex.B, carryToCell, false)); }
private static void Main() { Rise.InitializeNoGraphic(new ServerPlatform()); Directory.CreateDirectory(Game.GetSaveFolder()); Ressources.Load(); REGISTRY.Initialize(); Console.WriteLine("\n"); while (true) { Console.WriteLine($"{Game.Name} Server v{Game.Version}\n"); var saves = Directory.GetDirectories(Game.GetSaveFolder()); for (int i = 0; i < saves.Length; i++) { Console.WriteLine($"{i}: {saves[i]}"); } Console.WriteLine(); Console.WriteLine("0-99: load world."); Console.WriteLine(" n: new world."); Console.WriteLine(" d: delete world."); Console.Write("\n> "); string input = Console.ReadLine(); if (input.ToLower() == "n") { Console.WriteLine(); Console.Write("World name: "); var worldName = Console.ReadLine(); Console.Write("World seed: "); var worldSeed = Console.ReadLine(); int seed = 0; if (!int.TryParse(worldSeed, out seed)) { seed = worldSeed.GetHashCode(); } GameState gameState = (GameState)Jobs.GenerateWorld .SetArguments(new Jobs.WorldGeneratorInfo(Game.GetSaveFolder() + worldName, seed, GENERATOR.DEFAULT)) .Start(false) .Result; gameState.Initialize(); var repport = Job.NewEmpty("SaveWorld"); repport.StatusChanged += (sender, e) => { Console.WriteLine(e); }; Jobs.SaveWorld .SetArguments(new Jobs.WorldSaveInfo(Game.GetSaveFolder() + worldName, gameState)) .Start(false); } else if (int.TryParse(input, out var levelindex)) { } Console.Clear(); } }
public static void process_map_employee_contract_data( IObjectSpace objectSpace, DataTable employeeContractDataTable, out List <EmployeeContract> mapResult) { var employees = objectSpace.GetObjects <Employee>(); var contractTypes = objectSpace.GetObjects <ContractType>(); var designations = objectSpace.GetObjects <Designation>(); var jobs = objectSpace.GetObjects <Job>(); Employee employee = null; ContractType contractType = null; Designation designation = null; Employee signPerson = null; Job job = null; string empID = string.Empty; string contractTypeName = string.Empty; string designationName = string.Empty; string signPersonID = string.Empty; string jobName = string.Empty; mapResult = new List <EmployeeContract>(); foreach (DataRow row in employeeContractDataTable.Rows) { if (empID != row["EmpID"]?.ToString()) { empID = row["EmpID"]?.ToString(); employee = employees .Where(item => item.Code == empID) .FirstOrDefault(); } if (contractTypeName != row["Type"]?.ToString()) { contractTypeName = row["Type"]?.ToString(); contractType = contractTypes .Where(item => item.Name.ToUpper() == contractTypeName.ToUpper()) .FirstOrDefault(); } if (designationName != row["Designation"]?.ToString()) { designationName = row["Designation"]?.ToString(); designation = designations .Where(item => item.Name.ToUpper() == designationName.ToUpper()) .FirstOrDefault(); } if (signPersonID != row["CompanySignPerson"]?.ToString()) { signPersonID = row["CompanySignPerson"]?.ToString(); signPerson = employees .Where(item => item.Code == signPersonID) .FirstOrDefault(); } if (jobName != row["Job"]?.ToString()) { jobName = row["Job"]?.ToString(); job = jobs .Where(item => item.Name.ToUpper() == jobName.ToUpper()) .FirstOrDefault(); } if (employee != null) { var contract = objectSpace.CreateObject <EmployeeContract>(); contract.SetMemberValue("ContractNumber", row["ContractNumber"]?.ToString()); contract.SetMemberValue("Employee", employee); contract.SetMemberValue("Type", contractType); contract.SetMemberValue("Designation", designation); contract.SetMemberValue("CompanySignPerson", signPerson); contract.SetMemberValue("Job", job); contract.SetMemberValue("BaseSalary", row["BaseSalary"]); contract.SetMemberValue("InsurranceSalary", row["InsurranceSalary"]); contract.SetMemberValue("SignedDate", row["SignedDate"]); contract.SetMemberValue("ValidFromDate", row["ValidFromDate"]); mapResult.Add(contract); } } }
public void T06_InvalidJobCategory() { UnityEngine.TestTools.LogAssert.Expect(UnityEngine.LogType.Error, "Invalid tile detected. If this wasn't a test, you have an issue."); UnityEngine.TestTools.LogAssert.Expect(UnityEngine.LogType.Error, "Invalid category detected."); Job job = ((Deconstruct)badOrderAction).CreateJob(null, "test"); }
public override IResult <object> Action(Job job, IJobCancellationToken cancelationToken) => Do <object> .Try((r) => { var func = _actionExpression.Compile(); return(func(job)); }) .Result;
public void ReturnExceptionWhenUserIDisInvalidOnMarkJobAsDoneTest() { IMateDAO <Mate> MateDAO = new MateDAO(_connection); Mate testMate = new Mate(); testMate.FirstName = "Miguel"; testMate.LastName = "Dev"; testMate.UserName = "******"; testMate.Password = "******"; testMate.Email = "*****@*****.**"; testMate.Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."; testMate.Address = "Figueiró"; testMate.Categories = new[] { Categories.CLEANING, Categories.PLUMBING }; testMate.Rank = Ranks.SUPER_MATE; testMate.Range = 20; Mate returned = MateDAO.Create(testMate); IEmployerDAO <Employer> EmployerDAO = new EmployerDAO(_connection); Employer testEmployer = new Employer(); testEmployer.FirstName = "Marcelo"; testEmployer.LastName = "Carvalho"; testEmployer.UserName = "******"; testEmployer.Password = "******"; testEmployer.Email = "*****@*****.**"; testEmployer.Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."; testEmployer.Address = "Lixa"; Employer returnedEmp = EmployerDAO.Create(testEmployer); IJobDAO jobPostDAO = new JobDAO(_connection); JobPost testPost = new JobPost(); testPost.Title = "Canalização Estourada"; testPost.Category = Categories.PLUMBING; testPost.ImagePath = "path/image"; testPost.Description = "Grande estouro nos canos da sanita"; testPost.Tradable = true; testPost.InitialPrice = 60.6; testPost.Address = "Rua sem fim"; testPost.PaymentMethod = new[] { Payment.PAYPAL, Payment.MONEY }; JobPost jobReturned = jobPostDAO.Create(returnedEmp.Id, testPost); DateTime date = new DateTime(2020, 01, 16); Job job = new Job(); job.Date = date; job.Mate = returned.Id; job.JobPost = jobReturned.Id; job.FinishedConfirmedByEmployer = false; job.FinishedConfirmedByMate = false; job.Employer = returnedEmp.Id; IWorkDAO workDAO = new WorkDAO(_connection); Job returnedJob = workDAO.Create(returnedEmp.Id, job); Assert.Throws <Exception>(() => workDAO.MarkJobAsDone(returnedJob.Id, 10000)); _fixture.Dispose(); }
public Task NavigateTo_JobDetailPrestador(Job itemSelected, Client user) { return(Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new JobDetalhe_Prestador(itemSelected, user))); }
public IActionResult UpdateJob([FromBody] Job updatedJob) { _jobRepository.UpdateJob(updatedJob); return(Ok(updatedJob)); }
internal MonCDebuggerVMTool(Job job, IVMInput input) : base(job, input) { }
/// <summary> /// Run the sample async. /// </summary> /// <param name="config">The parm is of type ConfigWrapper. This class reads values from local configuration file.</param> /// <returns></returns> // <RunAsync> private static async Task RunAsync(ConfigWrapper config) { IAzureMediaServicesClient client = await CreateMediaServicesClientAsync(config); // Set the polling interval for long running operations to 2 seconds. // The default value is 30 seconds for the .NET client SDK client.LongRunningOperationRetryTimeout = 2; // Creating a unique suffix so that we don't have name collisions if you run the sample // multiple times without cleaning up. string uniqueness = Guid.NewGuid().ToString("N"); string jobName = $"job-{uniqueness}"; string locatorName = $"locator-{uniqueness}"; string outputAssetName = $"output-{uniqueness}"; // Ensure that you have the desired encoding Transform. This is really a one time setup operation. Transform transform = await GetOrCreateTransformAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName); // Output from the encoding Job must be written to an Asset, so let's create one Asset outputAsset = await CreateOutputAssetAsync(client, config.ResourceGroup, config.AccountName, outputAssetName); Job job = await SubmitJobAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, outputAsset.Name, jobName); // In this demo code, we will poll for Job status // Polling is not a recommended best practice for production applications because of the latency it introduces. // Overuse of this API may trigger throttling. Developers should instead use Event Grid. job = await WaitForJobToFinishAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, jobName); if (job.State == JobState.Finished) { // Set a token signing key that you want to use TokenSigningKey = Convert.FromBase64String(config.SymmetricKey); // Create the content key policy that configures how the content key is delivered to end clients // via the Key Delivery component of Azure Media Services. // We are using the ContentKeyIdentifierClaim in the ContentKeyPolicy which means that the token presented // to the Key Delivery Component must have the identifier of the content key in it. ContentKeyPolicy policy = await GetOrCreateContentKeyPolicyAsync(client, config.ResourceGroup, config.AccountName, ContentKeyPolicyName, TokenSigningKey); StreamingLocator locator = await CreateStreamingLocatorAsync(client, config.ResourceGroup, config.AccountName, outputAsset.Name, locatorName, ContentKeyPolicyName); // In this example, we want to play the PlayReady (CENC) encrypted stream. // We need to get the key identifier of the content key where its type is CommonEncryptionCenc. string keyIdentifier = locator.ContentKeys.Where(k => k.Type == StreamingLocatorContentKeyType.CommonEncryptionCenc).First().Id.ToString(); Console.WriteLine($"KeyIdentifier = {keyIdentifier}"); // In order to generate our test token we must get the ContentKeyId to put in the ContentKeyIdentifierClaim claim. string token = GetTokenAsync(Issuer, Audience, keyIdentifier, TokenSigningKey); string dashPath = await GetDASHStreamingUrlAsync(client, config.ResourceGroup, config.AccountName, locator.Name); Console.WriteLine("Copy and paste the following URL in your browser to play back the file in the Azure Media Player."); Console.WriteLine("You can use Edge/IE11 for PlayReady and Chrome/Firefox for Widevine."); Console.WriteLine(); Console.WriteLine($"https://ampdemo.azureedge.net/?url={dashPath}&playready=true&widevine=true&token=Bearer%3D{token}"); Console.WriteLine(); } Console.WriteLine("When finished testing press enter to cleanup."); Console.Out.Flush(); Console.ReadLine(); Console.WriteLine("Cleaning up..."); await CleanUpAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, job.Name, new List <string> { outputAsset.Name }, ContentKeyPolicyName); }
public void Change(Job job) { throw new Exception("You can't change state when the Job is Completed"); }
public Task NavigateTo_JobDetail(Job j) { return(Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new JobDetalhe(j))); }
[TestMethod()] public void TestLoadAndSaveJob() { ModelContext.beginTrans(); try { OracleMappers.JobDBMapper pdb = new OracleMappers.JobDBMapper(); long count = pdb.RecordCount(); if (pdb.SelectFromObjectName != pdb.ManagedTableName) { long countFromSelectObject = pdb.dbConn.getLngValue("select count(*) from " + pdb.SelectFromObjectName); Assert.AreEqual(count, countFromSelectObject, "Count of records in managedTableName {0} and SelectFromObjectName {1} should be equal, as there needs to be exactly 1 to 1 match between records in managed table and selectFromObject.", pdb.ManagedTableName, pdb.SelectFromObjectName); } if (count == 0) { Assert.Inconclusive("No Job in database, table is empty"); } else { /** * using (DataContext ctx = DBUtils.Current().dbContext()) { * * var query = ctx.ExecuteQuery<Job>(@"SELECT * FROM " + pdb.SelectFromObjectName ).Skip(1).Take(1); * var lst = query.ToList(); * * Assert.AreEqual(lst.Count, 1, "Expected to receive 1 record, got: " + lst.Count); * * } * todo: fix boolean fields by generating properties of original fields **/ object pid = ModelContext.CurrentDBUtils.getObjectValue("select top 1 " + pdb.pkFieldName + " from " + pdb.ManagedTableName); Job p = pdb.findByKey(pid); Job p2 = (Job)p.copy(); //Test equality and hash codes Assert.AreEqual(p.GetHashCode(), p2.GetHashCode()); Assert.AreEqual(p, p2); p.isDirty = true; // force save pdb.save(p); // now reload object from database p = null; p = pdb.findByKey(pid); //test fields to be equal before and after save Assert.IsTrue(p.PrJobId == p2.PrJobId, "Expected Field JobId to be equal"); Assert.IsTrue(p.PrJobTitle == p2.PrJobTitle, "Expected Field JobTitle to be equal"); Assert.IsTrue(p.PrMinSalary.GetValueOrDefault() == p2.PrMinSalary.GetValueOrDefault(), "Expected Field MinSalary to be equal"); Assert.IsTrue(p.PrMaxSalary.GetValueOrDefault() == p2.PrMaxSalary.GetValueOrDefault(), "Expected Field MaxSalary to be equal"); Assert.IsTrue(p.CreateDate.GetValueOrDefault().ToString("MM/dd/yy H:mm:ss zzz") == p2.CreateDate.GetValueOrDefault().ToString("MM/dd/yy H:mm:ss zzz"), "Expected Field CreateDate to be equal"); Assert.IsFalse(p.UpdateDate.GetValueOrDefault() == p2.UpdateDate.GetValueOrDefault(), "Expected Field UpdateDate NOT to be equal"); Assert.IsTrue(p.CreateUser == p2.CreateUser, "Expected Field CreateUser to be equal"); //skip update user! p.isDirty = true; //to force save ModelContext.Current.saveModelObject(p); p = ModelContext.Current.loadModelObject <Job>(p.Id); p.loadObjectHierarchy(); string json = JsonConvert.SerializeObject(p, Formatting.Indented, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); System.IO.FileInfo jf = new System.IO.FileInfo(".\\Job.json"); System.IO.File.WriteAllText(jf.FullName, json); if (pdb.isPrimaryKeyAutogenerated) { p.isNew = true; p.isDirty = true; try { pdb.save(p); } catch (System.Exception e) { Assert.IsTrue(e.Message.ToUpper().Contains("UNIQUE INDEX") || e.Message.Contains("Violation of UNIQUE KEY constraint"), "Insert statement produced error other than violation of unique key:" + e.Message); } } } } finally { ModelContext.rollbackTrans(); // 'Nothing should be saved to the database! } }
protected MonCVMTool(Job job, IVMInput input) { _job = job; _input = input; }
private XmlResource CreateUpdatedResource(Enums.ResourceType resourceType, string id, string fieldAlias, string fieldValue) { XmlResource result = null; switch (resourceType) { case Enums.ResourceType.Client: result = new Client() { Id = id }; result.DictionaryValues[fieldAlias] = fieldValue; break; case Enums.ResourceType.Activity: result = new Activity() { Id = id }; result.DictionaryValues[fieldAlias] = fieldValue; break; case Enums.ResourceType.Sales: result = new Sales() { Id = id }; result.DictionaryValues[fieldAlias] = fieldValue; break; case Enums.ResourceType.Contract: result = new Contract() { Id = id }; result.DictionaryValues[fieldAlias] = fieldValue; break; case Enums.ResourceType.Process: result = new Process() { Id = id }; result.DictionaryValues[fieldAlias] = fieldValue; break; case Enums.ResourceType.Job: result = new Job() { Id = id }; result.DictionaryValues[fieldAlias] = fieldValue; break; case Enums.ResourceType.Recruiter: result = new Recruiter() { Id = id }; result.DictionaryValues[fieldAlias] = fieldValue; break; case Enums.ResourceType.Resume: result = new Resume() { Id = id }; result.DictionaryValues[fieldAlias] = fieldValue; break; case Enums.ResourceType.Candidate: result = new Candidate() { Id = id }; result.DictionaryValues[fieldAlias] = fieldValue; break; } return(result); }
private void InitializeJob() { Job = new Job(); Job.Client = (Client)AppVM.Instace.Person; }
public void DoBuild(Tile t) { if (buildMode == BuildMode.FURNITURE) { // Create the Furniture and assign it to the tile // FIXME: This instantly builds the furnite: //WorldController.Instance.World.PlaceFurniture( buildModeObjectType, t ); // Can we build the furniture in the selected tile? // Run the ValidPlacement function! string furnitureType = buildModeObjectType; if ( WorldController.Instance.world.IsFurniturePlacementValid(furnitureType, t) && t.pendingFurnitureJob == null ) { // This tile position is valid for this furniture // Create a job for it to be build Job j; if (WorldController.Instance.world.furnitureJobPrototypes.ContainsKey(furnitureType)) { // Make a clone of the job prototype j = WorldController.Instance.world.furnitureJobPrototypes[furnitureType].Clone(); // Assign the correct tile. j.tile = t; } else { Debug.LogError("There is no furniture job prototype for '" + furnitureType + "'"); j = new Job(t, furnitureType, FurnitureActions.JobComplete_FurnitureBuilding, 0.1f, null); } j.furniturePrototype = WorldController.Instance.world.furniturePrototypes[furnitureType]; // FIXME: I don't like having to manually and explicitly set // flags that preven conflicts. It's too easy to forget to set/clear them! t.pendingFurnitureJob = j; j.RegisterJobStoppedCallback((theJob) => { theJob.tile.pendingFurnitureJob = null; }); // Add the job to the queue WorldController.Instance.world.jobQueue.Enqueue(j); } } else if (buildMode == BuildMode.FLOOR) { // We are in tile-changing mode. t.Type = buildModeTile; } else if (buildMode == BuildMode.DECONSTRUCT) { // TODO if (t.furniture != null) { t.furniture.Deconstruct(); } } else { Debug.LogError("UNIMPLMENTED BUILD MODE"); } }
// Decompiled code is painful to read... Continue at your own risk public static List <FloatMenuOption> ChoicesForThing(Thing thing, Pawn pawn) { List <FloatMenuOption> opts = new List <FloatMenuOption>(); Thing t = thing; // Copied from FloatMenuMakerMap.AddHumanlikeOrders if (t.def.ingestible != null && pawn.RaceProps.CanEverEat(t) && t.IngestibleNow) { string text; if (t.def.ingestible.ingestCommandString.NullOrEmpty()) { text = "ConsumeThing".Translate(new NamedArgument[] { t.LabelShort }); } else { text = string.Format(t.def.ingestible.ingestCommandString, t.LabelShort); } if (!t.IsSociallyProper(pawn)) { text = text + " (" + "ReservedForPrisoners".Translate() + ")"; } FloatMenuOption item7; if (t.def.IsNonMedicalDrug && pawn.IsTeetotaler()) { item7 = new FloatMenuOption(text + " (" + TraitDefOf.DrugDesire.DataAtDegree(-1).label + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); } else if (!pawn.CanReach(t, PathEndMode.OnCell, Danger.Deadly, false, TraverseMode.ByPawn)) { item7 = new FloatMenuOption(text + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); } else { MenuOptionPriority priority2 = (!(t is Corpse)) ? MenuOptionPriority.Default : MenuOptionPriority.Low; item7 = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text, delegate() { t.SetForbidden(false, true); Job job = new Job(JobDefOf.Ingest, t); job.count = FoodUtility.WillIngestStackCountOf(pawn, t.def, t.GetStatValue(StatDefOf.Nutrition, true)); pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); }, priority2, null, null, 0f, null, null), pawn, t, "ReservedBy"); } opts.Add(item7); } // Add equipment commands // Copied from FloatMenuMakerMap.AddHumanlikeOrders if (thing is ThingWithComps equipment && equipment.GetComp <CompEquippable>() != null) { string labelShort = equipment.LabelShort; FloatMenuOption item4; if (equipment.def.IsWeapon && pawn.WorkTagIsDisabled(WorkTags.Violent)) { item4 = new FloatMenuOption("CannotEquip".Translate(new NamedArgument[] { labelShort }) + " (" + "IsIncapableOfViolenceLower".Translate(new NamedArgument[] { pawn.LabelShort }) + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); } else if (!pawn.CanReach(equipment, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) { item4 = new FloatMenuOption("CannotEquip".Translate(new NamedArgument[] { labelShort }) + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); } else if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation)) { item4 = new FloatMenuOption("CannotEquip".Translate(new NamedArgument[] { labelShort }) + " (" + "Incapable".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); } else { string text5 = "Equip".Translate(new NamedArgument[] { labelShort }); if (equipment.def.IsRangedWeapon && pawn.story != null && pawn.story.traits.HasTrait(TraitDefOf.Brawler)) { text5 = text5 + " " + "EquipWarningBrawler".Translate(); } item4 = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(text5, delegate() { equipment.SetForbidden(false, true); pawn.jobs.TryTakeOrderedJob(new Job(JobDefOf.Equip, equipment), JobTag.Misc); MoteMaker.MakeStaticMote(equipment.DrawPos, equipment.Map, ThingDefOf.Mote_FeedbackEquip, 1f); PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.EquippingWeapons, KnowledgeAmount.Total); }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, equipment, "ReservedBy"); } opts.Add(item4); } // Add clothing commands Apparel apparel = thing as Apparel; if (apparel != null) { FloatMenuOption item5; if (!pawn.CanReach(apparel, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) { item5 = new FloatMenuOption("CannotWear".Translate(new NamedArgument[] { apparel.Label }) + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); } else if (!ApparelUtility.HasPartsToWear(pawn, apparel.def)) { item5 = new FloatMenuOption("CannotWear".Translate(new NamedArgument[] { apparel.Label }) + " (" + "CannotWearBecauseOfMissingBodyParts".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null); } else { item5 = FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("ForceWear".Translate(new NamedArgument[] { apparel.LabelShort }), delegate() { apparel.SetForbidden(false, true); Job job = new Job(JobDefOf.Wear, apparel); pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, apparel, "ReservedBy"); } opts.Add(item5); } // Add caravan commands if (pawn.IsFormingCaravan()) { if (thing != null && thing.def.EverHaulable) { Pawn packTarget = GiveToPackAnimalUtility.UsablePackAnimalWithTheMostFreeSpace(pawn) ?? pawn; JobDef jobDef = (packTarget != pawn) ? JobDefOf.GiveToPackAnimal : JobDefOf.TakeInventory; if (!pawn.CanReach(thing, PathEndMode.ClosestTouch, Danger.Deadly, false, TraverseMode.ByPawn)) { opts.Add(new FloatMenuOption("CannotLoadIntoCaravan".Translate(new NamedArgument[] { thing.Label }) + " (" + "NoPath".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); } else if (MassUtility.WillBeOverEncumberedAfterPickingUp(packTarget, thing, 1)) { opts.Add(new FloatMenuOption("CannotLoadIntoCaravan".Translate(new NamedArgument[] { thing.Label }) + " (" + "TooHeavy".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); } else { LordJob_FormAndSendCaravan lordJob = (LordJob_FormAndSendCaravan)pawn.GetLord().LordJob; float capacityLeft = CaravanFormingUtility.CapacityLeft(lordJob); if (thing.stackCount == 1) { float capacityLeft4 = capacityLeft - thing.GetStatValue(StatDefOf.Mass, true); opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(CaravanFormingUtility.AppendOverweightInfo("LoadIntoCaravan".Translate(new NamedArgument[] { thing.Label }), capacityLeft4), delegate() { thing.SetForbidden(false, false); Job job = new Job(jobDef, thing); job.count = 1; job.checkEncumbrance = (packTarget == pawn); pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, thing, "ReservedBy")); } else { if (MassUtility.WillBeOverEncumberedAfterPickingUp(packTarget, thing, thing.stackCount)) { opts.Add(new FloatMenuOption("CannotLoadIntoCaravanAll".Translate(new NamedArgument[] { thing.Label }) + " (" + "TooHeavy".Translate() + ")", null, MenuOptionPriority.Default, null, null, 0f, null, null)); } else { float capacityLeft2 = capacityLeft - (float)thing.stackCount * thing.GetStatValue(StatDefOf.Mass, true); opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption(CaravanFormingUtility.AppendOverweightInfo("LoadIntoCaravanAll".Translate(new NamedArgument[] { thing.Label }), capacityLeft2), delegate() { thing.SetForbidden(false, false); Job job = new Job(jobDef, thing); job.count = thing.stackCount; job.checkEncumbrance = (packTarget == pawn); pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, thing, "ReservedBy")); } opts.Add(FloatMenuUtility.DecoratePrioritizedTask(new FloatMenuOption("LoadIntoCaravanSome".Translate(new NamedArgument[] { thing.LabelNoCount }), delegate() { int to = Mathf.Min(MassUtility.CountToPickUpUntilOverEncumbered(packTarget, thing), thing.stackCount); Dialog_Slider window = new Dialog_Slider(delegate(int val) { float capacityLeft3 = capacityLeft - (float)val * thing.GetStatValue(StatDefOf.Mass, true); return(CaravanFormingUtility.AppendOverweightInfo(string.Format("LoadIntoCaravanCount".Translate(new NamedArgument[] { thing.LabelNoCount }), val), capacityLeft3)); }, 1, to, delegate(int count) { thing.SetForbidden(false, false); Job job = new Job(jobDef, thing); job.count = count; job.checkEncumbrance = (packTarget == pawn); pawn.jobs.TryTakeOrderedJob(job, JobTag.Misc); }, int.MinValue); Find.WindowStack.Add(window); }, MenuOptionPriority.High, null, null, 0f, null, null), pawn, thing, "ReservedBy")); } } } } if (opts.Count == 0) { opts.Add(new FloatMenuOption("NoneBrackets".Translate(), null) { Disabled = true }); } return(opts); }
public void Clone(Job job) => Nav.NavigateTo($"jobs/clone/{job.Id}");
public static void Execute(Job job, Agent implant) { Task task = job.Task; RemoveArguments args = JsonConvert.DeserializeObject <RemoveArguments>(task.parameters); string path = args.path; if (!string.IsNullOrEmpty(args.host)) { path = $"\\\\{args.host}\\{path.Replace(":", "$")}"; } ApolloTaskResponse resp; switch (job.Task.command) { case "rm": try { FileInfo finfo = new FileInfo(path); string hash = FileUtils.GetFileMD5(finfo.FullName); System.IO.File.Delete(path); task.completed = true; resp = new ApolloTaskResponse(task, $"Successfully deleted file \"{path}\""); resp.removed_files = new Mythic.Structs.RemovedFileInformation[] { new Mythic.Structs.RemovedFileInformation() { host = args.host, path = finfo.FullName }, }; resp.artifacts = new Mythic.Structs.Artifact[] { new Mythic.Structs.Artifact() { artifact = $"{finfo.FullName} (MD5: {hash})", base_artifact = "File Delete" } }; job.SetComplete(resp); } catch (Exception e) { job.SetError($"Error removing file \"{path}\": {e.Message}"); } break; case "rmdir": try { DirectoryInfo dirinfo = new DirectoryInfo(path); System.IO.Directory.Delete(path); task.completed = true; resp = new ApolloTaskResponse(task, $"Successfully deleted file \"{path}\""); resp.removed_files = new Mythic.Structs.RemovedFileInformation[] { new Mythic.Structs.RemovedFileInformation() { host = args.host, path = dirinfo.FullName } }; resp.artifacts = new Mythic.Structs.Artifact[] { new Mythic.Structs.Artifact() { artifact = $"{dirinfo.FullName}", base_artifact = "Directory Delete" } }; job.SetComplete(resp); } catch (Exception ex) { job.SetError($"Error deleting file \"{path}\". Reason: {ex.Message}"); } break; default: job.SetError("Unsupported code path reached in Remove.cs"); break; } }
public Task <int> DeleteJobAsync(Job job) { return(_database.DeleteAsync(job)); }
private void SelectJob(Job job) { Nav.NavigateTo($"job/{job.Id}"); }
static bool Prefix(ref JobGiver_Manhunter __instance, ref Job __result, ref Pawn pawn) { //Log.Warning("Detected Animal Attack"); bool hasRangedVerb = false; //Log.Warning("Trying to fire at pawn"); List <Verb> verbList = pawn.verbTracker.AllVerbs; //Log.Warning("Got list of verb"); List <Verb> rangeList = new List <Verb>(); for (int i = 0; i < verbList.Count; i++) { //Log.Warning("Checkity"); //It corresponds with verbs anyway if (verbList[i].verbProps.range > 1.1f) { rangeList.Add(verbList[i]); hasRangedVerb = true; } //Log.Warning("Added Ranged Verb"); } //Log.Warning("got list of ranged verb"); //If there is no ranged verb just return; if (hasRangedVerb == false) { return(true); } Verb rangeVerb = rangeList.RandomElementByWeight((Verb rangeItem) => rangeItem.verbProps.commonality); if (rangeVerb == null) { Log.Warning("Can't get random range verb"); return(true); } //Log.Warning("Range verb detected"); Thing target = (Thing)ARA_AttackTargetFinder.BestAttackTarget((IAttackTargetSearcher)pawn, TargetScanFlags.NeedThreat | TargetScanFlags.NeedReachable, (Predicate <Thing>)(x => x is Pawn || x is Building), 0.0f, 9999, new IntVec3(), float.MaxValue, false); //Seek thing hiding in embrasure. if (target == null) { target = (Thing)ARA_AttackTargetFinder.BestAttackTarget((IAttackTargetSearcher)pawn, TargetScanFlags.NeedThreat, (Predicate <Thing>)(x => x is Pawn || x is Building), 0.0f, 9999, new IntVec3(), float.MaxValue, false); } //Use normal manhunter //Can't check for target if it doesn't exist duh //Log.Warning("CurrentEffectiveVerb " + pawn.CurrentEffectiveVerb); /* * Log.Warning("Effective Range " + pawn.CurrentEffectiveVerb.verbProps.range); * if (!pawn.CurrentEffectiveVerb.verbProps.MeleeRange) * { * Log.Warning("Not melee range"); * } */ bool targetInSight = false; Thing shootable = null; if (target == null) { shootable = (Thing)ARA_AttackTargetFinder.BestShootTargetFromCurrentPosition(pawn, (Predicate <Thing>)(x => x is Pawn || x is Building), rangeVerb.verbProps.range, rangeVerb.verbProps.minRange, TargetScanFlags.NeedThreat | TargetScanFlags.NeedLOSToPawns | TargetScanFlags.LOSBlockableByGas); //Log.Warning("Shootable found, " + shootable); if (shootable == null) { //Log.Warning("No target in line of site"); return(true); } targetInSight = true; } else if (target.Position.DistanceTo(pawn.Position) < rangeVerb.verbProps.minRange || target.Position.AdjacentTo8Way(pawn.Position)) { //Log.Warning("Target too close, melee!"); //Core code can't handle animal anymore if (pawn.CanReach(target, PathEndMode.Touch, Danger.Deadly, false)) { //Log.Warning("Melee Attack"); __result = new Job(JobDefOf.AttackMelee, target) { maxNumMeleeAttacks = 1, expiryInterval = Rand.Range(420, 900), attackDoorIfTargetLost = false }; return(false); } else { return(true); } } //Log.Warning("Got target"); //Formally range attack job //if (target != null && pawn.CanReach(target, PathEndMode.Touch, Danger.Deadly, false)) //Log.Warning("Ranged verb selected, range of " + verb.verbProps.range); IntVec3 intVec; //Log.Warning("Trying to shoot"); //Searches for target within range again. if (!targetInSight) { //Log.Warning("No target"); shootable = (Thing)ARA_AttackTargetFinder.BestShootTargetFromCurrentPosition(pawn, (Predicate <Thing>)(x => x is Pawn || x is Building), rangeVerb.verbProps.range, rangeVerb.verbProps.minRange, TargetScanFlags.NeedThreat | TargetScanFlags.NeedLOSToPawns | TargetScanFlags.LOSBlockableByGas); } if (shootable != null) { //Log.Warning("Got Shootable"); if (target.Position.DistanceTo(pawn.Position) < rangeVerb.verbProps.minRange || target.Position.AdjacentTo8Way(pawn.Position)) { //Log.Warning("Target too close, melee!"); //Core code can't handle animal anymore if (pawn.CanReach(target, PathEndMode.Touch, Danger.Deadly, false)) { //Log.Warning("Melee Attack"); __result = new Job(JobDefOf.AttackMelee, target) { maxNumMeleeAttacks = 1, expiryInterval = Rand.Range(420, 900), attackDoorIfTargetLost = false }; return(false); } else { //Log.Warning("Target too close and I can't melee right away"); return(true); } } //Log.Warning("Trying initiate job"); __result = new Job(DefDatabase <JobDef> .GetNamed("AnimalRangeAttack"), shootable, JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange, true) { verbToUse = rangeVerb }; //Log.Warning("Succesfully created job"); return(false); } //Target is not null if (target != null) { //Can't shoot at target from current position. Find a new position bool canShootCondition = false; //Log.Warning("Try casting"); canShootCondition = CastPositionFinder.TryFindCastPosition(new CastPositionRequest { caster = pawn, target = target, verb = rangeVerb, maxRangeFromTarget = 9999, wantCoverFromTarget = false }, out intVec); if (!canShootCondition) { //Log.Warning("Can't find place to shoot at target"); return(true); } //Log.Warning("Going"); //Go to new destination //Protection againt not being able to find target. if (pawn.Position == intVec) { //Log.Warning(pawn + " already at position to shoot, but target not selected to shoot."); __result = new Job(JobDefOf.Wait, 100); return(false); } __result = new Job(JobDefOf.Goto, intVec) { expiryInterval = JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange, checkOverrideOnExpire = true }; return(false); } //Log.Warning("Hit end condition"); return(true); }
private void CollectIntermediateFiles(Job job) { job.IntermediatePdfFile = Directory.GetFiles(job.IntermediateFolder).Single(); }
public void GetJobIndex() { jobItem = jobToDisplay.jobs[SelectedIndex]; }
protected override void QueryTargetFile() { if (!Job.Profile.SkipPrintDialog) { Job.ApplyMetadata(); var w = new PrintJobWindow(); var model = new PrintJobViewModel(Job.JobInfo, Job.Profile); w.DataContext = model; if (TopMostHelper.ShowDialogTopMost(w, true) != true || model.PrintJobAction == PrintJobAction.Cancel) { Cancel = true; WorkflowStep = WorkflowStep.AbortedByUser; return; } if (model.PrintJobAction == PrintJobAction.ManagePrintJobs) { throw new ManagePrintJobsException(); } Job.Profile = model.SelectedProfile.Copy(); Job.ApplyMetadata(); if (model.PrintJobAction == PrintJobAction.EMail) { Job.SkipSaveFileDialog = true; Job.Profile.EmailClient.Enabled = true; Job.Profile.AutoSave.Enabled = false; Job.Profile.OpenViewer = false; } } if (Job.SkipSaveFileDialog) { ITempFolderProvider tempFolderProvider = JobInfoQueue.Instance; var sendFilesFolder = _pathSafe.Combine(tempFolderProvider.TempFolder, "Job" + Job.JobInfo.SourceFiles[0].JobId + "_SendFiles"); Directory.CreateDirectory(sendFilesFolder); var filePath = _pathSafe.Combine(sendFilesFolder, Job.ComposeOutputFilename()); filePath = FileUtil.Instance.EllipsisForTooLongPath(filePath); Job.OutputFilenameTemplate = filePath; } else { var saveFileDialog = new SaveFileDialog(); saveFileDialog.Title = _translator.GetTranslation("InteractiveWorkflow", "SelectDestination", "Select destination"); saveFileDialog.Filter = _translator.GetTranslation("InteractiveWorkflow", "PdfFile", "PDF file") + @" (*.pdf)|*.pdf"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "PdfA1bFile", "PDF/A-1b file") + @" (*.pdf)|*.pdf"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "PdfA2bFile", "PDF/A-2b file") + @" (*.pdf)|*.pdf"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "PdfXFile", "PDF/X file") + @" (*.pdf)|*.pdf"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "JpegFile", "JPEG file") + @" (*.jpg)|*.jpg;*.jpeg;"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "PngFile", "PNG file") + @" (*.png)|*.png;"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "TiffFile", "TIFF file") + @" (*.tif)|*.tif;*.tiff"; saveFileDialog.Filter += @"|" + _translator.GetTranslation("InteractiveWorkflow", "TextFile", "Text file") + @" (*.txt)|*.txt;"; saveFileDialog.FilterIndex = (int)Job.Profile.OutputFormat + 1; saveFileDialog.OverwritePrompt = true; if (Job.Profile.SaveDialog.SetDirectory) { var saveDirectory = FileUtil.Instance.MakeValidFolderName( Job.TokenReplacer.ReplaceTokens(Job.Profile.SaveDialog.Folder)); DirectoryHelper = new DirectoryHelper(saveDirectory); if (DirectoryHelper.CreateDirectory()) { saveFileDialog.RestoreDirectory = true; saveFileDialog.InitialDirectory = saveDirectory; Logger.Debug("Set directory in save file dialog: " + saveDirectory); } else { Logger.Warn( "Could not create directory for save file dialog. It will be opened with default save location."); } } Cancel = !LaunchSaveFileDialog(saveFileDialog); } }
public static NonEscapedString Render(Job job, int?maxArgumentToRenderSize) { if (job == null) { return(new NonEscapedString("<em>Can not find the target method.</em>")); } var builder = new StringBuilder(); builder.Append(WrapKeyword("using")); builder.Append(" "); builder.Append(Encode(job.Type.Namespace)); builder.Append(";"); builder.AppendLine(); builder.AppendLine(); string serviceName = null; if (!job.Method.IsStatic) { serviceName = GetNameWithoutGenericArity(job.Type); if (job.Type.GetTypeInfo().IsInterface&& serviceName[0] == 'I' && Char.IsUpper(serviceName[1])) { serviceName = serviceName.Substring(1); } serviceName = Char.ToLower(serviceName[0]) + serviceName.Substring(1); builder.Append(WrapKeyword("var")); builder.Append( $" {Encode(serviceName)} = Activate<{WrapType(Encode(job.Type.ToGenericTypeString()))}>();"); builder.AppendLine(); } if (job.Method.GetCustomAttribute <AsyncStateMachineAttribute>() != null) { builder.Append($"{WrapKeyword("await")} "); } builder.Append(!job.Method.IsStatic ? Encode(serviceName) : WrapType(Encode(job.Type.ToGenericTypeString()))); builder.Append("."); builder.Append(Encode(job.Method.Name)); if (job.Method.IsGenericMethod) { var genericArgumentTypes = job.Method.GetGenericArguments() .Select(x => WrapType(x.Name)) .ToArray(); builder.Append($"<{String.Join(", ", genericArgumentTypes)}>"); } builder.Append("("); var parameters = job.Method.GetParameters(); var renderedArguments = new List <string>(parameters.Length); var renderedArgumentsTotalLength = 0; const int splitStringMinLength = 100; for (var i = 0; i < parameters.Length; i++) { var parameter = parameters[i]; #pragma warning disable 618 if (i < job.Arguments.Length) { var argument = job.Arguments[i]; #pragma warning restore 618 if (maxArgumentToRenderSize != null && argument != null && argument.Length > maxArgumentToRenderSize) { renderedArguments.Add(Encode("<VALUE IS TOO BIG>")); continue; } string renderedArgument; var enumerableArgument = GetIEnumerableGenericArgument(parameter.ParameterType); object argumentValue; bool isJson = true; try { argumentValue = JobHelper.FromJson(argument, parameter.ParameterType); } catch (Exception) { // If argument value is not encoded as JSON (an old // way using TypeConverter), we should display it as is. argumentValue = argument; isJson = false; } if (enumerableArgument == null || argumentValue == null) { var argumentRenderer = ArgumentRenderer.GetRenderer(parameter.ParameterType); renderedArgument = argumentRenderer.Render(isJson, argumentValue?.ToString(), argument); } else { var renderedItems = new List <string>(); // ReSharper disable once LoopCanBeConvertedToQuery foreach (var item in (IEnumerable)argumentValue) { var argumentRenderer = ArgumentRenderer.GetRenderer(enumerableArgument); renderedItems.Add(argumentRenderer.Render(isJson, item?.ToString(), JobHelper.ToJson(item))); } // ReSharper disable once UseStringInterpolation renderedArgument = String.Format( "{0}{1} {{ {2} }}", WrapKeyword("new"), parameter.ParameterType.IsArray ? " []" : "", String.Join(", ", renderedItems)); } renderedArguments.Add(renderedArgument); renderedArgumentsTotalLength += renderedArgument.Length; } else { renderedArguments.Add(Encode("<NO VALUE>")); } } for (int i = 0; i < renderedArguments.Count; i++) { // TODO: be aware of out of range var parameter = parameters[i]; var tooltipPosition = "top"; var renderedArgument = renderedArguments[i]; if (renderedArgumentsTotalLength > splitStringMinLength) { builder.AppendLine(); builder.Append(" "); tooltipPosition = "left"; } else if (i > 0) { builder.Append(" "); } builder.Append($"<span title=\"{parameter.Name}\" data-placement=\"{tooltipPosition}\">"); builder.Append(renderedArgument); builder.Append("</span>"); if (i < renderedArguments.Count - 1) { builder.Append(","); } } builder.Append(");"); return(new NonEscapedString(builder.ToString())); }
static bool Prefix(ref JobGiver_AIFightEnemy __instance, ref Job __result, ref Pawn pawn) { //Log.Warning("Tame animal job detected"); if (!pawn.RaceProps.Animal) { return(true); } bool hasRangedVerb = false; List <Verb> verbList = pawn.verbTracker.AllVerbs; List <Verb> rangeList = new List <Verb>(); for (int i = 0; i < verbList.Count; i++) { //Log.Warning("Checkity"); //It corresponds with verbs anyway if (verbList[i].verbProps.range > 1.1f) { rangeList.Add(verbList[i]); hasRangedVerb = true; } //Log.Warning("Added Ranged Verb"); } if (hasRangedVerb == false) { //Log.Warning("I don't have range verb"); return(true); } // this.SetCurMeleeVerb(updatedAvailableVerbsList.RandomElementByWeight((VerbEntry ve) => ve.SelectionWeight).verb); Verb rangeVerb = rangeList.RandomElementByWeight((Verb rangeItem) => rangeItem.verbProps.commonality); if (rangeVerb == null) { //Log.Warning("Can't get random range verb"); return(true); } Thing enemyTarget = (Thing)AttackTargetFinder.BestAttackTarget((IAttackTargetSearcher)pawn, TargetScanFlags.NeedThreat, (Predicate <Thing>)(x => x is Pawn || x is Building), 0.0f, rangeVerb.verbProps.range, new IntVec3(), float.MaxValue, false); if (enemyTarget == null) { //Log.Warning("I can't find anything to fight."); return(true); } //Check if enemy directly next to pawn if (enemyTarget.Position.DistanceTo(pawn.Position) < rangeVerb.verbProps.minRange) { //If adjacent melee attack if (enemyTarget.Position.AdjacentTo8Way(pawn.Position)) { __result = new Job(JobDefOf.AttackMelee, enemyTarget) { maxNumMeleeAttacks = 1, expiryInterval = Rand.Range(420, 900), attackDoorIfTargetLost = false }; return(false); } //Only go if I am to be released. This prevent animal running off. if (pawn.CanReach(enemyTarget, PathEndMode.Touch, Danger.Deadly, false) && pawn.playerSettings.Master.playerSettings.animalsReleased) { //Log.Warning("Melee Attack"); __result = new Job(JobDefOf.AttackMelee, enemyTarget) { maxNumMeleeAttacks = 1, expiryInterval = Rand.Range(420, 900), attackDoorIfTargetLost = false }; return(false); } else { return(true); } } //Log.Warning("got list of ranged verb"); //Log.Warning("Attempting flag"); bool flag1 = (double)CoverUtility.CalculateOverallBlockChance(pawn.Position, enemyTarget.Position, pawn.Map) > 0.00999999977648258; bool flag2 = pawn.Position.Standable(pawn.Map); bool flag3 = rangeVerb.CanHitTarget(enemyTarget); bool flag4 = (pawn.Position - enemyTarget.Position).LengthHorizontalSquared < 25; if (flag1 && flag2 && flag3 || flag4 && flag3) { //Log.Warning("Shooting"); __result = new Job(DefDatabase <JobDef> .GetNamed("AnimalRangeAttack"), enemyTarget, JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange, true) { verbToUse = rangeVerb }; return(false); } IntVec3 dest; bool canShootCondition = false; //Log.Warning("Try casting"); //Animals with training seek cover /* * if (pawn.training.IsCompleted(TrainableDefOf.Release) && (double)verb.verbProps.range > 7.0) * Log.Warning("Attempting cover"); * Log.Warning("Try get flag radius :" + Traverse.Create(__instance).Method("GetFlagRadius", pawn).GetValue<float>()); * Log.Warning("Checking cast condition"); */ //Don't find new position if animal not released. canShootCondition = CastPositionFinder.TryFindCastPosition(new CastPositionRequest { caster = pawn, target = enemyTarget, verb = rangeVerb, maxRangeFromTarget = rangeVerb.verbProps.range, wantCoverFromTarget = pawn.training.HasLearned(TrainableDefOf.Release) && (double)rangeVerb.verbProps.range > 7.0, locus = pawn.playerSettings.Master.Position, maxRangeFromLocus = Traverse.Create(__instance).Method("GetFlagRadius", pawn).GetValue <float>(), maxRegions = 50 }, out dest); if (!canShootCondition) { //Log.Warning("I can't move to shooting position"); return(true); } if (dest == pawn.Position) { //Log.Warning("I will stay here and attack"); __result = new Job(DefDatabase <JobDef> .GetNamed("AnimalRangeAttack"), enemyTarget, JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange, true) { verbToUse = rangeVerb }; return(false); } //Log.Warning("Going to new place"); __result = new Job(JobDefOf.Goto, (LocalTargetInfo)dest) { expiryInterval = JobGiver_AIFightEnemy.ExpiryInterval_ShooterSucceeded.RandomInRange, checkOverrideOnExpire = true }; return(false); }