Consistent output of as.character for date objects in R - string

An external R library uses the as.character function to convert objects of different classes to strings. That works fine except for my date objects (classes "POSIXlt" and "POSIXt"): Normally the output is like "2010-11-04 10:43:00" (which is perfect) but every time when time is 00:00:00 (midnight) the time component is ommited and only the date component is shown like "2010-11-04". But for further processing I need a consistent output format. So the time component should be displayed in any case.
I can't simply use the format function because the external library does the call. So I thought that overwriting the as.character function for the classes "POSIXlt" and "POSIXt" could be a solution but I don't know how. Other ideas are welcome :)

You can overwrite the as.character method for POSIXct objects simply by creating your own.
as.character.POSIXct <- function(x, format="%Y-%m-%d %H:%M:%S", ...)
format(x, format=format, ...)
In this case though, there is no existing as.character.POSIXct so you're not actually overwriting anything. You are, however, overriding the default as.character.POSIXt method, which is what would be called in the absence of a POSIXct method.

Related

Python 3.10 datetime strptime not picking up time zone?

I have a timestamp embedded in some JSON data as a string, for ease of inspection and modification. An example looks like this:
"debug_time": 1670238819.9747384,
"last_saved": "2022-12-05 11:13:39.974725 UTC",
When loaded back in, I need to convert it back to a float for comparison against time.time() and similar things, however, I can't seem to find the magic incantations to have it restore the correct value.
In restoring the JSON data, I attempt to convert the string to a float via strptime() like this:
loaded_time = datetime.datetime.strptime(obj.last_saved, '%Y-%m-%d %H:%M:%S.%f %Z')
This does restore the timestamp to a valid datetime object, however calling .tzname() results in None, and my attempts to use loaded_time.replace(tzinfo=zoneinfo.ZoneInfo('UTC')) have not yielded any useful results.
In short, emitting loaded_time.timestamp() yields 1670267619.974725, which is 8 hours ahead of what it should be. I've tried using .astimezone(), in various permutations, but can't find a way to correctly have it convert to the client's local time.
I even tried to hard-code in my own time zone US/Pacific but it stubbornly refuses to give me that original debug_time value back.
This doesn't seem like it should be a difficult problem, but clearly I'm misunderstanding something about how python 3's time handling works. Any ideas are welcome!
Thank you for your time!
you have to use built in function replace like
.strftime("%Y-%m-%dT%H:%M:%S.%f%Z").replace("UTC", "")

Python SCons Action?

