how to prevent another where chain from quering db again - ruby-on-rails-4

I have an object called work_shift_stops created with .where and after modified to limit start and end_time, with code below:
work_shift_stops = Stoppage20.where(["machine20_id = :machine20_id AND (end_time >= :start AND start <= :end_time)",
{ machine20_id: params[:shift_result][:machine20_id],
end_time: work_shift.end,
start: work_shift.first}])
work_shift_stops.each do |ws|
ws.start = work_shift.first if ws.start < work_shift.first
ws.end_time = work_shift.end if ws.end_time > work_shift.end
end
Further in my code I am using another where chain on the object:
load_time = open_time - work_shift_stops.where(stop20_id: Stop20.where(stop_group20_id: 3).pluck(:id)).sum(:duration)
This gives unpleasant result as rails is making another db query, which retrieves work_shift_stops with unmodified start and end_time limits:
SELECT SUM("stoppage20s"."duration") AS sum_id FROM "stoppage20s" WHERE (machine20_id = '1' AND (end_time >= '2013-03-02 05:00:00.000000' AND start <= '2013-03-02 17:00:00.000000')) AND "stoppage20s"."stop20_id" IN (12, 17)
Question is how to prevent rails from making another db query and use object with modified attributes?

What I actually did was dropping .sum(:duration) function and iterating on active record collection work_shift_stopswith modified start and end_time:
work_shift_stops.each do |wsd|
planned_stops_time += wsd.duration if Stop20.where(stop_group20_id: 3).pluck(:id).include? wsd.stop20_id
tech_stops_time += wsd.duration if Stop20.where(stop_group20_id: 1).pluck(:id).include? wsd.stop20_id
org_stops_time += wsd.duration if Stop20.where(stop_group20_id: 2).pluck(:id).include? wsd.stop20_id
end

Related

How to add value to matrix

I want to add value to matrix.
But, I could not do it.
I made the stepfunction for reinforcement learning and I calculated value which named R.
I want to gather R of value and add to matrix named RR.
However, all the calculated values are not added.
Is this because it's done inside a function? If it's not in a function, it works.
Please someone tell me the way to fix it.
% Define the step function
function [NextObservation, Reward, IsDone, LoggedSignals] =
myStepfunction(Action,LoggedSignals,SimplePendulum)
% get the pre statement
statePre = [-pi/2;0];
statePre(1) = SimplePendulum.Theta;
statePre(2) = SimplePendulum.AngularVelocity;
IsDone = false;
% updating states
SimplePendulum.pstep(Action);
% get the statement after updating
state = [-pi/2;0];
state(1) = SimplePendulum.Theta;
state(2) = SimplePendulum.AngularVelocity;
RR = [];
Ball_Target = 10;
Ball_Distance = Ballfunction(SimplePendulum);
R = -abs(Ball_Distance -Ball_Target); ← this the calculated value
RR = [RR,R]; ← I want to add R to RR
if (state(2) > 0) || (SimplePendulum.Y_Position < 0)
IsDone = true;
[InitialObservation, LoggedSignal] = myResetFunction(SimplePendulum);
LoggedSignal.State = [-pi/2 ; 0];
InitialObservation = LoggedSignal.State;
state = InitialObservation;
SimplePendulum.Theta =-pi/2;
SimplePendulum.AngularVelocity = 0;
end
LoggedSignals.State = state;
NextObservation = LoggedSignals.State;
Reward = +max(R);
end
If I understand you correctly, you are trying update RR with this function, and then use/see it outside the loop. This means you need to make two edits:
a) You need to pass RR in and out of the function to update it. You will need to change the first line of your code as shown here, but you will also need to change how you call the function:
function [NextObservation, Reward, IsDone, LoggedSignals, RR] =
myStepfunction(Action,LoggedSignals,SimplePendulum, RR)
b) When you do this RR = [] you delete the content of RR. To initialise RR you will need to move this line to the script that calls this function, making sure it is called before this function is ever called.

Lua Tween Part Info

