python – Modifying __getattr__ to return a nested attribute instead of the named object

I’m writing an application with two basic class types:

  1. DocumentObject
  2. Property (of document object).

Property instances are attributes of the DocumentObject class and The Property class has several simple attributes of its own (value, unit, etc.) and some methods.

In trying to make the scripting as user friendly as possible, I would like
objectName.propertyName
to return the value attribute of the Property instance, not the Property instance itself. Of course, it is possible to write objectName.propertyName.value but most of the time, the user will be interacting with the value, not the Property instance.

It seems it should be possible to implement this behaviour using modified __getattr__ and __setattr__ methods in DocumentObject like in the following example:

Input

class Property():
    def __init__(self, name, value):
        self.name = name
        self.value = value


class DocumentObject():
    def __init__(self, properties):
        object.__setattr__(self, 'properties', dict())
        self.properties = properties
 
    def __getattr__(self, name):
        if "properties" in vars(self):
            if name in self.properties:
                return self.properties(name).value
            else: raise AttributeError
        else: raise AttributeError
 
    def __setattr__(self, key, value):
        if key in self.properties:
            self.properties(key).value = value
        else:
            object.__setattr__(self, key, value)
 

brick = DocumentObject({'length': Property('length',10), 'width': Property('width',5)})
print(brick.properties("length").name)
print(brick.length)

Output

length
10

Questions:

  1. Is is good practice to do this?
  2. Are there likely to be some negative consequences of this decision?
  3. Is there a more elegant solution that I have missed?

language design – Why do “checked exceptions”, i.e., “value-or-error return values”, work well in Rust and Go but not in Java?

From a scientific point of view, checked exceptions can be seen as alternative return values, e.g.

Exactly. They can be seen that way, and they should be but they aren’t.

Using an Error type like is common in Rust, Elm, Haskell, and in some sub-communities in Scala or a special error value as in Go is just an alternative return value indicated in the type system. A checked exception is like an alternative return value, but it doesn’t use the normal way of returning values, it is a completely separate, very different way of “returning values”. It also sits outside of the type system, and bolts on a completely separate “checked exception” system onto the type system.

But most importantly, it is not just an alternative return value, it is also an alternative control flow.

Another problem with the specific way checked exceptions are implemented in Java, is that they are anti-modular. That is, however, not a fundamental problem of checked exceptions, unlike the ones I mentioned above. There is an idea of Modular Anchored Exceptions, for example, where you can specify something like

int foo() throws like bar { return bar(); }

And you don’t have to know (and leak!) which precise exceptions bar can throw. You can even do something like throws like bar except ArrayOutOfBoundsException when you are handling some errors yourself.

magento2 – Save button does not return to admin grid

I have a plain old save button on an admin form, but it doesn’t return me to the grid after saving. It’s more or less a copy of MagentoCustomerBlockAdminhtmlEditAddressSaveButton.

What could be wrong?

class SaveButton implements ButtonProviderInterface
{
    public function getButtonData(): array
    {
        return (
            'label' => __('Save'),
            'class' => 'save primary',
            'data_attribute' => (
                'mage-init' => ('button' => ('event' => 'save')),
                'form-role' => 'save',
            ),
            'sort_order' => 20,
        );
    }
}

arrays – How do I return one object from returned lambda function in java?

I’ve implemented in java this lambda function which returns two objects:

int()()() array = { { { 1, 2, 3, 0 }, { 1, 2, 0, 3 } },
        { { 1, 1, 1, 0 }, { 1, 1, 0, 1 } },
        { { 2, 2, 2, 0 }, { 2, 2, 0, 2 } } };

int()()() sum =
        Arrays.stream(arr1).flatMap(Arrays::stream)
                .map(a -> new int()() { { a(2), a(3) },
                        { a(2) + a(3) } })
                .toArray(int()()()::new);

for (int()() a : sum) {
    System.out.println(Arrays.deepToString(a));
}

I came from world of C programming and just started learning java before 7months.
How do I print one of the objects that a has? I mean to print the first object seperately and second object separately. any help how do I implement that in java?
a has two objects first one is array, the other one is sum.
I tried to implement like this:

for (int()() a : sum) {
    System.out.println(Arrays.deepToString(a).first());
}

but it didn’t work..any help?

thanks

Why does nslookup return “non-existent domain” for hosts on my internal network?

My homelab network consists of the following relevant components: a VyOS router and a Windows Server (2019). VyOS is the default gateway, but Windows is the DNS server. VyOS, as the default gateway, provides the dhcp server, which I know is working. Everything within this network is able to ping each other as well as access the outside internet. VyOS has it’s system nameserver configured as the three IPs of the Windows server (there are three subnets involved). The Windows DNS server has three forward lookup zones and three reverse lookup zones, for each of the three subnets. In each of the forward zones, there are A records pointing to the IP address of my vcenter host (vcenter.(domain).net) in that subnet. In the reverse zones, there are pointers (PTRs) linking the ip of the vcenter host on that subnet to its hostname (vcenter.(domain).net).

