Applescript Get value of property by string name of property - properties

In AppleScript. Let's say I have a record with a property called Title.
Let's say I set a variable to the text "Title"; can I use that variable to get the value of the property Title? Basically, is there any way to do something like this:
set result to property named "Title" of myRecord
Instead of:
set result to Title of myRecord

I found the answer. I also realize I didn't ask the correct question. The value I'm trying to obtain is from a property list item.
Here's what I learned, and how to accomplish this:
use framework "Foundation"
set _plist to ...
set _objcPlist to GetAppleScriptObjectAsObjcObject(_plist)
set _value to GetObjcPropertyValueByName("MyProperty", item 1 of _objcPlist)
on GetAppleScriptObjectAsObjcObject(asObject)
set a to current application
set cClass to class of asObject
if (cClass is record) then
return a's NSDictionary's dictionaryWithDictionary:asObject
else if (cClass is list) then
return a's NSArray's arrayWithArray:asObject
else
error "Unexpected Class Type"
end if
end GetAppleScriptObjectAsObjcObject
on GetObjcPropertyValueByName(propertyName, objcItem)
return (objcItem's valueForKey:propertyName) as text
end GetObjcPropertyValueByName

you may try the try ... on error approach:
set aRecord to {title:"hello world", author:"who's who"}
try
aRecord as Unicode text
on error error_message
set err to error_message
end try
err
-- "Can’t make {title:\"hello world\", author:\"who's who\"} into type Unicode text."
then parse err (it's text now). it depends on the complexity of aRecord, if it's a record of nested lists, or records; the parsing would be very complicated. have fun :)

Related

SQLSTATE[22007]: Invalid datetime forma

I try to save some data that it brings me from my view, which is a table, but I don't know why it throws me that error with the insert.
result of insert
this is my view:
table of view
this is my controller:
$checked_array = $_POST['id_version'];
foreach ($request['id_version'] as $key => $value) {
if (in_array($request['id_version'][$key], $checked_array))
{
$soft_instal = new Software_instalacion;
$soft_instal->id_instalacion = $instalaciones->id;
$soft_instal->id_historial = $historial->id;
$soft_instal->id_usuario = $request->id_usuario;
$soft_instal->id_version = $_POST['id_version'][$key];
$soft_instal->obs_software = $_POST['obs_software'][$key];
$soft_instal->id_tipo_venta = $_POST['id_tipo_venta'][$key];
$soft_instal->save();
}
}
id_tipo_venta seems to be an empty string which is apparently not valid.
You can try debugging what you get in :
var_dump($_POST['id_tipo_venta'][$key]);
die;
Your database field expects to receive an integer. Therefore, using the intval() function can solve your problem.
Indeed, I think your code returns an alphanumeric string.
Therefore, the code below will return 0 in all cases if no version is returned (not set, string or simply null):
$soft_instal->id_tipo_venta = intval($_POST['id_tipo_venta'][$key]);
On the other hand, intval() will always convert to int, so a decimal will be converted, example :
intval("1.1") // returns 1
intval("v1.1") // returns 0
If this is not the desired behavior, maybe you should think about changing your database type.
EDIT :
Of course, you can also set the value as null if you prefer to 0. You must allow nullable values in your database.
id_tipo_venta can not be empty, try with some number or change type column to varchar in the database

Setting a variable to linq query with no results

I have a table that holds links to websites about particular theaters. I want to retrieve the first link for a given theater. My code to set the variable:
Dim link As String = TheaterLinks.Where(Function(x) x.TheaterID = TheaterID).FirstOrDefault().Link
If there are no results (some theaters won't have any links), then I get:
Object reference not set to an instance of an object.
How do I do this? I tried:
Dim link As String = Links.Where(Function(x) x.TheaterID = TheaterID.DefaultIfEmpty().First().Link
But I can't figure out what to put inside DefaultIfEmpty(). I tried DefaultIfEmpty("") and DefaultIfEmpty(blankstringvariable) but then I get:
Value of type 'String' cannot be converted to type 'TheaterLink'.
The problem is that FirstOrDefault() is allowed to return null, in which case accessing Link property would throw an exception.
If you use VB.NET 14, add question mark for automatic null checking:
Dim link As String = TheaterLinks.Where(Function(x) x.TheaterID = TheaterID).FirstOrDefault()?.Link
(see ?.Link instead of .Link)
Otherwise, do it in two stages: first, get the object using FirstOrDefault, then null-check it manually with an If statement.
For my original example, I just had to add a question mark:
Dim link As String = Links.Where(Function(x) x.ID = id).FirstOrDefault()?.Link
I tried doing this in my model and got a "Nullable object must have a value" error, so I did the two-stage approach:
Dim eventDate = Events.Where(Function(x) x.ID = id).FirstOrDefault()?.EventDate
If eventDate.HasValue Then
'some code
Else
'some code
End If

SPFieldUserValue : Value does not fall within the expected range

Following piece of code returning following error not sure where is the problem,
Exception Details: System.ArgumentException: Value does not fall within the expected range.
public static SPUser convertStringToSPUser(string struser)
{
SPFieldUserValue userValue = new SPFieldUserValue(SPContext.Current.Web, struser);
SPUser objSPUser = userValue.User;
return objSPUser;
}
My string is something like, "S, Rishi".
In order to create an instance of SPFieldUserValue you should Pass a string with the following format:
[int];#[domain]\[username]
The easiest way to get that value from a list item is:
ListItem[field_GUID].ToString();

Matlab's arrayfun for uniform output of class objects

I need to build an array of objects of class ID using arrayfun:
% ID.m
classdef ID < handle
properties
id
end
methods
function obj = ID(id)
obj.id = id;
end
end
end
But get an error:
>> ids = 1:5;
>> s = arrayfun(#(id) ID(id), ids)
??? Error using ==> arrayfun
ID output type is not currently implemented.
I can build it alternatively in a loop:
s = [];
for k = 1 : length(ids)
s = cat(1, s, ID(ids(k)));
end
but what is wrong with this usage of arrayfun?
Edit (clarification of the question): The question is not how to workaround the problem (there are several solutions), but why the simple syntax s = arrayfun(#(id) ID(id), ids); doesn't work. Thanks.
Perhaps the easiest is to use cellfun, or force arrayfun to return a cell array by setting the 'UniformOutput' option. Then you can convert this cell array to an array of obects (same as using cat above).
s = arrayfun(#(x) ID(x), ids, 'UniformOutput', false);
s = [s{:}];
You are asking arrayfun to do something it isn't built to do.
The output from arrayfun must be:
scalar values (numeric, logical, character, or structure) or cell
arrays.
Objects don't count as any of the scalar types, which is why the "workarounds" all involve using a cell array as the output. One thing to try is using cell2mat to convert the output to your desired form; it can be done in one line. (I haven't tested it though.)
s = cell2mat(arrayfun(#(id) ID(id), ids,'UniformOutput',false));
This is how I would create an array of objects:
s = ID.empty(0,5);
for i=5:-1:1
s(i) = ID(i);
end
It is always a good idea to provide a "default constructor" with no arguments, or at least use default values:
classdef ID < handle
properties
id
end
methods
function obj = ID(id)
if nargin<1, id = 0; end
obj.id = id;
end
end
end

Flag invalid attribute in ActiveRecord

I am trying to implement functionality wherein an attribute, once set, cannot be changed on an ActiveRecord model. To this end, I have written the following methods:
def address
self[:address]
end
def address=(val)
if new_record?
self[:address] = val
else
errors.add(:address, "Cannot change address, once it is set")
return false # tried return nil here first, did not work
end
end
Am I doing something wrong here? I want the object to be invalid once I try to change an address, but I do not get any errors when I do obj.valid?
EDIT: The value is not changed once it is set, but I would like to get invalid object when I do the validation via obj.valid?
When you do obj.valid?, it clears all of your errors, and then runs each of the validations in turn. To have this produce an error on validation, you'll have to move that logic into a validation block.
Here's an example of one way to do that with an instance variable:
def address=(val)
if new_record?
self[:address] = val
else
#addr_change = true
return false # tried return nil here first, did not work
end
end
validate do |user|
errors.add(:address, "Cannot change address, once it is set") if #addr_change
end