I am making a tween that uses data given from a Humanoid.Seated event, and I wanted to make the camera go to the end point when sat down, however, move back after they sat up. I have a feeling that the problem is with the part info, however I could be wrong.
This is the code:
The Sender/Event Handler:
local camPart = script.Parent
local camEvent = game.ReplicatedStorage.CamEvent
local blueSeat = script.Parent.Parent.BlueSeat.Seat --the correct seat person should be in
local bluePlayerName = script.Parent.Parent.Buttons.BlueEnter.PlayerName --the supposed name of person
bluePlayerName:GetPropertyChangedSignal("Value"):Connect(function ()
if (bluePlayerName ~= "") then
local char = game.Workspace:FindFirstChild(bluePlayerName.Value, true)
local player = game.Players:GetPlayerFromCharacter(char)
char.Humanoid.Seated:Connect(function (isSeated, seat)
if (seat.Name == blueSeat.Name) then
camEvent:FireClient(player, camPart, isSeated) --go to tween handler
end
end)
end
end)
The Receiver/Tween Handler:
local TweenService = game:GetService("TweenService")
local cam = game.Workspace.Camera
local partData
local tween
local length = 2
local tweenData = TweenInfo.new(
length,
Enum.EasingStyle.Sine,
Enum.EasingDirection.Out,
0,
true,
0
)
script.Parent.OnClientEvent:Connect(function (camPart, isSeated) --receiver
partData = {
CFrame = camPart.CFrame
}
tween = TweenService:Create(cam, tweenData, partData)
if (isSeated == true) then
cam.CameraType = Enum.CameraType.Scriptable --remove control
tween:Play()
wait(length / 2)
tween:Pause() --stop at end point
elseif (isSeated == false) then
tween:Play() --go back/finish
wait(length / 2)
cam.CameraType = Enum.CameraType.Custom --give control back
end
end)
The fact that the RemoteEvent isn't firing at all should be an clue that the connection to the Humanoid.Seated event isn't being reached in the server Script. It's unclear from your code sample what would trigger the code in the first place, but it looks like you're just looking for when a player's character loads into the workspace.
I would recommend using the Player.CharacterAdded or Player.CharacterAppearanceLoaded events as ways of getting access to the player's Character and humanoid. You can still use your UI code as a trigger for whether to tween or not, but it might be easier.
-- Server Script
local camPart = script.Parent
local camEvent = game.ReplicatedStorage.CamEvent
local thing = script.Parent.Parent
local blueSeat = thing.BlueSeat.Seat --the correct seat person should be in
local bluePlayerName = thing.Buttons.BlueEnter.PlayerName --the supposed name of person
-- listen for when a player sits in a seat
game.Players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
character.Humanoid.Seated:Connect(function(isSeated, seat)
print("Player is seated?", isSeated)
if not isSeated then
-- tell the client to zoom out
camEvent:FireClient(player, camPart, isSeated)
else
-- decide whether to tween the camera
local isApprovedSeat = seat.Name == blueSeat.Name
local isNameSet = bluePlayerName.Value ~= ""
local shouldTweenCamera = isApprovedSeat and isNameSet
if shouldTweenCamera then
camEvent:FireClient(player, camPart, isSeated)
else
local message = table.concat({
"Camera not tweening because: ",
"Player has claimed this seat? " .. tostring(hasClaimedSeat),
"This is the approved seat? " .. tostring(isApprovedSeat)
}, "\n")
warn(messsage)
end
end
end)
end)
end)
Also, it looks like the LocalScript that is listening for this RemoteEvent is located in ReplicatedStorage. Check the documentation on LocalScripts, they only fire in a handful of locations, and ReplicatedStorage unfortunately isn't one of them. Try moving the LocalScript into StarterCharacterScripts and update the path to the RemoteEvent.
local camEvent = game.ReplicatedStorage.CamEvent
camEvent.OnClientEvent:Connect(function (camPart, isSeated) --receiver

Create a JPA Named Query with conditional where clause based on user value selections

I am rewriting an existing application and am required to use the existing application queries using JPA 2. How do I write a Named Query that replaces a dynamic query that will add sections to the where clause based on a value selection. In other words, if a value is selected from a drop down box, I will add a AND/OR section to the where clause. If not, that where clause section is omitted. For example:
int paramIdx = 0;
String query = "SELECT * FROM ANIMAL_TABLE WHERE...something";
String whereClause = "";
if(canine!= null and canine.trim().length() > 0) {
whereClause += " AND canine_type = :" + (paramIdx + 1) + viewObject.setWhereClauseParam(paramIdx, canine);
paramIdx++;
}
if(cat != null and cat.trim().length() > 0) {
whereClause += " AND cat_type = :" + (paramIdx + 1) + viewObject.setWhereClauseParam(paramIdx, cat);
}
I'm wondering if there is a way to accomplish this using JPA. Any ideas or suggestions would be helpful.

Dynamodb pagination of 10 results

I have a message table which I would like to get the last 10 messages for that user and if they click more it would retrieve another 10 until there were no more message left. I could not see how to do this, so far I am able to get message based on time, but this is not exactly what I want. Reading through the documentation I can see it a method called LastEvaluatedKey, but where and how do I use this I can't find a working example of this. This is my code for time:
long startDateMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L);
long endDateMilli = (new Date()).getTime() - (5L*24L*60L*60L*1000L);
java.text.SimpleDateFormat df = new java.text.SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String startDate = df.format(startDateMilli);
String endDate = df.format(endDateMilli);
QuerySpec spec = new QuerySpec()
.withProjectionExpression("to,fr,sta,cr")
.withKeyConditionExpression("to = :v_to and cr between :v_start_dt and :v_end_dt")
.withValueMap(new ValueMap()
.withString(":v_id", username)
.withString(":v_start_dt", startDate)
.withString(":v_end_dt", endDate));
ItemCollection<QueryOutcome> items = table.query(spec);
System.out.println("\nfindRepliesPostedWithinTimePeriod results:");
Iterator<Item> iterator = items.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next().toJSONPretty());
}
How can I modify this to eliminate the time based pagination and use instead a last 10 messages type of pagination?