Interestingly, when I run nslookup on the domain name only ((domain).net), it returns the IP of the Windows server, which seems promising. However, if I nslookup vcenter.(domain).net, it returns “(domain).net can’t find vcenter.(domain).net: Non-existent domain”. What piece of this am I missing? Why can the domain name be resolved to the IP of the Windows server, but host-name.domain-name cannot be resolved?

Edit: and if I simply type (domain).net into a browser, it is getting resolved to my public domain name (the same (domain).net that I purchased from a registrar and which points back to my public IP, which I can tell because the browser returns the public web page of my router). So the domain name is not getting resolved to my Windows server before it gets forwarded out to a public DNS.

air travel – Rules regarding the changing my return flight date on Belavia (Frankfurt -> Minsk -> Frankfurt)

I want to change the date of my flight back to Frankfurt from Minsk on Belavia. On their website it says:

Changes in the date, flight number and route before departure: Allowed for 30 EUR. Differences can be paid up to a higher fare or brand level.

Changes in the date, flight number and route after departure: Allowed
from 100 EUR. Differences can be paid up to a higher fare or brand
level.

I’m having some trouble with the language here. By departure, is it referring to my original flight from Frankfurt to Minsk? Or does it mean, for example if my return flight is on 20.01.2021, that if I change my flight date to 15.01.2021 then it’s 30€ + difference in fares, and if I change the date to 30.01.2021 then it’s 100€ + difference in fares?

Kind of confused here. I tried contacting them, but I couldn’t get through to an English speaking agent.

query – How can MySQL return an empty row matching a given table’s schema, given the table name as an input string?

How can a query or procedure return an empty copy of a new record?

Ideally suited for objects which are in a transactional allocation process:
It is highly preferable to have authoritative defaults and NULLS for arbitrary tables when constructing new objects() that may-or-may not ultimately be saved to the database.

For example, a CMS user relies on AJAX which calls for a new post() or new product() dynamically. Rather than trusting stored profiles to set values in the scripting language, a blank “instance” of a row would be rather useful.

php – Is having 3 return types for a function, in order to facilitate error handling a bad idea?

I have a function which returns either true/false, each return plays nicely with the function name: isOnline, however, there are cases in which I want to throw an error inside of it. Maybe the status server isn’t available or what-not. But the problem is, errors in PHP are not that well-supported, nor is the community to keen about them. A try/catchis a foreign concept to most, so, I need to return a custom ErrorObject. So, your code ends up looking something like this:

$online = isOnline();

if( !$online ) {
  return False;
}

if( gotError( $online ) ) {
  //Return the error or do something, execution stops here.
}

I personally like it. While verbose, I genuinely never found this level of error checking to be exhaustive or to slow-down development, but a function that has more than 2 return possibilities just feels wrong.

Is there any literature/thoughts about returning errors?

gui design – Best practice for meaning of “return” in UI flow

For context in this question, I am recalling a programmable thermostat interface with four large buttons, two each on the left and right side of an LCD display. The display showed labels for the buttons, which changed depending on the mode. At a particular place in the “programming” sequence, the center of the screen had a flashing “Monday / Leave / 19C ” with “10:30” not flashing and the labels next to each button were: “Return” (upper left), “Save” (upper right), “-” (lower left) and “+” (lower right).

Does that upper left label mean “return” as in the common sense of “go back to where you were before / the previous step?” Or does it carry the programming sense of the word, “take this value back and continue to the next step?” On many keyboards, it seems the “return” key (also sometimes called Enter) is closer to the latter meaning. In this particular context, it could also mean “Instead of programming the ‘leave’ temperature, switch to programming what the temperature when the occupant returns/comes back into the space, when the temperature setting should return to what is desired for when the space is occupied.”

From this interface, it seems that pushing the + and – buttons would adjust the time set temperature but it’s not clear exactly what the meaning of “return” should be in UIs. In the particular instance motivating the question, the user had a very young child who had pressed some of the buttons on a thermostat the user did not have permission to program. The user wished to cancel out all recent changes and return to the previous state, without having personal memory of what all that state was, and the interface did not appear at all clear about how to accomplish that, if it was even possible.

Are there any standards or best practices published on this?

windows 10 – Automatically restart USB audio device after return from standby

I have a speaker system with a built in USB audio interface connected to my PC.
When the PC returns from standby, audio output is not working, even though the device is shown as audio output.

To get audio output again, I have to manually select another source than USB on the speaker system, and then switch back to USB.

I’d like to automate this on my Windows 10 system, so that after logon the USB device is automatically disconnected and reconnected.

I understand that this can be done using the Task Scheduler and a batch file that runs devcon.exe from the SDK, but when I enter “devcon disable “USBVID_154E&PID_1004″” it demands a reboot.

“devcon restart” demands a reboot, too.

Is there a solution for my problem?