I've been searching the documentation for a long time and still can't figure this out.
In the SCons documentation, there is discussion about adding a PreAction or PostAction. In the examples, they call an example method:
foo = Program('foo.c')
AddPreAction(foo, 'pre_action')
This calls 'pre_action' before 'foo.c' is compiled and linked. However, there is no explanation about what format 'pre_action' must take.
I have discovered that there are several pre-built actions, such as 'Copy'. However, I cannot find the source of 'Copy' to reverse-engineer it and write my own.
Can anyone point me to a guide as to how to create my own Actions? I either need an interface for calling my own method such as 'pre_action' above, or a guide for writing an Action class.
Really, even just some example code that is actually complete enough to use would be helpful...
The manpage section Action Objects lists the types of things that can be passed to the Action factory function to create an action; that is also what you pass to AddPostAction and AddPreAction as the second argument - that is, either an Action already made by a previous call to Action, or something that can be converted into one like a command string, or a list of such, or a function with appropriate signature. Pre/Post will simply call the Action function with that argument. So in that section, where there's an example with a call to Action, you could just plug that argument into AddPreAction, or you could save the result of calling Action and give that as the argument to AddPreAction.
The amount of flexibility here makes it a little tricky to document concisely.
(btw the source to Copy is a function called copy_func but you probably don't want to use that form because it's a couple of extra levels of abstraction you won't need)

JMeter functions and variables

I'm new to JMeter so this question may sound absolutely dumb...
I have a loop in which a variable (let's say it is called "raw") is being changed and written to file every iteration. The variable contains HTML encoded text so it has to be converted into plain text. I found out this can be done using __unescapeHtml function. When I tried using it worked but I ended up always receiving the same text as on the first iteration. Then I learned that I have to use vars.get instead of ${} to access a variable. So I changed ${__unescapeHtml("${raw}")} to ${__unescapeHtml(vars.get("raw")} which kind of helped: vars.get is getting the new value of raw each iteration but __unescapeHtml didn't work at all now - it just returns the encoded text from raw. I didn't succeded finding anything about this exact problem so I'm kind of stuck.
Ended up using
import org.apache.commons.lang3.StringEscapeUtils
...
StringEscapeUtils.unescapeHtml4(vars.get("raw"))
Don't know if it is a good way to do this but at least it works.
I assume, that you are using the expression ${...} inside a JSR-223 sampler or similar context. The user manual for JSR-223 Sampler states, that those scripts can be cached by JMeter. That is why you only get the values from the first time the context gets created.
The same is true for simple variable evaluations as ${varname}, as for function calls like ${__unescapeHtml(...)}.
The solution here is:
don't use ${...} inside of JSR-223 contexts, that might be cached.
you can however pass those expressions (${...}) into the context by using them as parameters through the input labeled Parameters on the JSR-223 Sampler – again assuming, that you are using it.
you can use the features, that your chosen JSR-223 context gives you, as you have done, by using the StringEscapeUtils#unescapeHtml4

automapper - simplest option to only write to destination property if the source property is different?

NOTE: The scenario is using 2 entity framework models to sync data between 2 databases, but I'd imagine this is applicable to other scenarios. One could try tackling this on the EF side as well (like in this SO question) but I wanted to see if AutoMapper could handle it out-of-the-box
I'm trying to figure out if AutoMapper can (easily :) compare the source and dest values (when using it to sync to an existing object) and do the copy only if the values are different (based on Equals by default, potentially passing in a Func, like if I decided to do String.Equals with StringComparison.OrdinalIgnoreCase for some particular pair of values). At least for my scenario, I'm fine if it's restricted to just the TSource == TDest case (I'll be syncing over int's, string's, etc, so I don't think I'll need any type converters involved)
Looking through the samples and tests, the closest thing seems to be conditional mapping (src\UnitTests\ConditionalMapping.cs), and I would use the Condition overload that takes the Func (since the other overload isn't sufficient, as we need the dest information too). That certainly looks on the surface like it would work fine (I haven't actually used it yet), but I would end up with specifying this for every member (although I'm guessing I could define a small number of actions/methods and at least reuse them instead of having N different lambdas).
Is this the simplest available route (outside of changing AutoMapper) for getting a 'only copy if source and dest values are different' or is there another way I'm not seeing? If it is the simplest route, has this already been done before elsewhere? It certainly feels like I'm likely reinventing a wheel here. :)
Chuck Norris (formerly known as Omu? :) already answered this, but via comments, so just answering and accepting to repeat what he said.
#James Manning you would have to inherit ConventionInjection, override
the Match method and write there return c.SourceProp.Name =
c.TargetProp.Name && c.SourceProp.Value != c.TargetProp.Value and
after use it target.InjectFrom(source);
In my particular case, since I had a couple of other needs for it anyway, I just customized the EF4 code generation to include the check for whether the new value is the same as the current value (for scalars) which takes care of the issue with doing a 'conditional' copy - now I can use Automapper or ValueInject or whatever as-is. :)
For anyone interested in the change, when you get the default *.tt file, the simplest way to make this change (at least that I could tell) was to find the 2 lines like:
if (ef.IsKey(primitiveProperty))
and change both to be something like:
if (ef.IsKey(primitiveProperty) || true) // we always want the setter to include checking for the target value already being set

python: manipulating __dict__ of the class

(All in ActivePython 3.1.2)
I tried to change the class (rather than instance) attributes. The __dict__ of the metaclass seemed like the perfect solution. But when I tried to modify, I got:
TypeError: 'dict_proxy' object does
not support item assignment
Why, and what can I do about it?
EDIT
I'm adding attributes inside the class definition.
setattr doesn't work because the class is not yet built, and hence I can't refer to it yet (or at least I don't know how).
The traditional assignment doesn't work because I'm adding a large number of attributes, whose names are determined by a certain rule (so I can't just type them out).
In other words, suppose I want class A to have attributes A.a001 through A.a999; and all of them have to be defined before it's fully built (since otherwise SQLAlchemy won't instrument it properly).
Note also that I made a typo in the original title: it's __dict__ of a regular class, not a metaclass, that I wanted to modify.
The creation of a large number of attributes following some rule smells like something is seriously wrong. I'd go back and see if there isn't a better way of doing that.
Having said there here is "Evil Code" (but it'll work, I think)
class A:
locals()['alpha'] = 1
print A.alpha
This works because while the class is being defined there is a dictionary that tracks the local variables you are definining. These local variables eventually become the class attributes. Be careful with locals as it won't necessarily act "correctly." You aren't really supposed to be modifying locals, but it does seem to work when I tried it.
Instead of using the declarative syntax, build the table seperately and then use mapper on it. see http://www.sqlalchemy.org/docs/05/ormtutorial.html# I think there is just no good way to add computed attributes to class while defining it.
Alternatively, I don't know whether this will work but:
class A(object):
pass
A.all_my_attributes = values
class B(declarative_base, A):
pass
might possibly work.
I'm not too familiar with how 3 treats dict but you might be able to circumvent this problem by simply inheriting the dictionary class like so:
class A(dict):
def __init__(self,dict_of_args):
self['key'] = 'myvalue'
self.update(dict_of_args)
# whatever else you need to do goes here...
A() can be referenced like so:
d = {1:2,3:4}
obj = A(mydict)
print obj['test'],obj[3] # this will print myvalue and 4
Hope this helps.

Resources