ColdFusion - Get next scheduled task due to run

This thread was useful in finding out the next run-time for a scheduled task.
How do I find out the next run time for a Scheduled Task?
But, is there also a way to simply get the next scheduled task due to run?
If I can get the date and name of the next task due to run, I can plug that date into a jQuery countdown timer, which will display a countdown to the next scheduled task, something like:
TaskABC due to run in:
12 03 20
hrs min sec
. This is for an admin interface in case you're wondering how geeky can people get:-)
EDIT
I had the same thought as Bill. But was curious if there was another way.
I poked around and apparently the internal Scheduler class maintains a list of upcoming tasks. The list is private, but you can use the same reflection technique to access it. Interestingly the list also includes system tasks like the mail spooler, session/application trackers, watchers, etecetera. So you must iterate through it until you find a "scheduled task" ie CronTabEntry
Below is a very lightly tested function that seems to do the trick in CF9. (Note, includes the CreateTimeStruct function from http://www.cflib.org).
Rules:
Returns a structure containing the name and time remaining until the next task. If no tasks were found, result.task is an empty string.
Excludes paused tasks
Usage:
result = new TaskUtil().getNextTask();
WriteDump(result);
CFC
component {
public struct function getNextTask() {
// get list of upcoming tasks from factory (UNDOCUMENTED)
local.scheduler = createObject("java", "coldfusion.server.ServiceFactory").getSchedulerService();
local.taskField = local.scheduler.getClass().getDeclaredField("_tasks");
local.taskField.setAccessible( true );
local.taskList = local.taskField.get(local.scheduler);
// taskList contains system jobs too, so we must iterate
// through the tasks to find the next "scheduled task"
local.nextTask = "";
local.tasks = local.taskList.iterator();
while ( local.tasks.hasNext() ) {
local.currTask = local.tasks.next();
local.className = local.currTask.getRunnable().getClass().name;
// exit as soon as we find a scheduled task that is NOT paused
if (local.className eq "coldfusion.scheduling.CronTabEntry"
&& !local.currTask.getRunnable().paused) {
local.nextTask = local.currTask;
break;
}
}
// if we found a task, calculate how many days, hours, etcetera
// until its next run time
local.details = { task="", remaining={} };
if ( isObject(local.nextTask) ) {
local.secondsToGo = (local.nextTask.getWhen() - now().getTime()) / 1000;
local.details.task = local.nextTask.getRunnable().task;
local.details.remaining = createTimeStruct(local.secondsToGo);
local.details.nextDate = dateAdd("s", local.nextTask.getWhen() / 1000
, "January 1 1970 00:00:00" );
}
return local.details;
}
/**
* Abbreviated version of CreateTimeStruct by Dave Pomerance
* See http://www.cflib.org/index.cfm?event=page.udfbyid&udfid=421
*
* #param timespan The timespan to convert.
* #return Returns a structure.
* #author Dave Pomerance
* #version 1, January 7, 2002
*/
public struct function CreateTimeStruct(required numeric timespan) {
var timestruct = StructNew();
var mask = "s";
// only 4 allowed values for mask - if not one of those, return blank struct
if (ListFind("d,h,m,s", mask)) {
// compute seconds
if (mask eq "s") {
timestruct.s = (timespan mod 60) + (timespan - Int(timespan));
timespan = int(timespan/60);
mask = "m";
} else timestruct.s = 0;
// compute minutes
if (mask eq "m") {
timestruct.m = timespan mod 60;
timespan = int(timespan/60);
mask = "h";
} else timestruct.m = 0;
// compute hours, days
if (mask eq "h") {
timestruct.h = timespan mod 24;
timestruct.d = int(timespan/24);
} else {
timestruct.h = 0;
timestruct.d = timespan;
}
}
return timestruct;
}
}
My first thought is to iterate Leigh's getNextRunTime(string taskName) function over the collection of tasks. You can get an array of structs containing the details of all scheduled tasks using taskArray = createobject("java","coldfusion.server.ServiceFactory").getCronService().listAll();
The key in the struct containing the task name is "task". So you can extract all the task names as an array for example, run Leigh's function on each element and determine which one will run next.