How can I scope created_at between two times and use said scope on an instance? - class

I'm trying to create a scope, active, that queries for entries of a class, Shift, that are 5 hours old. I'm then trying to take the scope and apply it to an instance of Shift so I can have the shifts controller redirect to show the active shift. Here's shift.rb:
class Shift < ActiveRecord::Base
scope :active, -> { where(created_at: (Time.now.ago(5.hours)..Time.now)) }
validates :created_at, uniqueness: true
validates_time :created_at, :between => ['9:30pm', '2:30am']
validate :active_shift_limit
private
def active_shift_limit
if Shift.active.count >= 1
errors.add(:base, "Shift already exists for tonight")
end
end
end
First off, I'm having problems with the scope. I created a shift 8 hours ago and am querying for it in the console.
Shift.active.exists?
Shift Exists (0.2ms) SELECT 1 AS one FROM "shifts" WHERE ("shifts"."created_at" BETWEEN '2015-09-14 22:48:35.929658' AND '2015-09-15 03:48:35.929768') LIMIT 1
=> true
So I take a look at the entry.
Shift.active
Shift Load (0.2ms) SELECT "shifts".* FROM "shifts" WHERE ("shifts"."created_at" BETWEEN '2015-09-14 23:03:38.195154' AND '2015-09-15 04:03:38.195191')
=> #<ActiveRecord::Relation [#<Shift id: 32, shift_id: nil, vehicle_id: nil, user_id: nil, created_at: "2015-09-15 00:11:32", updated_at: "2015-09-15 00:11:32">]>
The scope is registering a range into tomorrow, I don't know why, so I try entering the range I've given the scope into the console to see if the problem is there:
Time.now.ago(5.hours)..Time.now
=> 2015-09-14 16:08:35 -0700..2015-09-14 21:08:35 -0700
Alright. At this point I'm stumped. Where am I going wrong?
As for the second part of the question, calling the scope on an instance of Shift, I'm also stumped. I've realized, after some tinkering, that scope is a class method. So I figured calling it on the method and putting that inside an instance variable would work. No cigar. I get this error:
ActiveRecord::RecordNotFound in ShiftsController#create
"Couldn't find Shift without an ID"
Here's my shifts_controller.rb:
class ShiftsController < ApplicationController
skip_before_filter :verify_authenticity_token, :only => :create
def show
#shift = Shift.find(params[:id])
end
def create
#active_shift = Shift.active
if Shift.active.exists?
redirect_to shift_path(#active_shift)
else
#shift = Shift.new
#shift.save
redirect_to shift_path(#shift)
end
end
end
I'm using this gem for validates_time in shift.rb:
gem 'jc-validates_timeliness', '~> 3.1.1'. I heavily referenced this in figuring out the scope: How do I validate one post per day?

Related

I am thinking of easy account security Developers

If there is "FreezeToken" in the wallet, freeze the wallet.
And if there is "ThawToken" in the wallet, it cancels the freeze.
This code is an example of failure.
let FreezeToken = base58'GwmXnsF3Z5tANgHwmDW7Lf4SwyYNEp4S3QZM3aBFLHwS'
let ThawToken = base58'GK7ZV8xFbh1Qz14Cnr6mLkV93svaZGrurVuaBZocwLZZ'
match tx {
case m : ExchangeTransaction. =>
if (assetBalance(e.sender,ThawToken) >= 1 ) then{true}
else if (assetBalance(e.sender,ThawToken) >= 1 ) then{false}
else true
case _ => false
}
TransferTransaction succeeded but ExchangeTransaction failed.
How do I change this code? please tell me.
I am guessing you are creating a smart account?
From what I see in the code, is that you used 2 times ThawToken, one time this results to true and another time to false. My guess is that you want one from the 2 be replaced by FreezeToken
Also in your example you have "ExchangeTransaction.", this dot doesn't seem needed here from what I can understand from your code.
Also according to the examples it seems that your whole second if structure should be included into {}. Example: https://github.com/wavesplatform/ride-examples/blob/bc8db2342f53fe1554a10dc5aaa211b1542a5ca1/smart-assets/HotPotatoToken.ride#L41
However I think this issue could be solved with a && statement, and as following the second if-then-else is not needed anymore.
What I propose is a check that does following:
Check if ThawToken not in wallet and if that is the case, check if freezetoken is in wallet.
If ThawToken is and FreezeToken is also => wallet free since ThawToken frees it.
If ThawToken is not and FreezeToken is 1 or more => wallet locked since only FreezeToken.
If ThawToken is not and FreezeToken is not => wallet free since no FreezeToken
if (assetBalance(e.sender,ThawToken) == 0 &&
assetBalance(e.sender,FreezeToken) >= 1 ) then{
false
}else{
true
}
Also to block all transactions and indeed freeze the wallet, you would need to filter on another type, for all types use: Transaction, be careful this also disables the option to change the script in case you locked your account.
To block transfer transaction use: TransferTransaction.
All types can be found here:
https://docs.wavesplatform.com/en/smart-contracts/ride-language/standard-library.html

Set object properties after setting the object

I've created a class with various properties in VB6.
The properties are
PiccoId
OrderId
UserId
StockCode
Quantity
At the top of the class I have declared 2 instances of classes I'm using.
Dim stkLine As CSOPSLine ' This is the class where the properties are declared and read
Private SOPSLines As cSLine ' This class creates the new objects and sets the property values
When the user enters the order number on a handheld barcode scanner, I'm creating an object to associate with this particular scanner like so:
Set SOPSLines = New cSLine
Set SOPSLines = getSOPSLine(ID, sOrder, "", "", 0)
In the next stage of the process, the user needs to enter their user ID so it can be seen which user scanned in the item.
I need to update the property of this same object, but I'm not sure how - Currently I am trying to do it within my getSOPSLine function, like this:
Dim line As New CSOPSLine
Dim bFound As Boolean
bFound = False
For Each line In SOPSLines.Items
If line.PiccoId = ID Then
line.OrderId = OrderId
line.Quantity = Qty
line.StockCode = stock
line.UserId = UserId
Set getSOPSLine = line
bFound = True
Exit For
End If
Next
If bFound = False Then
Set line = SOPSLines.Add(ID, OrderId, UserId, stock, Qty)
Set getSOPSLine = line
End If
Set line = Nothing
However, as I'm not storing sOrder at class level (Due to the fact multiple users can be using barcode scanners, the order ID can't be kept at class level as other users will just overwrite it),
I'm not sure how once I've got the next variable (In this case, userID, and the other variables after this stage) I can update the same object as I've just created.
I've tried to do something like
Set stkLine = getSOPSLine(ID, stkLine.OrderId, pUser, "", 0)
but it errors saying
object or with block variable has not been set
How can I update the properties of stkLine without constantly creating new objects?
EDIT
To clarify:
When the application receives data from the handheld barcode scanner, a select case is entered, with one case for each of the variables being entered (E.g. Order ID, user ID, stock code etc.)
The first case sets the order ID.
The code here is
Case FRAME_ORDER_SELECTION
On Error Resume Next
Dim sOrder As Long
sOrder = Picco.GetData(ID, 50)
If sOrder = 0 Then
Call Picco.Send(ID, FRAME_ORDER_SELECTION)
Exit Sub
Else
With Picco
Call .ClearForm(ID)
Call .Text(ID, LINE_1, "===== User ID =====")
Call .Text(ID, LINE_2, "")
Call .NewField(ID, 60, 5, FLD_LINE + SND_ENTER)
Call .Send(ID, FRAME_LINE_ADD)
Set SOPSLines = New cSLine
Set SOPSLines = getSOPSLine(ID, sOrder, "", "", 0)
End With
End If
frameid = FRAME_LINE_ADD
m_iLastFrameId = FRAME_ORDER_SELECTION
On Error GoTo Picco_DataArrived_Err
This is where the object is created.
The next case is after the user enters their user ID into the scanner.
Case FRAME_LINE_ADD
On Error Resume Next
Dim pUser As String
pUser = ""
pUser = Picco.GetData(ID, 60)
If pUser = "" Then
Exit Sub
End If
On Error GoTo Picco_DataArrived_Err
With Picco
Call .ClearForm(ID)
Call .Text(ID, LINE_1, "===== Add Line =====")
Call .Text(ID, LINE_2, "")
Call .Text(ID, LINE_7, "Scan or type code")
Call .NewField(ID, FIELD_POS, 18, FLD_LINE + FLD_READER + SND_ENTER)
Call .Send(ID, FRAME_LINE_QTY)
End With
Set stkLine = getSOPSLine(ID, stkLine.OrderId, pUser, "", 0)
frameid = FRAME_LINE_QTY
m_iLastFrameId = FRAME_LINE_ADD
Then there will be 2 or 3 more cases when populating the rest of the required values.
What I need to do, is in the second case (And all other following cases) update the properties of the object created in the first case.
I'm using the getSOPSLine function as this gets the object with the matching barcode scanner ID (As multiple users may be accessing different orders, they need to be kept separate in this way), but I'm not sure how to update the object where the scanner ID matches.
When you call getSOPSLine in each Case, enter some temporary values for the variables that you're not setting.
Example;
In the UserID case: stkLine = getSOPSLine(ID, 0, pUser, "", 0)
Then, in the getSOPSLine() function, change it so that instead of setting the values automatically, it instead only updates them if they don't equal 0, or "", or whichever temporary variables you use.
That way you're updating the same object, but aren't storing data that may get overwritten.
I'm not sure what you're confused about; I think that you must have some misunderstanding of what objects, variables, and properties are that is preventing you from asking this in a way that I understand. I'm not sure how your code lines up with your questions. But I'll give this a shot:
Private SOPSLines As cSLine
Set SOPSLines = New cSLine
Set SOPSLines = getSOPSLine(ID, sOrder, "", "", 0)
This declares a class-level variable, that can hold a cSLine object. That seems reasonable. Then you create a new instance of cSLine to put in that variable. But I don't know why, because you then point the variable to a different instance entirely, which is the instance returned from your getSOPSLine function. That middle line doesn't seem to be doing anything, and I'm not sure what you're trying to do with it.
I've tried to do something like
Set stkLine = getSOPSLine(ID, stkLine.OrderId, pUser, "", 0)
but it errors saying
object or with block variable has not been set
Well, then it sounds like stkLine isn't set to an object. I don't see any code that's trying to set stkLine other than that line. So when you try to get stkLine.OrderId, there isn't an object to get the OrderID property of, so it gives you an error.
I need to update the property of this same object, but I'm not sure how
Well, if there's an object you care about, you probably have it in a variable somewhere. You use variable.property = value syntax to assign value to the property of the object currently stored in variable.
But again, I'm not sure where your confusion is, since you're clearly assigning properties of objects in your code already.
If you're not understanding how objects work in VB, I'd recommend reading through the Working with Objects chapter of the documentation.
And if your confusion lies elsewhere, perhaps you could put together a more specific question about what you're trying to do?

Hartl Section 9.1.3: test_unsuccessful_edit fails with error ParameterMissing "user"

I'm running through Michael Hartl's Ruby on Rails Tutorial, and have run into a problem I have been unable to troubleshoot. The test for editing users (users_edit_test.rb) fails for reasons I don't understand. Since the tutorial is mostly an exercise in copying code, if have checked and double-checked my typing, but I can't find where I messed up. And, more importantly, I want to understand what is going on. Any help you can provide would be appreciated.
The error message (included below) seems to indicate that the test is launching the edit method in the users controller (users_controller.rb), which in turn launches the private user_params method in the same controller. The user_params method sets strong parameters that require the user parameter, and permit the name, email, password, and password_confirmation parameters. The user parameter does not exist when the test runs, so it returns the error.
My first question is, "What is the user parameter?" The name, email, password, and password_confirmation parameters all refer to columns in the users database, and there is also an id column. But there is no user column. The test and the controller both have an #user variable. Is that the user parameter? That doesn't seem to make sense, as I ought to be able to call the variable whatever I want to, right? I feel like there is something fundamental here that I am not getting, and if I got it, I could troubleshoot this and answer the second question, "What did I screw up/how do I fix this?", myself.
users_edit_test.rb
require 'test_helper'
class UsersEditTest < ActionDispatch::IntegrationTest
def setup
#user = users(:michael)
end
test "unsuccessful edit" do
get edit_user_path(#user)
#assert_template 'users/edit'
#patch user_path(#user), user: { name: "",
# email: "foo#invalid",
# password: "foo",
# password_confirmation: "bar" }
#assert_template 'users/edit'
end
end
users_controller.rb
class UsersController < ApplicationController
def show
#user = User.find(params[:id])
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
log_in #user
flash[:success] = "Welcome to the Sample App!"
redirect_to #user
else
render 'new'
end
end
def edit
#user = User.find(params[:id])
if #user.update_attributes(user_params)
# Handle a successful update.
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:name,
:email,
:password,
:password_confirmation)
end
end
users.yml
michael:
name: Michael Example
email: michael#example.com
password_digest: <%= User.digest('password') %>
Test Output
Started
ERROR["test_unsuccessful_edit", UsersEditTest, 2015-05-14 00:05:19 +0000]
test_unsuccessful_edit#UsersEditTest (1431561919.08s)
ActionController::ParameterMissing:
ActionController::ParameterMissing: param is missing or the value is empty: user
app/controllers/users_controller.rb:34:in user_params
app/controllers/users_controller.rb:24:in edit
test/integration/users_edit_test.rb:10:in block in class:UsersEditTest
app/controllers/users_controller.rb:34:in user_params
app/controllers/users_controller.rb:24:in edit
test/integration/users_edit_test.rb:10:in block in class:UsersEditTest
27/27:
[==================================================================]
100% Time: 00:00:00, Time: 00:00:00
Finished in 0.69446s 27 tests, 60 assertions, 0 failures, 1 errors, 0 skips
For starters: you probably should start your test with a log_in as(#user) before get edit_user_path(#user).
That is part of the question: the logged in user provides the params-info you are looking for.
The params are sent by the browser, to one of the controller actions. This is probably one of the hard parts when you are starting Rails; you may want to find some info on the request/response cycle in rails, and how they are mapped to the controller actions.
(And by the way, why are your test lines commented out in your question?)
You should implement method Update, then there is no errors.
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to #user
else
render 'edit'
end
end

Form Gathering Info from Two Other Forms

I have a form that creates a New Work Order. I want to be able to pull the ClientID from the New Client Form or the Main Menu, whichever is open. However I am not getting the desired results:
I have used =IIf(IsNull(Forms![New Client]![txtClientID]), Forms![Main Menu]![txtClientID], Forms![New Client]![txtClientID]) in the Default Value of the Control on the New Work Order Form. I get the correct ID when I go to the form from New Client, but a #Name error when I try to access it from the Main Menu.
What can I do to make it work?
You need to check if the form is loaded, for example (you need to add your own error traps):
Function IsLoaded(ByVal strFormName As String) As Boolean
Const conObjStateClosed = 0
Const conDesignView = 0
If SysCmd(acSysCmdGetObjectState, acForm, strFormName) <> conObjStateClosed Then
If Forms(strFormName).CurrentView <> conDesignView Then
IsLoaded = True
End If
End If
However, it may be easier to use OpenArgs ( http://msdn.microsoft.com/en-us/library/office/ff820845(v=office.15).aspx )
In which case you could say something like:
If IsNull(Me.OpenArgs) Then
MsgBox "No openargs"
Else
Me.txtClientID = Me.Openargs
End If
Or even use Openargs to set the default value.

ClearQuest Perl API -- Adding a Child Record to another record

I have a ClearQuest database with a record type called "BuildSheet". On a BuildSheet record, you can attach tasks which are another record type.
I thought I could create a task record type, via the BuildEntity Session method, then do a EditEntity Session method on the BuildSheet record, and add the Task Id field via the AddFieldValue Entity method.
Unfortunately, my attempt to create the Type record fails. It gets tripped by the eval statement:
#
# Now Create the Record Type and Fill in the Fields
#
my $record;
eval { $record = $cq->BuildEntity(TASK_RECORD_TYPE); };
if ($#) {
croak qq(Error when attempting to create record type ")
. TASK_RECORD_TYPE . qq("\n$#\n);
}
if (not $record) {
die qq(Cannot create entity ") . TASK_RECORD_TYPE . qq("\n);
}
The eval is failing when I attempt to create the TASK_RECORD_TYPE record. I get the following error message:
Error when attempting to create record type "Task"
Permission denied for user WeintraubH to perform action Create (of type SUBMIT)
at D:/Program Files/Rational/Common/lib/perl5/site_perl/5.8.6/CQPerlExt.pm line 43.
at H:\svn\addTask.cqpl line 340
main::createTask('TASK', 'cm', 'HEADLINE',
'FMS-CWA_APP_B35_HF276', 'DESCRIPTION', 'FMS-CWA_APP_B35_HF276',
'PRIORITY', 2, 'EFFORT', ...) called at H:\svn\addTask.cqpl line 236
Now, I can bring up a BuildSheet record, go into the Child Record tag, click Create and build my task record that way, so apparently I do have permission.
What it seems is that I must somehow associate the "Task" record with a "BuildSheet" before I try to create it, but how?
I found the culprit. They have a hook on the BuildEntity method in order to ensure that the Task record I'm trying to create is connected to a parent record. Stupid *###*$&#.
Anyway I found the hook script (written in VB) and found where they were trying to trip me up:
Set oSession = GetSession
pRequestIDValue = oSession.NameValue("ParentRequestID")
pTaskIDValue = oSession.NameValue("ParentTaskID")
pBuildSheetIDValue = oSession.NameValue("ParentBuildSheetID")
NewTaskPermittedValue = oSession.NameValue("NewTaskPermitted")
curUser = oSession.GetUserLoginName
if (pBuildSheetIDValue <> "") or (pTaskIDValue <> "") _
or ((pRequestIDValue <> "") and (NewTaskPermittedValue = "Yes")) then
task_AccessControl = TRUE
else
task_AccessControl = FALSE
end if
To get around this, I set ParentBuildSheetID with the SetNameValue method before I attempted to create the record:
$cq->SetNameValue("ParentBuildSheetID", $buildsheetId);
my $record;
eval { $record = $cq->BuildEntity(TASK_RECORD_TYPE); };
if ($#) {
croak qq(Error when attempting to create record type ")
. TASK_RECORD_TYPE . qq("\n$#\n);
}
if (not $record) {
die qq(Cannot create entity ") . TASK_RECORD_TYPE . qq("\n);
}
Now, that worked!
No, I don't think you have to associate the Task record with the BuildSheet as you call BuildEntity.
Can you call GetSubmitEntityDefNames and verify that "Task" is in its results?
http://www.ibm.com/developerworks/forums/thread.jspa?threadID=179429 has the closest example I see to what you are trying to do. If so, once you get past the BuildEntity problem, rather than:
then do a EditEntity Session method on the BuildSheet record, and add the Task Id field via the AddFieldValue Entity method.
you want to set the correct relation field on your new Task to the BuildSheet Id before Commit rather than set the Task Id on the BuildSheet record.
I hope this helps; I haven't had to use ClearQuest in more than a decade, so I'm just going by what the (way too scant) documentation says.