Loop over files to check if param is present, if not, add it with default value

Question: For deployment process i have to go through a list of configuration files, and for each i have to check the presence of parameters, and if they are not present add them to the file
It's not just replacing the line by a default line with lineinfile, the parameters can be modified by hands and in this case i must do not change it by a default value and keep the actual.
In my role/defaults/main.yml i had created a list of files with params and default values to check
example :
<code>webui_test_conf_files:
  - file: '{{ common_pms_workspace_path }}conf\conf-PROD.properties'
    param: 'printing.timeout'
    value: '{{ webui_template_configuration_vars.confPRODpropertiesj2.printing_timeout }}'
  - file: '{{ common_pms_workspace_path }}conf\conf-PROD.properties'
    param: 'period.bom.check'
    value: '{{ webui_template_configuration_vars.confPRODpropertiesj2.period_bom_check }}'
  - file: '{{ common_pms_workspace_path }}conf\conf-PROD.properties'
    param: 'enabled.bom.check'
    value: '{{ webui_template_configuration_vars.confPRODpropertiesj2.enabled_bom_check }}'
  - file: '{{ common_pms_workspace_path }}conf\sso-conf.properties'
    param: 'user.redirect.url'
    value: '{{ webui_template_configuration_vars.ssoconfpropertiesj2.user_redirect_url }}'
  - file: '{{ common_pms_workspace_path }}conf\sso-conf.properties'
    param: 'authorization.endpoint'
    value: '{{ webui_template_configuration_vars.ssoconfpropertiesj2.authorization_endpoint }}'
  - file: '{{ common_pms_workspace_path }}conf\sso-conf.properties'
    param: 'token.endpoint'
    value: '{{ webui_template_configuration_vars.ssoconfpropertiesj2.token_endpoint }}'
</code>
For every file (two in this example) i have to test the presence of each param.
if there is no occurence of this param, then add line in the file with : param=value
but if i found the param, i must do nothing for this one :-)
For now i can test and register the test like this
<code> - name: "Testing parameters"
   lineinfile:
     path: "{{ item.file }}"
     line: "{{ item.param }}"
     state: present
   check_mode: yes
   register: params
   loop: '{{ webui_test_conf_files }}'
</code>
But i do not succeed to use this registered value to do another loop :-(
Can you help me ?
Thanks a lot for your help !
Comment: `But i do not succeed to use this registered value to do another loop` => what is the exact problem you are facing? How did you try exactly? What is the error you get? How does the actual result differs from the expected one? Is it simply a problem using the registered results or the result itself which does not contain what you expect? Please [edit](https://stackoverflow.com/posts/68271414/edit) your question to add more details about your implementation.
Comment: Sorry, in fact i do not find how to do this second loop...

for me i need to loop over each file a second time and update the file if params.rc != 0
Comment: Did you debug `params.results` to have a look at what it contains exactly? => all the results from the previous looped task in a list, each of them containing info about the task as well as an `item` entry with the original data that was used inside the loop. If you loop over `params.results`, `item.whatever` contains your task data (replace with an actual var from the task), and `item.item` the initial data.
Comment: item.item ! i do not know this one :)
thanks i will try this right now ^^
Comment: Without knowing, you just have to observe the data => `- debug: var=params`
Comment: Thanks for the tip, i didn't think to simply use debug .... my bad :-(
Comment: Regarding the `results` entry when registering a variable with a loop, read this: https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#registering-variables-with-a-loop
Comment: Please do not add large portions of code in comments, they are not made for this. [edit your question](https://stackoverflow.com/posts/68271414/edit).
Answer: Success with this code for windows test :-)
<code> - name: "Test parameters"
   win_shell: (Select-String -Path "{{ item.file }}" -Pattern "{{ item.param }}=")
   register: params
   check_mode: no
   ignore_errors: yes
   changed_when: no
   loop: '{{ webui_test_conf_files }}'

 - name: "Add missing parameters"
   win_lineinfile:
     path: "{{ item.item.file }}"
     line: "{{ item.item.param }}={{ item.item.value }}"
     state: present
   when: item.stdout | length == 0
   loop: "{{ params.results }}"
</code>
Thank you @Zeitounator for putting me on track !


how to keep an UIImage from disappearing after an app resumes from a background? (iPad)

Question: I have an UIImage* loadedPoofSprite which I initialize like so:
NSMutableDictionary* loadedDictionary=[NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",Main_Bundle_Path,poofConfigFileName]];
NSString *textureFileName = [[loadedDictionary objectForKey:@"metadata"] valueForKey:@"textureFileName"];
loadedPoofSprite = [UIImage imageNamed:textureFileName];

poofImage = [[UIImage imageNamed:textureFileName] CGImage];

From there I use my poofImage and everything seems fine till my app resumes from a background. I get a crash 'cause loadedPoofSprite is gone. I thought the way to avoid this would be to retain loadedPoofSprite like so:
[loadedPoofSprite autorelease];
loadedPoofSprite = [[UIImage imageNamed:textureFileName] retain];

This works but I was suggested it's not the right way to do it and I should basically load loadedPoofSprite again in applicationWillEnterForeground. I don't understand why it's better to load it twice instead of retaining it. What would be a right approach to deal with the above?
thanks!
Answer: If you would make loadedPoofSprite a retained property, and assign it like:
self.loadedPoofSprite = [UIImage imageNamed:textureFileName];

then all will be fine. A retained property is declared using
@property (nonatomic,retain) UIImage *loadedPoofSprite;

and you need to generate a getter/setter using
@synthesize loadedPoofSprite;

Then in the dealloc routine, add self.loadedPoofSprite = nil; to release the image when needed.
Answer: You don't specify what you do with your loadedPoofSprite/poofImage.
Possibly the problem is not related to retain/release: e.g., if you add the image as a subview to another view (through an UIImageView), your image is automatically retained by the framework, so retaining it yourself should not be required and could prevent unloading it when the system needs it.
Indeed, it is possible that your application, while in the background, is affected by the system attempting to recover memory for the benefit of another app running; in such case, your views would be released, possibly deallocated, and on resume to foreground, your app would not find its views. Hence the failure.
If my reasoning applies, you will need to check whether your UIViews are there and be prepared to reload/recreate them as needed (as specified by the docs about didReceiveMemoryWarning/viewWillLoad/viewDidUnload).


How to mock an array in RSpec?

Question: I am trying to mock an array in RSpec (in the app it's a return object from an external API), yet I don't know how.
I tried mocking it like this:
item = double("item")
item.stub(:[]) { :return_value }

which works, but then I'll get :return_value for each value in the array.
Is there another way?
Comment: i know a solution is to wrap the return object from the API in a wrapper and then mock it instead, but I'm trying to avoid it.
Answer: I think you don't need to generate test doubles for array, they will add unnecessary complication to the code of your tests. You can just create fake array and use it later:
items = [:return_value1, :return_value2]

In case if you need to stub method and return different results for first and subsequent calls, you can do this:
obj.stub(:method).and_return('1', '2')

In this case obj.method will return '1' when it is called for the first time and return '2' for all subsequent calls.
Also, as far as you use block for stub, you can dynamically calculate return value in this block. But this is considered to be not very good practice because idiomatically stubs should return static data.
obj.stub(:method) { Time.now }

Comment: duh, didn't think about the easiest way of just creating an array. thanks

How to mock an array in RSpec?


Non clickable breadcrumbs to show a user's place in a booking process?

Question: I have a case where there is a multi-step system that a user goes through, like an in depth booking process.
For example the user has to go through 6 steps to complete the booking, the system currently has what looks like breadcrumbs showing their place in the process (they are dynamically generated and named accordingly).
For example if the user is on step 3 of 6.
step-1 >> step-2 >> step-3 >> step-4 >> step-5 >> step-6
My argument is that this is not only trivial but distracting. The "breadcrumbs" or "visual steps" look like links, yet they are not. Also why does this information even matter?
Have there been any studies or discussion on this UI element.
ps. It reminds me very much of the "you are here" arrows you see on a map, but in the case of booking , I'm having a hard to finding out if it's actually as useful.
Answer: The use of the progress bar pattern is helpful if a user would benefit from knowing where they are in a multi-step process.  As you noted, it should not be styled to look like links if it is not clickable.
Here's an example from the Yahoo Design Pattern Library:
Comment: +1 though I would still be tempted to click those process step arrows in your picture. :)
Comment: @JOG you would be able to click the different step arrows once you have visited that step of the process. You just can't "fast forward" yourself to the end.
Comment: Of course, though the breadcrumbs the OP described "look like links, yet they are not".
Answer: Personally, I find a long series of wizard like windows wearisome. But it depends on the application and my expectations. A casual, once-in-a-while user who has a significant number of alternatives may get frustrated by the 4th or 5th step and exit the process. A frequent user or a user who is accustomed to such wizards in their industry would be far more tolerant.
Some kind of status indicator also conveys both how much work is left to be done and how much has been accomplished. This works in your favor in two ways. First, giving your user a light at the end of the tunnel gives them hope and assurance (as said, depending on the user's expectations). But second, if you have a user who is not accustomed to many-screened wizards, showing them how much they have done gives them a vested interest in finishing (via ye olde "sunk cost" psychology). If you are worried about losing a customer, showing them how much they have already invested can help convince them to stick it out a little longer (although this is not infinite, so getting the number of screens down to a minimum is essential).
Personally, I have always favored the progress bar which uses images or animation rather than boring text, just to keep me engaged and interested. For example, you could use a series of images (preferably of people) acting out what the process would look like in the non-digital world. Then, gray out all but the step you are currently on. It would give the user a connection with the real-world process and help them to justify the time they are spending on the computer. People are notoriously less patient with a computer then they are with real-world processes, so a subtle reminder of how long they'd be willing to wait in the real-world might help to keep them a little longer.
I can't give you any specific studies on the progress bars effect on a user's psychology, but I think if used correctly they can be a very useful and powerful visual cue to connect him or her with the abstracted process which is mostly invisible to them.
EDIT: As a side note, if you are not giving them a way to correct a mistake on a past window, but rather forcing them to restart the entire process, then you are much more likely to lose them over something as simple as a mistyped street name. The ability to go back in a multi-step process is extremely valuable. You may want to consider investing in such a capability.
Answer: Research shows that its better not to depend on breadcrumbs as user might not use it effectively. But in your case if you create visual design not look like just a link, expected result can be achieved. It should be made look like a section instead of having plane text.
Comment: I find usability.gov research to be weak. One article written by Heidi A. Uliasz concludes completely opposite of the research she cites in her article. She provided absolutely zero support for her conclusion. Did she misread the research? Or just make her own conclusion?
Comment: @mawcsco - Its interesting to know your point of view. But as this is an official U.S. Government Web site (managed by Dept of Health & Human Services); I consider it to be good. Even the book 'Research-Based Web Design & Usability Guidelines' which is US Govt official edition, seems to be covering guidance on lot of UX issues, with the help of research citation mentioned for each module. I do agree that the site and this book needs to be updated to align with recent industry changes. The site has many articles by many authors. Doubting it due to someone seems a bit irrelevant.


automatic mail generation in cocoa from server side

Question: I don't have any idea for generating automatic emails using cocoa from server side. In every link they have given only by using applescript. Can anyone please suggest me with some ideas for generating mails from server side? Thanks :)
Answer: Here is an example of sending an email by using the Mail.app. Pretty sure you can send it with out a gui if thats what you need to do too.
What you ask is pretty vague, but I think this is what you were looking for. As for set mail() script which is available in something like PHP, there is none that I know of.
Comment: Thank u :) But here we have to be synchronized with Mail app. Do we have any other way to send an automatically generated email from server side?
Comment: That example uses Mail.app to send the email. What do you mean by synchronized?
Comment: The user's mail account should be valid under 'Mail' app right?
Comment: I would believe so, or at the very least have an account that is setup  in it.
Comment: So can't we do it without using Mail app?
Comment: you can, but you would need to program a whole lot more. It is not as simple as you want it to be like applescript or php.
Comment: Can you provide me any idea for implementing this?


Mutually exclusive Switches

Question: The software I am designing for has 3 functions, which can be turned on or off with Switches. However, due to how the software works, the following rules apply:

At least one function must be enabled at all times.
Switch (C) cannot be enabled together with (A) or (B).

The current implementation looks like the image below. If you enable (C) then (A) and (B) will be disabled automatically, and vice-versa.

I'm not very happy with this though. I wish I could make it clearer to the user that C is mutually exclusive to A and B.
Perhaps Switches are not viable? Perhaps I can add something before or after the switches that indicate their relation? Spacing? Grouping?
I'm out of ideas.

Edit:

We previously had the above design but abandoned it because we wanted to display contextual options in an expandable section below each option (i.e checking A would give you configuration options related to A. Same for B and C. The "tree" nesting/indentation would get too big, which is why we decided to lift all options to the top-level.
Comment: Please get rid of the switches.  It is hard to tell which is meant to be on or off.  It is always a guessing game.  Does left mean on or does right mean on?  They are a bad idea, and should never have been invented as GUI elements.
Comment: Ah, switches. Destroying usability since 2005. Back then, we had radios and checkboxes, which were clean, simple and obvious.
Comment: @JRE I beg to disagree. Perhaps they are a bad fit for this particular problem but they have been used in both android and iOS for well over a decade and nearly everone has a smartphone. These are not new daring concepts anymore. They are standard. I also find it exceedingly hard to believe that anyone does not know which state above is on and which one is off.
Comment: To my way of thinking, when the switch nub is towards the text then that function would be active.  If the GUI switches had a marking (text label) on both sides, then it would be obvious.  The function in the description nearest the nub would activate.  GUI switches are ambiguous, though.  Only one side is labelled.  You all seem to think "nub away from the description is on," but that's the opposite of the way real switches work.
Comment: Check box and done.  Much clearer.
Comment: If all options are visible on a screen close together, the user will immediately see what happens after he clicks option C (A and B are automatically disabled). If there are configurations between the options this behavior will be a lot more opaque, since pressing one of the options will completely change the whole page-layout (configuration sections disappearing and appearing) which will make it very hard to process or reason about what exactly is happening.
Comment: I don't.  The colors are not standardized in any way.  Is left on or is left off?  Damifno.  I am posting from an Android phone.  It uses the stupid switches.  The only thing that makes them halfway useful is that something obvious usually changes when you change the state of the switch.  Manual switches (hardware, like light switches) have labels on both sides **and** something obviously changes when you flip the switch.
Comment: Relevant: Material Design's guidelines on checkbox and switch usage.
https://material.io/components/checkboxes#usage
https://material.io/components/switches#usage
Essentially, switches are better for isolated, immediately-applied changes (like a light switch activating a light).
Comment: @JRE So you have a gray color and a light blue color but you cannot tell which one is meant to signal "off"? The illuminating side is obviously communicating "on". Even the switches in your car work that way.... In addition, I've never seen a switch where you flip it to the left to turn it on. I've only ever seen Left = off and Right = on.
Comment: What is the default background color?  Blue or gray? You think it is obvious, but it isn't.  For all I know, gray is the on color.
Comment: @JRE I'll agree with you that they are misused a lot. But that does not mean they are bad. Here's how I would use a switch with text only on one side (unrelated to OP): *Allow us to collect of anonymous usage data* [Switch]. Or even: *Airplane mode* [Switch]. I think these are clear anyway.
Comment: @JRE for all I know a square with a tick symbol in it means "off".
Comment: @Chris I believe you when you say you've "never seen a switch where you flip it to the left to turn it on." This is the reason why it is often good to make decisions about what makes sense in a UI by consulting others with more experience in that area. (In the meantime, consider referencing an [Android phone menu in Arabic](https://i.imgur.com/5BTebba.png) for a digital example, and [this circuit breaker panel](https://images.tmbi.com/wp-content/uploads/wwwroot/tfh/projects/apr17_reset_breaker_1.jpg) for a real-world example.)
Comment: Regardless of how the breaker panel is installed, the direction which is `on` is different for each column.
Comment: @JRE Checkboxes semantically only mean a selection of something and are almost always accompanied by a save button or some other control input. They should rarely be used on their own. Same thing with radio buttons.
Comment: @TheRubberDuck Exactly. Checkbox here is not better than Switches, despite what people might say in the comments. This is a well researched topic by the largest UX teams in the world and applied to tens of billions of devices. Like, there is no debate to be had really.
Comment: @Chris I'm not really here for the debate, which probably has its own UX.SE question(s) anyway. It's probably too vague to say with generic labels like "Option A". I could see it either way, personally.
Comment: @TheRubberDuck I know. I was commenting generally.
Comment: @Chris I'm confused, you seem to be implying that your switches have immediate action, no save buttons, etc.? But then it also seems like there's a whole page for this, with multiple sub-configurations below A, B, C....wouldn't that typically have a Save button?
Comment: Also, I'm confused about the complaint that it was too big. The nested version seems to be adding one line vertically and one tab of indentation horizontally...which isn't really a huge increase in size. Is this meant for some mobile application where screen size is expected to be very small?
Comment: @user3067860 No, all inputs have immediate action. The application is mainly desktop, but 2/3 of the screen is occupied by a large video player. The player must be displayed along with the configuration options as these directly affect the video. So in a way, yes, space is somewhat limited.
Comment: @user91655 we have a colorblind mode for this exact problem. No solution is perfect.
Comment: @cjs Some languages are read from right to left, so of course the control is reverted there too. We're talking about general UX solutions and not localization-specific issues. Surely you understand that I am generalizing. The experience of many here is really up in the air for me when they are trying to argue that Switches are the worst without knowing exactly how they are used in this context. If they truly were so bad, how come Apple - probably the single most influential UX body in the world - still has them?
Comment: @cjs In addition, we have had usability tests with several dozen people. While that's not really that many, not a single person ever hesitated on how to use the switch. It feels to me that some (not everyone!) are only here to make an argument based on a controversial topic and to look smart, rather than making a strong argument for their opinion. Instead, people resort to ridiculous claims, like, they don't know if the blue means off or on. We've had these controls for **at least** a decade, and any other allegation is in my eyes just a troll - especially if you frequent these forums.
Comment: @cjs by the way, that circuit breaker panel is mounted sideways lol. Judging by the labels, on was meant to be "up" and off "down".
Comment: @StvnW ah yes, indeed. Speaking of great UX :D
Comment: @Chris _"If they truly were so bad, how come Apple - probably the single most influential UX body in the world - still has them?"_ Becuase Apple's priority is to make things look cool, which often leads to compromises in UX design, as Bruce Tognazzini (you know Tog, right?) and others have been [explaining for more than a decade now](https://www.fastcompany.com/3053406/how-apple-is-giving-design-a-bad-name).
Comment: Note that this is not Apple taking a "wrong turn" at some point: Apple started making things more "minimal" at the cost of usability from the very start. Consider the single-button mouse: it has to cover the functions of at least two of the Altos mouse buttons, but unlike two or three buttons, has only one obvious affordance. So they had to hide additional functionality under the "double click" (something completely unknown to users at the time) and drop the useful context menu functionality.
Comment: @Chris And also, no, the ciruit breaker panel is not mounted sideways, it's mounted in the most common orientation for such panels (and there are good reasons to mount it in that direction). You're now just proving that you're willing to make pronouncements on things you know little about.
Comment: @cjs You brought in a circuit panel which has text and labels in three different orientations to make a case example of good UX. I have to turn my head sideways to read what the switches do, but hey "here is an example where a switch in the "left" position means "on". How many can relate to that brilliant UX compared to millions of UI's. You want to make a case example for the 1% to look smart? Go right ahead.
Comment: @cjs You're also making pronouncements about the research we've done. How many usability tests we've done. How many UX designers are involved in my team. What UX knowledge I have. Maybe I just came here to get a second opinion? As you can see from the different proposals posted here, there is no obvious solution.
Comment: @cjs I find checkboxes difficult to use. Switches can be bad **if used incorrectly**. As with everything. I'm done with this conversation. I already asked you to stop once. I'm gonna ask you politely again. Unless you have *an actual answer* to post down below, kindly refrain from commenting.
Answer: The way I see this is that you have two exclusive groups of options, it just happens that the second group only contains one option.
Something as simple as the word 'or' will help a lot - that way it's unambiguous as to the grouping.
Comment: I see this as the nicest design but it is still missing something. It does not explain the user that either C or one of A,B must always be selected. ------ Also how it should behave when the user tries to change the switches to an unsupported combination? For example in the state as shown above: a) turning off A - should it be blocked (not obvious from the appearance) or should it turn on B or C? b) turning on C - should it turn off A and B (and forget their state)? ------ I think that flipping an on/off switch there and back in a well designed GUI should not change other settings.
Comment: @Chris - is it possible for you to tell us the true labels of these options? I think having the right context would open up other solutions that make more sense.
Comment: Thanks. I wish I could use this approach but with all options stacked.
Comment: Ah - that's interesting, @pabouk, I hadn't even considered that. You make an excellent point about how to handle turning off C. In that case, [musefan's approach](https://ux.stackexchange.com/a/141271/30287) covers all the requirements.
Answer: Your constraints limit you to only four valid choices:

A and B
Only A
Only B
Only C

I would just use a set of 4 radio buttons.
Comment: I feel like this would be tricky for the user to parse if the labels were at all complex. Presumably they're not going to be called 'Option A, B, C' in the real system.
Comment: If a simple pairing of two options is too complex, each of the two options is probably too complex as well.
Comment: @Chris: So the solution also needs to work for potential future extensions? If that's a requirement for answers you should emphasize that in the question.
Comment: This approach is not bad but will become a problem in itself if the system gets a 4th option in the future.
Comment: @chepner Most of other approaches will also require rework if a fourth option is added which can be combined with existing options.
Comment: Yes, but that is a problem for if a new option gets added. If you *expect* that to happen, then it would be better to prepare for it than to require an overhaul to the UI.
Comment: @chepner you never know with product owners ;-)
Comment: @Schmuddi There is no answer to that. The nature of software is such that unforeseen changes and additions can rarely be entirely excluded. Flexible designs are many times preferred for this very reason. In other words: I'm not to say what is to be expected in the future.
Comment: I like this solution because there's no ambiguity (as in "is this a bug or what happens with these switches that are disabled randomly?"): clearly, all the available options are actual options that are deliberately offered.
Comment: @Chris This approach only becomes a problem if the system gets a 4th option _and_ you refuse to revise the design beyond adding another switch when it gets the 4th option. Why would someone already modifying the design deliberately make it worse when he could just as well make it better?
Comment: @cjs Revising designs are costly and it's if there is a solution out there that does not require a revision, wouldn't you agree that would be the best solution? Every solution has benefits and drawbacks. This design has many benefits but it also has this particular drawback. What I meant by a 4th option wasn't a 4th option in the set of radio buttons, but rather a 4th "letter". With the same rules (all combinations are valid, except C which can only be selected alone), you would now have 8 choices rather than 4. 8 radio buttons seems like too much to me.
Comment: @Chris Revising designs like this should not be costly; software developers have spent decades working to make changes like this cheap. If it's still expensive for a team to make simple changes like this they have a large problem that's going to be hurting every part of their UI, since there are always plenty of changes you _didn't_ anticipate.
Comment: @cjs cheap is relative
Answer: What I understand from the question is that A, B, and C are independently selectable but selecting C disables A or B.
What is the way to graphically show three selectors where one is linked to the other two?

Or how to graphically show the link:
Comment: Also please never use radio buttons as checkboxes.
Comment: I think this GUI would give me the opposite signal.  Radio-buttons usually imply mutual-exclusivity within a group, so grouping two radio-buttons together makes them look mutually-exclusive (rather than mutually-compatible).
Comment: Another variant I've seen of the second example is a background color highlight that moves behind whatever set of elements is active, with the inactive elements greying out. Bonus points for a rudimentary CSS animation.
Comment: The latter design is nice and pretty clear I think. Though each option has contextual parameters that can be set. I think your design in combination with the latter suggestion from @musefan could work. Thanks!
Comment: This will just tell me that A and B are linked in some way (possibly both part of some logical group or category), but I would only figure out that it has anything to do with mutual exclusivity after switching the switches a few times (after I get past the initial confusion of having one switch disable another). Putting an "OR" between the two (i.e. combining this with the top-voted answer) would make what's going on here much clearer.
Comment: This seems to be more something that will make sense after a user's already figured it out ("oh, so that's why there's a block around those"), rather than something that clearly conveys a meaning, which isn't really ideal in UIs (unless you use the same thing in many other places).
Comment: If the first layout would be used, I'd probably expect the region around Option A and Option B to itself a radio-button, while Options A and B within it would each be a check-box.
Comment: This has the same problem as some of the other designs, where it's not clear what is supposed to happen if you have, say, C selected and then you try to turn off C. (Should both A and B turn on? Only A? Only B? You just can't turn off C?) I think radio buttons are the only design element we have that means "you must select at least one".
Answer: Option 1
Note: this was the original answer before the question was updated (see comments).
I think what you essentially have here is two groups. You have the "A and/or B" group, and you have the "C" group.
Only one group can be selected (so use radio buttons). However, if you pick the first "A and/or B" group, then you have sub-options that allow you to select either A or B or both (use checkboxes).
So I would recommend a design similar to this:

Note that it is hard for me to give you a good example of what the text should say, as your example is very generic, but hopefully you understand my point and can apply some more sensible text based on your actual specification.

Option 2
After your comment that you require additional configuration options to appear depend on the selected options.
I would suggest that rather than trying to make the advanced options appear inline with the root options, separate it into a "2 step" process:

Step 1: Select which options you want to enable
Step 2: Configure each of the selected options

You could make this a 2-page wizard, or you could simply put it on the same screen/page but as individual sections.
Something like this. Where the configuration options panels dynamically appear based on which root options the user selects.

Option 3
You might consider having the configuration options as a modal form. This would allow you to keep the initial options screen much simpler. Depending on your validation requirements for the configuration options, this may not be the best approach. But if additional configuration is optional (i.e. defaults are provided for all config options already) then it could work well.
Comment: @Chris I think this is important information that you should include in your question. The whole concept of "automatically disabled other options" only really works if the user can see all options on screen at once. If you have a risk other config options pushing the main options off the screen, it's not wise to use a toggle approach. I do have another idea though so I will update my answer.
Comment: We actually had this exact design before but abandoned it because we wanted to display contextual options in an expandable section below each option (i.e checking A would give you configuration options related to A. Same for B and C. The "tree" nesting/indentation would get too big, which is why we decided to lift all options to the top-level. Thanks for your input!
Comment: Thanks for the update as well. Not a bad idea. What happens when the user selects C? The right-hand cards are replaced by the corresponding one for C?
Comment: @Chris. Yes, in that instance you would only see the config options for C. Likewise, if the select only A, then they see only config panel for A. In a "mobile" screen view, the panels can appear below the options panel, so that works too. I will also add a 3rd idea which may or may not be suitable depending on your logic for config options.
Comment: Another issue with this sort of design is that while it's clear that options A/B are not compatible with option C, it's not clear that at least one of A or B must be selected.
Answer: I think your initial instinct to use radio buttons (and as suggested by @musefan) for the primary alternatives is the semantically correct choice. (Whether to use switches or checkboxes for the secondary options can then be left open to debate...)
There are ways to achieve the visual grouping other than indentation that will retain the full horizontal width to use for displaying more information or sub-options. Here is one possible suggestion:
Comment: This suggestion is, in my eyes, as good as you can get it. It's a nice balance between semantics and function. It could use some polish, but I think it's an excellent starting point. Thank you!
Answer: Many of the custom home builder sites offer options on their plan viewers.  They tackle this swapping the slider control to a stop sign on the mutually exclusive item.  Any sub-items appear with the main slider selection.
Nothing Selected:

Mutually exclusive item, with sub-item added:
Comment: This doesn't address the requirement that B is independent from A (So you could select the Outdoor Kitchen without first selecting the Patio). It's a good approach for sub-options, though.
Comment: I was more trying to highlight the visual cues that some items were mutually exclusive.  There isn't really anything obvious that they are mutually exclusive until you start clicking around.  Toggling things on/off can be fun.  Not sure you *have* to spend a ton of time indicating things are mutually exclusive to the users when most likely they are going to just start toggling options to play around on the screen anyway.
Comment: Sometimes play/exploration is good, but I think it depends a lot on the context of the application. House designer, yes definitely.
Answer: You can try a dropdown (or radio buttons) with clear choices:
<code>Please choose your options:
- A
- B
- A and B
- C
</code>
You only have these four options when I understand your post correctly. So don't increase the user's mental load through unusual and complex UI, but provide a simple list, even when it has one item more than the other possible solutions.
Answer: If you're willing to make a new control, designed for this precise task, you could make it look and behave like this animation:

As you can see, it allows only the combinations you have requested, but it would require more programming than would an arrangement of premade controls. If A, B and C are longer than single letters, you could either add a key just below, or have it vertical rather than horizontal and put descriptions alongside.
You will have to think carefully about accessibility features for users with visual impairment: description, feedback on change of selection that would have to work with a standard screen-reader. Keyboard control should be easy, though: arrows!
Comment: Interesting design! Quite a daring concept, but pretty good nonetheless. Thanks

Mutually exclusive Switches


React: Props sent by parent are not the same received by child

Question: Basically the title sums it all, I'm sending a prop to a child and comes different. I make a console.log just before rendering of parent and the prop is OK and make a console.log of same prop at the beginning of Child component and it's different.
This is the parent:
  const Main = () => {
  const carrier = createShip(5);

  // Gameboards setup
  const userPrimaryGrid = createGameboard('primary');
  const userTrackingGrid = createGameboard('tracking');

  userPrimaryGrid.randomPlaceShip(carrier);

  console.log(userPrimaryGrid.array);

  return (

      <Gameboard
        type={'primary'}
        board={userPrimaryGrid}
        enemyArray={computerTrackingGrid}
      />

  );
};

export default Main;

And this is the child (I removed mostly everything from child because after receiving the prop wrong everything else is wrong, when I use a mock prop it works):
const Gameboard = (props) => {

  console.log(props.board.array);

  return (
    <div className={`gameBoard ${props.type}Board`} onClick={props.onClick}>
      {squaresArray} <== this depends on board.array don't worry

  );
};

export default Gameboard;
I have a suspicion it has something to do with the randomPlaceShip method in parent, because what I receive in child is an array different from the parent one but as if it had its own randomPlaceShip (with  another result). The randomePlaceShip method is the following:
const randomPlaceShip = (ship) => {
    let direction = '';
    let randomDirection = _.random(0, 1);
    let x = _.random(0, 9);
    let y = _.random(0, 9);

    randomDirection === 0
      ? (direction = 'horizontal')
      : (direction = 'vertical');

    console.log(x, y, direction);

    let position = false;
    while (position === false) {
      if (direction === 'horizontal') {
        if (y > 10 - ship.length || array[x][y] !== false) {
          console.log(`cant place ship in ${x},${y}`);
          randomDirection = _.random(0, 1);
          x = _.random(0, 9);
          y = _.random(0, 9);
          randomDirection === 0
            ? (direction = 'horizontal')
            : (direction = 'vertical');
          console.log(x, y, direction);
        } else {
          for (let i = 0; i < ship.length; i++) {
            ship.hitPoints[i].x = x;
            ship.hitPoints[i].y = i + y;
            array[x][i + y] = ship.hitPoints[i];
            position = true;
          }
        }
      }

      if (direction === 'vertical') {
        if (x > 10 - ship.length || array[x][y] !== false) {
          console.log(`cant place ship in ${x},${y}`);
          randomDirection = _.random(0, 1);
          x = _.random(0, 9);
          y = _.random(0, 9);
          randomDirection === 0
            ? (direction = 'horizontal')
            : (direction = 'vertical');
          console.log(x, y, direction);
        } else {
          for (let i = 0; i < ship.length; i++) {
            ship.hitPoints[i].x = i + x;
            ship.hitPoints[i].y = y;
            array[i + x][y] = ship.hitPoints[i];
            position = true;
          }
        }
      }
    }
    console.log(x, y, direction);
  };

The console.log within the method matches on what I get in parent; however, in the child component which apparently gets another go to the method won't show me that console.log so I'm not sure if it's really running the method.
Comment: I suspect that you are mutating the data, probably here? `array[i + x][y] = ship.hitPoints[i];`  But `array` is `undefined` within that function so something got lost in your editing.  Any data that changes, such as ship positions, needs to be stored in React state and updated via `setState` calls in order to trigger re-renders with the correct data.  Instead of a function `createGameboard` you might want to make a hook `useGameboard` that stores its state internally in a way that React can understand.
Comment: That's right, in the end I managed to make it work using `setState` and `useEffect`. I believe it wasn't an issue of mutating the data but something like rerunning the `randomPlaceShip` function somehow again. I'll post how I did it so you can check if it's more or less what you recommended.
Answer: I managed to solve it, as Linda also commented, by using setState.
This way:
  const [boards, setBoards] = useState({
    userPrimaryGrid: createGameboard('primary'),
    userTrackingGrid: createGameboard('tracking'),
    computerPrimaryGrid: createGameboard('primary'),
    computerTrackingGrid: createGameboard('tracking'),
  });

  const [gameFinished, setGameFinished] = useState(false);

  const [result, setResult] = useState('');

  useEffect(() => {
    fillBoard(boards.userPrimaryGrid);
    fillBoard(boards.computerPrimaryGrid);
    setBoards({
      userPrimaryGrid: boards.userPrimaryGrid,
      userTrackingGrid: boards.userTrackingGrid,
      computerPrimaryGrid: boards.computerPrimaryGrid,
      computerTrackingGrid: boards.computerTrackingGrid,
    });
  }, [
    boards.computerPrimaryGrid,
    boards.computerTrackingGrid,
    boards.userPrimaryGrid,
    boards.userTrackingGrid,
  ]);

In this case the function fillBoard contains the function randomePlaceShip done to all of the five ships required to play.
Comment: I think you are still mutating state because you are just calling `fillBoard(boards.userPrimaryGrid)` and not assigning that result to any variable.  Any time you change a board object you need to return a new version of the object.
Comment: I see! I'm going to revisit that, since the `fillBoard` affects what's inside the boards (which are the arguments) I didn't think it needed to be assigned to a variable. I'm gonna check that, thanks!


Using Reflection to get a variable's name

Question: I'm using MVVM and within one of my VM's I have an IsEditable property (well they all do from a base class) which is used by a series of buttons to determine whether their commands can fire.
This VM also has a sub VM for which I need to echo this IsEditable property down to, currently I'm overriding my OnPropertyChanged method to check if the property being refreshed is .Equals("IsEditable").
I've got a nagging which is telling me this isn't really good practice, if this IsEditable is renamed in the future then this functionality will break silently. Is there a better way to do this, or to be able to use the property name with reflection, e.g.:
if (propertyRefreshName.Equals(IsEditable.Name))
{
    // Echo down IsEditable change....
}

Comment: Using reflection in time critical code is usually not a good idea because it can be very slow.  It sounds like you will be running this in the UI thread.  The slowdown might not be noticeable at first, but over time you may notice your app start to crawl for no obvios reason.  I would recommend a notification mechanism like Reed suggests.
Answer: You could, potentially, use the same trick with expressions that people use to implement INotifyPropertyChanged.  Eric De Carufel blogged about this.
If you use the same technique, you could write your code as:
if (IsPropertyName(() => this.IsEditable, propertyRefreshName))
{ ... }

This would just require implementing a function to check the property name, but let you do it in a way that doesn't use hard coded strings.
Comment: Your link has `_22` in it that breaks it. Should be http://blog.decarufel.net/2009/07/how-to-use-inotifypropertychanged-type.html
Comment: Hrm... Both are working for me.  The _22 is the revision from the day after...
Comment: I get "Sorry, the page you were looking for in the blog Eric De C# does not exist" when going to it.
Comment: very odd - it's working here for me, with no issues.
Answer: Try an extension method to get property names off of objects
public static class ObjectExtensions
{
    public static string PropertyName<T,TOut>(this T source, Expression<Func<T,TOut>> property)
    {
        var memberExpression = (MemberExpression) property.Body;
        return memberExpression.Member.Name;
    }
}

Then in your OnPropertyChanged add
if(propertyRefreshName == this.PropertyName(x => x.IsEditable))
  SubVM.IsEditable = IsEditable;

Answer: I agree with statenjason.
Unless I'm mistaken, in my own experience I learned that the body of the expression tree is not always a MemberExpression (it can actually be anything) so there is more code needed.
Refer to the GetMemberExpression method in the following code from the FluentNHibernate project:
http://github.com/jagregory/fluent-nhibernate/blob/master/src/FluentNHibernate/Utils/Reflection/ReflectionHelper.cs


Is there a proper way to use slow Pokemon in the party?

Question: I'm playing Pokemon White 2, and I really love using fast Pokemon in battle. But this time, I think I wanna try to use slow Pokemon in my party. I'm leaning towards using Rock and Steel type Pokemon: Steel and Rock type are the best for great defense, but they have really bad speed in battle.
Here's my current team list.

Golem
Aerodactyl (it's fast actually)
tyranitar
Magcargo
Kabutops
Bastiodon

I just want to know if there is a way use slow Pokemon properly, like their learnset, ability, and move combination for double/triple battle. Is it good to have five Pokemon that really slow at speed?
I'm asking this because I'm curious for the fact that there's many Gym leaders that specialist at Rock and Steel type.
Answer: In non-competitive scenarios such as playing through the story (which is what you mention that you're playing), it shouldn't really matter too much. You can simply outlevel other trainers and Gym leaders and overwhelm them with pure force.
As for movesets, use your Pokemon's secondary typings to your advantage. For example:

Use Magcargo's & Aerodactyl's Fire and Flying moves vs Grass & Bug Pokemon,
Use Tyranitar's Dark moves vs Psychic
Kabuto's Water vs Fire, Rock and Ground

and so on. Even having Non-S.T.A.B. coverage moves on your Pokemon is worth it. Kabutops can learn Ice Beam, which will be helpful when taking on Dragon types for example.

If you want to build a team that actually takes advantage of slow Pokemon's speed, you might also want to consider a Team that revolves around Trick Room:

Trick Room reverses the move order within each priority bracket so that Pokémon with a lower Speed stat attack first, whilst those with a higher Speed stat will attack last.

If you're looking for Pokemon that can set it up, Bronzong would be a good example of a Trick Room Pokemon that fits your criteria. It's a slow Steel/Psychic type.
Comment: @TrentHawkins Unfortunately dems the breaks when running a mono-type or themed team. As I said the only real way to overcome these problems is to outlevel and have coverage moves, or otherwise have a plan to deal with certain threats on Gym leader/E4 teams (regular trainers won't matter too much). As an example, utilising Golem's Sturdy (assuming it has Sturdy) to survive OHKOs and hit back with a high-powered move is a viable strategy to take care of large threats on the opposing team. Stocking up on Revives and Full Restores is probably a must as well.
Comment: The only thing that I would add to this is that the current type composition of his team means that his entire team is criplingly weak to Water and Fighting which may present some issues with the Wave Badge and the Fighting member of the Elite Four (although fighting might not be too much of an issue since Aerodactyl should be able to handily out speed everything and deliver 2x STAB-boosted flying damage). Similar weaknesses to ground (though aerodactyl is normally immune). Grass and Steel are also a bit problematic with half the team being weak to those types, and the other half neutral.
Comment: If you want a rock type that helps your weakness to water moves, consider Cradily. It has Storm drain to completely nullify water attacks.
Comment: I would suggest the use of Gyro Ball on either Bronzong or Metagross, both because you would get the STAB and because it's power goes up the lower your Pokemon's speed stat is. So if you combo Gyro Ball with a move like Hammer Arm, then you can drop your speed even lower comparatively and boost Gyro Ball's damage output, and on top of that you can still utilize Trick Room because it doesn't affect the stats themselves so you would still have lower speed than the opposing Pokemon but move before they do.


Kafka message filtering

Question: I have a scenario where system A is going to get information from system B.
Options/Scenarios

B will send message to a topic for A to consume along with other consumers of the same topic
Pros - for B things will be simple
Cons - A has to consume all messages where many messages are not relevant to A
B will send message to a topic meant for only A to consume
Pros - A will only get the messages that are relevant to A
Cons - B has to send to a different topic meant only for A's use case
B will a rest API hosted by A
Pros - A does not have to worry about message consumption
Cons - B has to call API for one consumer A and this is not a scalable approach.

To give more information, in my case the messages relevant to A is very small in number compared to all messages that B sends to A
If the number of messages that A is interested in is very very less (say couple of 100s in x days) vs number of total messages published in the topic (few millions in x days) - then does it justify A to read all these from the topic as in option 1.
C should not sound good from the producer (B) perspective as B can not call API for every new consumer with similar need.
While I am working to find out better solutions (if any) would like to know other thoughts.
Updated below
Option 4
B will send message to a topic for A to consume along with other consumers of the same topic but with key that can be used as filtration/rejection by A.
Option 4 sounds a better one and will explore more.
Comment: I can't see any other option than 1) be viable in the long run; what if the information A is interested in changes? You'll have to adjust B for the other cases. Option 2 might be applicable, but that's really dependent on the overall architecture of your system - if there are too many messages on a topic not meant for a consumer, that begins to become a smell.
Answer: Option 4 is a better idea as in that case A will only read messages relevant to it. So while configuring your consumer for A you can only assign the partition which holds the partition key for A.

Kafka message filtering


Show that $f(A)^c\subseteq f(A^c)$ if and only if $f$ is injective

Question: Let $E_i$ be a set, $f:E_1\to E_2$ and $A\subseteq E_1$.
It is easy to show (see, for example, https://math.stackexchange.com/a/1447826/47771) that $f(A)^c\subseteq f(A^c)$ if and only if $f$ is surjective.
Are we able to show that

$f(A^c)\subseteq f(A)^c$ if and only if $f$ is injective

as well? (It's quite easy to prove $f(A^c)=f(A)^c$ if $f$ is bijective; see, for example, https://math.stackexchange.com/a/3301866/47771.)
Comment: If $A$ is (arbitrary but) fixed, then no. But $f$ is injective iff $f(A^c) \subseteq f(A)^c$ holds for *all* $A \subseteq E_1$.
Comment: what have you tried?
Comment: The title and question don't seem to match.
Comment: @DanielFischer I see. Somehow surprisingly, since the analogue surjectivity result holds for a fixed $A$.
Answer: I will denote $X = E_1$ and $Y = E_2$ and $f:X \rightarrow Y$.
Suppose $f$ is injective. Let $y \in f[X\setminus A]$ be arbitrary. Then, there exists $x_1 \in X\setminus A$, equivalently $x_1 \not\in A$, such that $f(x_1) = y$. Now, suppose there is $x_2 \in A$ such that $f(x_2) = y$. Then, $x_1 \neq x_2$ and this means $f(x_1) \neq f(x_2)$ by injectivity, which is a contradiction. So, for all $x \in A$, $f(x) \neq y$, which means $y \not\in f[A]$, equivalently $y \in Y\setminus f[A]$.
Suppose $f[X\setminus A] \subseteq Y\setminus f[A]$. Let $x_1 \neq x_2$ be elements of $X$ and assume $X$ has at least two elements. Then, there is a subset $A$ of $X$ such that $x_1\in A$ and $x_2\not\in A$. Then, we immediately have $f(x_1) \in f[A]$. $x_2 \in X\setminus A$ implies $f(x_2) \in f[X\setminus A] \subseteq Y\setminus f[A]$, that is, $f(x_2) \not\in f[A]$. Therefore, $f(x_1) \neq f(x_2)$.
Comment: Thank you for your answer. I see. Did I get something wrong or does the analogue surjectivity claim hold for a fixed $A$?
Comment: What do you mean by 'fixed'?
Comment: I mean that if $A\subseteq E_1$ is fixed, then "$f(A)^c\subseteq f(A^c)$ if and only $f$ is surjective".
Comment: I am sorry, I was late. Yes, $A$ as a subset of $X$ can be universally quantified. I should have said that "Suppose that for each $A \subseteq X$, $f[X\setminus A]...$ in the third paragraph.


Does Ubuntu provide patched version of openssl for 12.10?

Question: 12.10 is right at end of life in April 2014.
Answer: Yes, here's the changelog for the openssl package in 12.10 showing the Heartbleed fix released on April 7.
Comment: Yes, I see I got it, I forgot to restart Apache. Thanks.


terminal emulator vs terminal

Question: I am a having a little trouble understanding the difference between running the terminal emulator from the GUI (gnome) and booting straight into the terminal. I have been a system/network administrator for a little over 10 years and I am very familiar with terminal emulation and how it works on a Windows platform, however I was told by a Linux "engineer" that running the terminal emulator from the GUI (as root) would not grant the proper permissions to edit the kernel source code. He said you need to boot to the console and login as root.
Answer: Booting straight into the terminal means running in the text console. Technically, this console (/dev/console, /dev/tty1, /dev/tty2 and the likes) is just provided by another terminal emulator.
Real terminals like the famous VT100 used to be connected to computer through serial lines but are now essentially history.
About the kernel editing restriction, I guess you misunderstood what was told by the Linux engineer. Obviously, nothing prevents you to edit a file whatever the terminal emulator used. However, if you want to see console messages while experimenting with a custom kernel, that makes more sense.
Comment: As a little addendum, terminal emulators in the GUI are in most cases not virtual terminals, but pseudo terminal slaves (PTS). The number of virtual terminals you can use concurrently on a machine is fixed. You very rarely need for example 64 virtual terminals at the same time, but there is a limit ;) A PTS behaves for almost any purposes like a virtual terminal, but it doesn't occupy a virtual terminal.
Comment: @HenningKockerbeck don't confuse the terminal emulators, which are userland pieces of software and the drivers which are behind the devices they are connected to, here the pseudo terminal slaves. The former are emulating a display and a keyboard while the latter are used to interconnect command line programs and the emulators.
Comment: @jlliagre - Are the definitions of a terminal and console the same or do they mean different things? If consoles are provided by another terminal emulator, shouldn't these be /dev/pts1 for example? I have seen VT100 referenced a number of times and if it refers to (https://en.wikipedia.org/wiki/VT100), it appears to be a strongly coupled video screen, keyboard and computer. If yes, what do you mean by it "used to be connected to [a] computer?
Comment: @Motivated A console used to be **the** main physical device from where operators were interacting with a computer while a terminal was a topological term naming one of the multiple devices connected to a central computer through RS232 serial lines. Terminals, even VT100's were "dumb" and useless when standalone. There was no computer inside, i.e. no operating system, just enough electronics to drive the CRT, the keyboard, the serial line and store the setup.
Comment: @jlliagre - When you say the main physical device, was it part of the computer/server/mainframe? For example, did it feature its own display, mouse and keyboard that were connected to the computer?
Comment: @Motivated In early computers, the console was part of the whole system, initially with switches then with typewriters. Later, the console was a remote device like a VT100. There was no graphics nor mouse on the VT100.
Comment: @jlliagre - Historically was the console limited to switches and typewriters or did it feature video terminals, keyboards and possibly a mouse?
Comment: @Motivated That depends on when you start "history" but computers definitely predate video terminals and mice.
Comment: @jlliagre - In the context of consoles, would these have featured video terminals, keyboards and mice?
Comment: @Motivated Have a look to the [Ferranti Mark 1 console](http://ferut.ca/mark-1/) to get an idea.
Comment: @jlliagre - Thanks. It appears that a console can feature switches and a video terminal. The reason for my question is to understand the use of console and terminal in Linux. If a console is part of a computer and a terminal is a remote device to access a computer, what constitutes a console and terminal in Linux today? For example, you mention that booting straight into a terminal means running a text console. Does that mean that a console runs within a terminal session? Is a terminal emulator only a terminal?
Comment: @jlliagre - I came across your post (https://unix.stackexchange.com/questions/60641/linux-difference-between-dev-console-dev-tty-and-dev-tty0) however it remains unclear to me. I also read the remaining posts. What is the difference between /dev/tty0 and /dev/tty[1-7]? What does dev/console is a virtual set of devices mean?

terminal emulator vs terminal


python google colab directory access error: (-215:Assertion failed) !ssize.empty() in function 'resize'

Question: I am working with google colab. I am facing slow access rate to my image directory from colab to drive. After some investigation, I saw to improve to the rate, you have to copy the zip from drive to colab and unzip into colab. My issue is when I perform process_images function it returns me an error: error: OpenCV(4.1.2) /io/opencv/modules/imgproc/src/resize.cpp:3720: error: (-215:Assertion failed) !ssize.empty() in function 'resize'.
However if I do ls on the directory I have the files in the colab directory. Note this error doesn't not appear when I access from google drive.
I copy the zip from google drive to colab
!cp /content/drive/MyDrive/invasive_60000.zip /content/invasive/

I unzip the archive in the colab directory
!unzip -q /content/invasive/invasive_60000.zip

I check if files are there:
!ls -la /content/invasive_60000/

I define my image patches: imagePatches = glob('/content/invasive_60000', recursive=True)
define my function process image:
def process_images(lowerIndex,upperIndex):
    """
    Returns two arrays:
        x is an array of resized images
        y is an array of labels
    """
    height = 50
    width = 50
    channels = 3
    x = [] #list to store image data
    y = [] #list to store corresponding class
    for img in imagePatches[lowerIndex:upperIndex]:
        full_size_image = cv2.imread(img)
        image = (cv2.resize(full_size_image, (width,height), interpolation=cv2.INTER_CUBIC))
        x.append(image)
        if img in classZero:
            y.append(0)
        elif img in classOne:
            y.append(1)
        else:
            return
    return x,y

When I call the function: X, Y = process_images(0,60000) I have this error:
error                                     Traceback (most recent call last)
<ipython-input-23-8fa6697d3af2> in <module>()
----> 1 X, Y = process_images(0,60000) #it has to be 60000

<ipython-input-21-129e46598d2e> in process_images(lowerIndex, upperIndex)
     12     for img in imagePatches[lowerIndex:upperIndex]:
     13         full_size_image = cv2.imread(img)
---> 14         image = (cv2.resize(full_size_image, (width,height), interpolation=cv2.INTER_CUBIC))
     15         x.append(image)
     16         if img in classZero:

error: OpenCV(4.1.2) /io/opencv/modules/imgproc/src/resize.cpp:3720: error: (-215:Assertion failed) !ssize.empty() in function 'resize'

It is like the folder is empty of images. Do you have any idea ?
Answer: I understood my error, imagePatches = glob('/content/invasive_60000/**/*.png', recursive=True) as to be written like that recursively on all pictures.


SubSonic Save() changes not working

Question: I am trying to save changes to a record, however I am getting the error

Violation of PRIMARY KEY constraint
  'PK_TStoreAssignment'. Cannot insert
  duplicate key in object 'TAssignment'.
  The statement has been terminated.

Here is the subsonic query
Dim current = DB.Select().From(TStoreAssignment.Schema) _
                                 .Where("assignmentID").IsEqualTo(selectedRow.AssignmentID) _
                                 .ExecuteSingle(Of TStoreAssignment)()

'Modify the sequence
 current.ManualSequence = 999
 current.Save()

Answer: I see two possibilities for this error:

Either ManualSequence is (part of) the primary key of TStoreAssignment, and you already have an other entry with 999
or (probably) SubSonic thinks current is a new object and tries to insert it instead of updating it when you call Save(). You can debug and check the IsNewproperty. If that's the case, you may call MarkOld() before the Save method. Or even better, use something like:
DB.Update().From(Of TStoreAssignment)() _
    .Set(TStoreAssignment.ManualSequenceColumn).EqualTo(999) _
    .Where(TStoreAssignment.AssignementIDColumn).IsEqualTo(selectedRow.AssignmentID) _
    .Execute()

SubSonic Save() changes not working


Continuity using nets on a dense subspace and regularity

Question: If $Y$ is regular, $f:T\to Y$ is a function such that $X\subseteq T$ is dense in $T$, and for any net $x_\alpha\in X$ converging to $x\in T$, $f(x_\alpha)$ converges to $f(x)$, then $f$ must be continuous.
For explanation of the above see this question.
Note that $f$ is continuous iff for any net $x_\alpha$ converging to $x$, $f(x_\alpha)$ converges to $f(x)$.
Now fix space $Y$. If for every such choice of $X, T$ and $f$, the above property holds, is $Y$ necessarily regular?
Answer: Yes, this is true.  Suppose $Y$ is not regular; let $a\in Y$ be a point with  a neighborhood $U$ which contains no closed neighborhood of $a$.  For each neighborhood $V$ of $a$, its closure is not contained in $U$, so we can pick a filter $F_V$ which contains $V$ and converges to a point $y_V\not\in U$.
Now let $S$ be the set of neighborhoods of $a$, $X$ consist of elements of $Y$, and let $T=X\sqcup S\sqcup\{\infty\}$ equipped with the following topology.  A set $A\subseteq T$ is open iff it satisfies the following conditions:

For each $V\in S$ which is in $A$, $A\cap X\in F_V$.
If $\infty\in A$ then there exists some $V\in S$ such that $W\in A$ for all neighborhoods $W\subseteq V$ of $a$.

Intuitively, we are starting with $Y$ with the discrete topology, then adjoining a point $V$ for each $V\in S$ which is a limit of the filter $F_V$ on $Y$, and then adjoining a point $\infty$ which is a limit of the net formed by these points $V$ with respect to the reverse inclusion order of neighborhoods.
Note that $X$ is dense in $T$ (its closure contains all of $S$ by (1) and thus contains $\infty$ by (2)).  Define $f:T\to Y$ by $f(y)=y$ for $y\in X$, $f(V)=y_V$ for $V\in S$, and $f(\infty)=a$.  Note that $f$ is continuous when restricted to $X\sqcup S$: if $W\subseteq Y$ is open and $f(V)=y_V\in W$, then $W\in F_V$ since $F_V$ converges to $y_V$ so $f^{-1}(W)$ satisfies condition (1). However, $f$ is not continuous on all of $T$ since $f^{-1}(U)$ is not open (it contains $\infty$ but does not contain any elements of $S$).
Finally, I claim that $f$ preserves convergence of nets in the dense subset $X\subset T$.  Since $f$ is continuous on $X\sqcup S$, it suffices to check this for nets that converge to $\infty$.  So suppose $(y_i)$ is a net in $X$ that converges to $\infty$ in $T$; we wish to show that $(y_i)$ converges to $f(\infty)=a$ in the topology of $Y$.  Note that if $V\in S$, then $V\sqcup \{W\in S:W\subseteq V\}\sqcup\{\infty\}$ is open in $T$.  So, $(y_i)$ is eventually in this open set, which means $(y_i)$ is eventually in $V$.  That is, $(y_i)$ is eventually in every open neighborhood of $a$, so it converges to $a$.
(If you restrict to Hausdorff spaces, then there is a rather more elegant construction: you can instead take $T$ to be the set of all convergent ultrafilters on $Y$ (with the usual topology on the set of ultrafilters on a set) and $f:T\to Y$ the map taking a convergent ultrafilter to its limit.  Then $f$ is continuous iff $Y$ is regular by an argument similar to the one above; see here.  But the principal ultrafilters are dense in $T$ and $f$ always preserves convergence of nets of principal ultrafilters, again by an argument similar to one above.)


AWS Lambda function can't connect to and query SQLite DB file from S3

Question: My goal is to upload a SQLite database file to AWS S3, use AWS Lambda & python (sqlite3) to connect to the database, query it, and return some of its data.
Having uploaded the database file to S3, I wrote a python script (which is to become the Lambda function) that successfully downloads the database from S3, connects to it with sqlite3, and returns some query results.
The issue is that when I take the exact same code and put it in AWS Lambda, I get the following error:
{
  "errorMessage": "malformed database schema (message_idx_undelivered_one_to_one_imessage) - near \"where\": syntax error",
  "errorType": "DatabaseError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 11, in lambda_handler\n    print(cursor.execute(\"select mycolumn from message limit 1\").fetchone())\n"
  ]
}

Here is the python script/Lambda function:
import sqlite3
import boto3

def lambda_handler(event, context):
    s3 = boto3.resource("s3")
    bucket = s3.Bucket("my-bucket")
    bucket.download_file("my_database.db", "/tmp/my_database.db")

    conn = sqlite3.connect("/tmp/my_database.db")
    cursor = conn.cursor()
    print(cursor.execute("select mycolumn from message limit 1").fetchone())

Running this file locally works correctly. I have confirmed that both my local environment and Lambda are using these versions of the following:
boto3: 1.20.32
python: 3.9.13
sqlite3: 2.6.0

Here is the schema of the database I'm trying to read.
Why is Lambda producing this error while my local environment isn't? How can I go about getting python to connect to the database within the Lambda function?
Comment: it's not quite easy either to infer the sqlite3 version from the python sqlite3 package. you could add the result of this python statement in your question `print(sqlite3.sqlite_version)`.
Comment: You're using SQLite 3.7.17, which does not support partial indexes (the "where" clause on your index), that feature was added in [3.8.0](https://www.sqlite.org/releaselog/3_8_0.html)
Comment: indeed, if you're using the same version on both environment there is no way it works on one and not on the other. you may want to clarify versions on both sides.
Comment: `print(sqlite3.sqlite_version)` yields `3.37.0` on my machine and yields `3.7.17` on Lambda, so it seems like this is the issue..? If I can get my lambda function to run with a newer version of `sqlite3` then this should work on Lambda. I'll give this a try and update my question with the results. Appreciate the help!
Comment: `sqlite:  2.6.0` you mean `sqlite3: 2.6.0` ? what's your database schema, is message a view ?
Comment: Yeah sorry I meant `sqlite3`. `message` is a table in the database. I'm not super familiar with SQLite, so I'm not exactly sure how to describe the schema. As far as I know, there are no views in the database.
Comment: to show the schemas you juste need to open your database with the sqlite3 comment `sqlite3 file.db` and then issue the `.schema` command, that should show the full database structure
Comment: Ok, here's the output of that command: https://pastebin.com/NCrWitsX
Comment: this is this ddl which seems to not be understood `CREATE INDEX message_idx_undelivered_one_to_one_imessage ON message(cache_roomnames,service,is_sent,is_delivered,was_downgraded,item_type) where cache_roomnames IS NULL AND service = 'iMessage' AND is_sent = 1 AND is_delivered = 0 AND was_downgraded = 0 AND item_type == 0;` you may want to edit that to your question so that it's clear for every reader
Comment: for more references https://www.sqlite.org/partialindex.html
Comment: Indeed that's the issue
Answer: From pastebin extract here is your DDL in your database schema which triggers your error when opening your database
CREATE INDEX message_idx_undelivered_one_to_one_imessage
ON message(
    cache_roomnames,
    service,
    is_sent,
    is_delivered,
    was_downgraded,
    item_type
) where cache_roomnames IS NULL
    AND service = 'iMessage'
    AND is_sent = 1
    AND is_delivered = 0
    AND was_downgraded = 0
    AND item_type == 0;

The partial index feature has been integrated in sqlite since the 3.8.0 version https://www.sqlite.org/partialindex.html.
The sqlite3 version on the lambda environment is probably to old to handle such king of schema. An version bump in your sqlite3 dependency in your lambda environment should fix your issue.


Combining attached photos in kmail

Question: Someone has sent me an email with about 30 attached jpeg files.  It's extremely tedious to view them by clicking on them one by one.  Is there a way to view them in a single viewer, sequentially?
It is obviously better for people to collect photos in archives, but I've generally been unable to persuade them of that.
Comment: Can you highlight all of them and then right-click mouse and select open or view?
Answer: I would download all attachments together and view them with an image viewer like Gwenview. Right click on the email in the list and select download attachments. This feature is not available in an opened email, you must right click the email in the list of emails.

Combining attached photos in kmail


Find a homogeneous linear system for which the space of solutions is exactly the subspace of $\mathbb{R}^4$ spanned by $v_1, v_2,$ and $v_3$.

Question:
Consider the vectors in $\mathbb{R}^4$ defined by
  $v_1 = (1,2,10,5), v_2 = (0,1,1,1), v_3 = (1,4,12,7)$ Find a homogeneous linear system for which the space of solutions is exactly the subspace of $\mathbb{R}^4$ spanned by
  $v_1, v_2,$ and $v_3$.

It's related to a previous post feel like this question needed its own post. So basically i need to find $av_1+bv_2+cv_3 = 0$ such that $a=b=c=0$ span a $4$ dimensional subspace of $\mathbb{R}^4$.

$$\begin{bmatrix} 1&0&1\\2&1&4\\10&1&12\\5&1&7 \end{bmatrix} = \begin{bmatrix} 0\\0\\0\\0 \end{bmatrix}$$
And reduce it down to
$$\begin{bmatrix} 1&0&1\\0&1&2\\0&0&0\\0&0&0\end{bmatrix}= \begin{bmatrix} 0\\0\\0\\0 \end{bmatrix}$$
which means rank is $2$ because we have $2$ leading ones.
Also i think it's not linearly independent as row 1 $= a+c=0, \text{row} \hspace{.1cm} 2 = b+2c=0, a=-c$ and $b=-2c$
hence $a$,$b$ and $c$ are not equal to zero. Meaning $\{v_1,v_2,v_3\}$ is linearly dependent as there are $4$ components to the vectors we are in a subspace of $\mathbb{R}^4$ and that subspace is $2$ dimensional as we have to leading ones.
But we need the set to span $\mathbb{R}^4$ in a $4$ dimensional subspace.
Comment: No we don't. It doesn't say "span $\Bbb R^4$". It says "subspace of $\Bbb R^4$ spanned *by* $\{v_1, v_2, v_3\}$". I.e. the problem is to find a system of equations (expressed in homogenous form) such that $v_1, v_2, v_3$ are all solutions, and futher, such that every solution is a linear combination of $v_1, v_2, v_3$. For this, it doesn't matter what the dimension of the span of  $\{v_1, v_2, v_3\}$ is.
Comment: Homogenous meaning a=b=c=0 hence be linearly independent?
Answer: Let $Ax=0$ be a homogeneous linear system with $\text{null}(A)=\text{span}\{v_1,v_2,v_3\}$.
Then $\text{row}(A)=(\text{null}(A))^{\perp}$, so we can find a basis for $\text{row}(A)$ by reducing
$\begin{bmatrix}1&2&10&5&0\\0&1&1&1&0\\1&4&12&7&0\end{bmatrix}\rightarrow\begin{bmatrix}1&2&10&5&0\\0&1&1&1&0\\0&2&2&2&0\end{bmatrix}\rightarrow\begin{bmatrix}1&2&10&5&0\\0&1&1&1&0\\0&0&0&0&0\end{bmatrix}\rightarrow\begin{bmatrix}1&0&8&3&0\\0&1&1&1&0\\0&0&0&0&0\end{bmatrix}$.
If we let $x_3=s$ and $x_4=t$, this gives $x_1=-8s-3t$ and $x_2=-s-t$,
so a basis for $\text{row}(A)$ is given by $r_1=\langle-8,-1,1,0\rangle$ and $r_2=\langle-3,-1,0,1\rangle$.
This gives the homogeneous linear system  $\;\;\;8x_1+x_2-x_3=0$
$\hspace{2.84 in} 3x_1+x_2-x_4=0$.


Python generator objects and .join

Question: Just a fundamental question regarding python and .join() method:
file1 = open(f1,"r")
file2 = open(f2,"r")
file3 = open("results","w")

diff = difflib.Differ()
result = diff.compare(file1.read(),file2.read())
file3.write("".join(result)),

The above snippet of code yields a nice output stored in a file called "results", in string format, showing the differences between the two files line-by-line. However I notice that if I just print "result" without using .join(), the compiler returns a message that includes a memory address. After trying to write the result to the file without using .join(), I was informed by the compiler that only strings and character buffers may be used in the .join() method, and not generator objects. So based off of all the evidence that I have adduced, please correct me if I am wrong:

result = diff.compare(file1.read(),file2.read())  <---- result is a generator object?
result is a list of strings, with result itself being the reference to the first string?
.join() takes a memory address and points to the first, and then iterates over the rest of the addresses of strings in that structure?
A generator object is an object that returns a pointer?

I apologize if my questions are unclear, but I basically wanted to ask the python veterans if my deductions were correct. My question is less about the observable results, and more so about the inner workings of python. I appreciate all of your help.
Comment: You don't have a memory address; python gives you a representation of an object, and the default for custom objects is to show the type and memory address of the object. There is still an object there.
Answer: join is a method of strings.  That method takes any iterable and iterates over it and joins the contents together.  (The contents have to be strings, or it will raise an exception.)
If you attempt to write the generator object directly to the file, you will just get the generator object itself, not its contents.  join "unrolls" the contents of the generator.
You can see what is going with a simple, explicit generator:
def gen():
    yield 'A'
    yield 'B'
    yield 'C'

>>> g = gen()
>>> print g
<generator object gen at 0x0000000004BB9090>
>>> print ''.join(g)
ABC

The generator doles out its contents one at a time.  If you try to look at the generator itself, it doesn't dole anything out and you just see it as "generator object".  To get at its contents, you need to iterate over them.  You can do this with a for loop, with the next function, or with any of various other functions/methods that iterate over things (str.join among them).
When you say that result "is a list of string" you are getting close to the idea.  A generator (or iterable) is sort of like a "potential list".  Instead of actually being a list of all its contents all at once, it lets you peel off each item one at a time.
None of the objects is a "memory address".  The string representation of a generator object (like that of many other objects) includes a memory address, so if you print it (as above) or write it to a file, you'll see that address.  But that doesn't mean that object "is" that memory address, and the address itself isn't really usable as such.  It's just a handy identifying tag so that if you have multiple objects you can tell them apart.
Comment: Interesting fact: Giving `''.join()` a generator is *slower* than giving `''.join()` the result of calling `list()` on a generator. `''.join(list(result))` is faster than `''.join(result)`.
Comment: Note that `join` assumes that the iterable contains/yields only strings.  It will complain if that isn't the case...
Comment: @Phob see http://stackoverflow.com/a/9061024/100297. Check your benchmark, you are probably exhausting your generator in the first run.
Comment: @Marcin: The message was:
Comment: @BrenBarn, great, so .join() is basically setting up a pointer that iterates over a generator, and access the contents and adjoin them. It kind of reminds me of a simpler form of accessing a character array in C. Thanks again!
Comment: @eazar001: You don't really want to think of it in terms of pointers.  Basically a generator provides a certain API (the iterator protocol), and `join` makes use of that API to get the generator to release its contents.
Comment: @BrenBarn, Okay, I'll make sure to get that out of my head, I guess I should have started emptying pointers from my head when the first few posts stated 'no memory addresses.' It's just really difficult for me to link "contents" and "iteration" without thinking of pointers I suppose. Thank you for clearing that up though.
Comment: @MartijnPieters a quick benchmark in iPython shows this to be false. Why would you think otherwise?

Python generator objects and .join


What happens to Threads started in Android Service when Android restarts the Service?

Question: I have a Service like this (this is not the actual Service, it's just for describing my problem).
public class UploadService {

    private BlockingQueue<UploadData> queue = null;

    private UploadInfoReceiver receiver = null;

    public void onStart(...) {
        queue = new LinkedBlockingQueue<UploadData>();
        (new Processor()).start();
        // creating and reigtering receiver
    }

    public void onDestroy() {
        queue.add(new ServiceDestroyedData());
        // unregistering the receiver
    }

    private class Processor extends Thread() {

        public void run() {
            while (true) {
                UploadData data = queue.take();

                if (data instanceof ServiceDestroyedData) {
                    return;
                }

                // processing data
            }
        }

    }

    private class UploadInfoReceiver extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {
            queue.add(new UploadData(/* getting data from intent */));
        }

    }

}

And my problem is that if I do something like this in my App:
if (!isUploadServiceRunning()) {
    // start the Service
}

Then it starts the Service, but when I move my App to the background and open task manager (android 4.2.2), and kill the app, Android restart my Service, and I can see that it creates a whole new instance of it, and I can see that onDestroy never gets called for the previous Service instance. And I also can see that the instance of the previous Processor Thread is no longer running. How can this be? If onDestroy never gets called how does Android know that it should stop my Thread?
Thanks for your answers.
Comment: As meredrica states, if you Force Stop an app the process is literally just killed and everything ripped out of memory. It's why Android provides a warning when you try to do it, i.e., the usual graceful shutdown won't happen and none of the life-cycle methods will be called. As an aside, it's also why Task Killer apps are evil and go against the Android design principle.
Answer: Android will kill off anything that it finds that is attached to your apps classloader when you select force stop from the menu. Think kill -9 on Linux. There will be no nice callbacks to any onDestroy methods, the system will just end everything.
Now for your service:
while(true) should really NEVER be used. It will instantly kill the battery and will not do any work 99% of the time anyway.
You area already using a receiver, you can just put your while logic into there and once the upload is done call the next upload and so on. There is absolutely no need for the loop.


What are the connections on this German TV socket?

Question: I live in Germany. I have zero knowledge in TVs. I found a TV socket in the wall but I have no idea what it means.
My questions is: can you please explain to me what does each port in the socket does?
Here I attach a picture for the socket:

EDIT: Is it called DVB-T?
Comment: Your simplest and probably cheapest option is to buy a used TV.
Comment: Your laptop is not a television, TV's contain tuners to tune in a channel being broadcast. You can buy these for computers, but that conversation off topic for the site.
Answer:
can you please explain to me what does each port in the socket does?

In your photo they are labelled DATA, TV, R
So it is reasonable to assume

DATA: DOCSIS connection, you can use it to connect to the internet if you purchase a data plan from your cable television provider
TV: A TV antenna.
R: A Radio antenna.

Nowadays the TV signal is likely to be DVB-T. The antenna and coaxial cable and connectors are the same as for the old analogue PAL signals. It is possible that it is DVB-S from a satellite dish. I'd ask the building manager (if there is one).
Answer: The data port is a satellite feed from your dish, or if it's a shared complex, it's a satellite feed. You may or may not require a decoder for the satellite depending on the setup. Data in this case actually means it's a digital connection.
The only problem with this fixture is that hd satellite may require multiple feeds to the HD receiver, (TiVo and pvr stuff)
The TV port is a the old school tv antenna port where you have the rf antenna on the roof. You will need to scan for open air channels from your TV with this analog connection
Radio is just connected to a radio antenna or mast.


How to wire a relay for an evaporative cooler to a thermostat?

Question: I have an evaporative cooler with 120VAC control that I want to switch on and off using a relay that is activated when the cool call comes from my thermostat. I plan on just using 1 relay to activate the whole cooler control (rather than multiple relays to control the different aspects of the cooler), so this is a simple on/off when cooling call comes from the thermostat.
All of the wiring for the thermostat goes to the air handler and then heat, fan, etc. kick on from there. I have a C wire running to the thermostat. My thought was that I just put the relay in line with the Y wire (run Y from thermostat to relay, then out from relay to the air handler). This puts 24VAC across the relay (which is what the relay is rated for), but does not throw the switch.
Comment: So you've already tried wiring this up but it's not working? Could be the power supply for the 24vac cannot provide enough current to pull the relay.
Comment: I've wondered about this. Any ideas on how to wire if I need to put in a 2nd 24VAC source?
Comment: Could you please include a wiring diagram of what you're trying to do?  This will help both us, and you understand the problem a bit better.
Comment: Does [this diagram](http://chat.stackexchange.com/transcript/message/10362451#10362451) represent what you're trying to do?
Comment: Tester101, that diagram does represent what I'm trying to do
Answer: You'll want to connect the Y and C wires to the coil of the relay, so you end up with something like this.

When the temperature switch in the thermostat closes (calling for cool), 24 volts will be applied to the relay coil.This should pull the contact in the relay to the normally open (NO) position, allowing electricity to flow to the evaporative cooler (or whatever 120V device needs to be powered).
Answer: It actually sounds like you don't have it wired correctly. You should have a wire from the C terminal connected to one side of the relay, and the Y terminal to the other.
To verify, use your multimeter to test that you measure 24V AC across the relay coil when the thermostat calls for cooling.
Comment: What does your multimeter measure? If you don't have one, go buy one, you need it to diagnose what's happening.
Comment: This was actually my 2nd guess. Tried that as well, no luck. I tried it both with the Y from the thermostat and the line to the relay attached only to each other and with them both attached to the Y on the air handler as well.
Answer: I would look for the green wire (fan) at the air handler. You might as well use this control voltage since you would want the evap cooler active when the fan is on. Measure the voltage at the fan relay to ensure it's 24 VAC (remember this value). Run wires from the green wire to your relay and also connect the common. Does your relay activate when the fan turns on? If the 24 VAC transformer can't handle the extra load, it may not turn on the fan. What is the voltage at the fan relay now? Alternately, you could replace the fan relay with a 2-pole version to give you the extra contacts for the evap cooler while only using a single relay.
Hope this helps.
Thinking about this again, use the cool control since you do not want the evap cooler on during heating mode. Or stay with the fan signal and place a normally closed relay in series wired to the heat signal. That way you would have evap cooling any time the fan is on (which you want for cooling) and the evap cooler is off during heating operation.
Answer: Late answer, but I did this on my cooler.   Since my thermostat requires batteries, it doesn't use the C connection.   Run one lead of 24ac to the thermo (R) then take (Y) from the thermo to one input of relay coil.  Take other lead of 24ac and connect to the other input of relay coil.

The black wire goes the the 24vac transformer.  The grey wire going down goes to the relay inside cooler.  The grey wire going up/left goes to the theromstat, hooked to R and Y.  It's setup like this because my cooler is in a window.  In winter I just disconnect the wires, shove inside the window and close it.  Since the polarity doesn't matter, you hook it back up in Y configuration, always works.  Yes, that's Cat5E cable, I'm using a pair for each run.
Relay is in inside the cooler, outside.  Thermostat is upstairs in the hallway.  24VAC transformer is inside house, plugged into outlet.
One problem I have is the current draw on this huge cooler welds the contacts.  I would suggest a 24ac contacter, or a 40 amp relay.


sqlalchemy pymssql "connection reset by peer" recovery

Question: I'm running a cherrypy webservice and wondering what the best option is to recover from "connection reset by peer" for a pymssql connection via sqlalchemy. Right now I have to restart the webservice.
Answer: This seems to be a bug in the is_disconnect() method for pymssql where it ignore TCP connection and timeout failures, leaving the cursor in an unhappy state; see http://www.sqlalchemy.org/trac/ticket/2172. For now, you can monkey-patch as:
<code>from sqlalchemy.dialects.mssql import pymssql

def is_disconnect(self, e):
    for msg in (
        "20003",
        "20004",
        "Error 10054",
        "Not connected to any MS SQL server",
        "Connection is closed"
        ):
        if msg in str(e):
            return True
    else:
        return False

pymssql.MSDialect_pymssql.is_disconnect = is_disconnect
</code>


send datatable from a page to another one in asp.net

Question: i have a datatable that i get it from sql,and after some process on each row i add a column to the datatable that shows the process result and then i want to send it to another page in asp.net ,what is the best way?
is it ok to use session or what?
i try it with session but i'm not sure that it is ok,because many people use my server.
        DataTable dt = new DataTable();
        dt.Columns.Add("img", typeof(string));
        dt.Columns.Add("soratvaziat", typeof(string));
        dt.Columns.Add("shomaregharardad", typeof(string));
        dt.Columns.Add("sharh", typeof(string));
        dt.Columns.Add("eghdam", typeof (Boolean));

        DataRow dtrow = dt.NewRow();    // Create New Row
        dtrow["img"] = "accepted.png";            //Bind Data to Columns
        dtrow["soratvaziat"] = "SureshDasari";
        dtrow["shomaregharardad"] = "B.Tech";
        dtrow["sharh"] = "Chennai";
        dtrow["eghdam"] = true;
        dt.Rows.Add(dtrow);

        dtrow = dt.NewRow();               // Create New Row
        dtrow["img"] = "attention.png";               //Bind Data to Columns
        dtrow["soratvaziat"] = "MadhavSai";
        dtrow["shomaregharardad"] = "MBA";
        dtrow["sharh"] = "Nagpur";
        dtrow["eghdam"] = true;

        dt.Rows.Add(dtrow);

        dtrow = dt.NewRow();              // Create New Row
        dtrow["img"] = "canceled.png";              //Bind Data to Columns
        dtrow["soratvaziat"] = "MaheshDasari";
        dtrow["shomaregharardad"] = "B.Tech";
        dtrow["sharh"] = "Nuzividu";
        dtrow["eghdam"] = true;

        dt.Rows.Add(dtrow);

        dtrow = dt.NewRow();              // Create New Row
        dtrow["img"] = "accepted.png";              //Bind Data to Columns
        dtrow["soratvaziat"] = "Mahendra";
        dtrow["shomaregharardad"] = "CA";
        dtrow["sharh"] = "Guntur";
        dtrow["eghdam"] = false;

        dt.Rows.Add(dtrow);
        RadGrid1.DataSource = dt;
        RadGrid1.DataBind();
        Session["dt"] = dt;

Comment: Don't store datatable in session. bad bad bad. too bloated, too heavy and if you are storing large objects in session then you need to re-think your approach.
Comment: You are not able to make an insert for new row in SQL, and in another page make another query for all inserted rows? This is the best choice when you have a database. Is better making multiple inserts and selects for a single user, than storing a lot of data in session
Comment: Do you keep client specific data on your datatable?
Answer: I think you can do this with the PreviousPage property. This allows you to access variables from the page that sent control to the currently loaded page. You need to set a couple things up in your .ASPX page directive, but then you use
PreviousPage.Something

To do it. I'd set the datatable up as a property and refer to that property on the current page.
For further reading:
Passing values across ASPX pages
Comment: Does this work with Response.Redirect or do I have to post on the target page?
Answer: if session is not enabled then you context to send data
Context.Items.Add("context name", DataTable);

and you can access it from the another page by
DataTable dt = (DataTable)Context.Items["context name"];

Answer: 1- create a class
2- put into your class a public static DataTable dataTable
3- then put your dataTable variable to it;
4- you can restore it from any where.
Comment: That is even worse than `Cache` suggested in the other answer. `static` is also application wide so shared across all users but you are also introducing threading issues.
Comment: @EmanuelPirovano if it is then why didn't you down vote it? Or if you think it can be improved offer that advice.


Format kendo ui grid to hierarchy

Question:
I want to create a grid by kendo ui as the below figure. When loading data, if level is zero, padding of field name is 1, bold, if level 2: font-size small, padding 10.
// Kendo ui grid
<code>@(Html.Kendo().Grid<Model>()
          .Name("gridModel")
          .HtmlAttributes(new { @class = "table" })
          .DataSource(x => x.Ajax()
                      .Read("ReadData", "Information")

          )
          .Events(r => r.DataBound("FormatTable"))
          .Columns(c =>
          {

             c.Bound(i=>i.ID)
             ....
</code>
I want to call a event to format table when loading data. It will check value of level field then format row, but I don't know how to implement it.
// javascript
<code>function FormatTable() {
    alert('b');
    var grid = $("#gridModel").data("kendoGrid");
    grid.closest("tr").has("td:eq(2):contains(1)").setSize(7);
}
</code>
It isn't work. Please help me if you have any ideas. Many thanks.
Answer: Try to below code (Bold is the change in your code)
<code> @(Html.Kendo().Grid<Model>()
      .Name("gridModel")
      .HtmlAttributes(new { @class = "table" })
      .DataSource(x => x.Ajax()
                  .Read("ReadData", "Information")

      )
      .Events(r => r.DataBound("FormatTable"))
      .Columns(c =>
      {

         c.Bound(i=>i.ID)
         **c.Bound(i=>i.Name).HtmlAttributes(new {@class="grid-name-column"})**
         ....

 function FormatTable() {
    var grid = $("#gridModel").data("kendoGrid");
    **$.each(data, function (i, row) {
        if (row.Level!= null) {
            var element = $('tr[data-uid="' + row.uid + '"]');
            $(element).find(".grid-name-column").addCss("level-"+row.Level);
        }
    });**
}

**.level-1{
   margin-left:10px;
}
.level-2{
   margin-left:20px;
}
.level-3{
   margin-left:30px;
}**
</code>
Hope it help!

Format kendo ui grid to hierarchy


gnome-terminal scrollback disappearing

Question: When I enter a newline in the commandline, or a command emits a newline, it makes a line of text at the top disappear, almost as though I had a 30 line scrollback. However, I have an unlimited scrollback.
Restarting gnome-terminal does not fix the problem.
Versions:
Gnome Terminal 220.127.116.11
Ubuntu Precise Pangolin
Answer: How about loading it to defaults . I mean
sudo apt-get install --reinstall gnome-terminal

gnome-terminal scrollback disappearing


React how to pass variable to different function

Question: I am new to react! But here goes...
I have created a component that consumes a JSON url, then spits out the news feed in a pretty reactive component.
  // Grabs the posts from the json url
  public getPosts() {
    axios
      .get("https://cors-anywhere.herokuapp.com/" + this.props.jsonUrl)
      .then(response =>
        response.data.map(post => ({
          id: `${post.Id}`,
          name: `${post.Name}`,
          summary: `${post.Summary}`,
          url: `${post.AbsoluteUrl}`,
          imgUrl: `${post.ListingImageUrl}`
        }))
      )
      .then(posts => {
        this.setState({
          posts,
          isLoading: false
        });
      })
    // We can still use the `.catch()` method since axios is promise-based
    .catch(error => this.setState({ error, isLoading: false }));
  }

I had it set that the user would type in the JSON url in the UI, but now I need to make it work with a drop down selection so I created a switch statement to handle this.
  // This will update the json URL for getPosts
  public getCompanyUrl() {
    let url: string = '';
    switch (this.props.listName) {
      case "company1":
        url = "http://example1.co.uk";
        break;
      case 'company2':
        url = "http://example2.co.uk";
        break;
      case 'company3':
         url = "http://example3.co.uk";
        break;
      case 'company4':
        url = "http://example4.co.uk";
        break;
      case 'company5':
        url = "http://example5.co.uk";
        break;
      case 'company6':
        url = "http://example6.co.uk";
        break;
      default:
        url = '';
    }
    console.log(url);
  }

How ever I am unsure how to update:
.get("https://cors-anywhere.herokuapp.com/" + this.props.jsonUrl)

To take the switch statement url variable instead of this.props.jsonUrl.
Any ideas?! :)
Comment: Can't you call the function? `.get("https://cors-anywhere.herokuapp.com/" + this.getCompanyUrl()) `. Ofcourse then you'd also need to return the `url` from the `getCompanyUrl` function.
Comment: That is a good idea!!! TY @ApplePearPerson post the answer ill accept it :)
Comment: you could as well set the url to state inside  `getCompanyUrl()`  and then just use it inside `getPosts()`
Comment: @harisu Sorry I am new to react, how would I set the state of the url inside getCompanyUrl?
Comment: you create a state variable call url and at the end of the `getCompanyUrl()` where you have `console .log()` you do setState({url, url}) then inside of getPosts() you have `get("https://cors-anywhere.herokuapp.com/" +this.state.url)` but then it will be alot optimal if you do it inside the unchange function of the dropdown that way you will not have to create a getCompanyUrl function
Answer: First ensure that getCompanyUrl returns the value of the url, and that it accepts a listName parameter. (Not calling props within this function directly will ensure it's pure and more testable).
public getCompanyUrl(listName) {
    switch (listName) {
      case "company1":
        return "http://example1.co.uk";
      case 'company2':
        return "http://example2.co.uk";
      case 'company3':
         return "http://example3.co.uk";
      case 'company4':
        return "http://example4.co.uk";
      case 'company5':
        return "http://example5.co.uk";
      case 'company6':
        return "http://example6.co.uk";
      default:
        throw new Error();
    }
  }

Then within your getPosts() function you can then call this function to return the relevant URL for the company:
 axios
      .get(getCompanyUrl(this.props.listName))
    .......

Alternatively you could simplify this by converting the getCompanyUrl into a key/value object and then lookup the value from there:
const companies = {
  "company1: "http://example1.co.uk",
  "company2: "http://example2.co.uk",
  "company3: "http://example3.co.uk",
  "company4: "http://example4.co.uk",
  "company5: "http://example5.co.uk",
  "company6: "http://example6.co.uk"
}

  axios
      .get(companies[this.props.listName])
    .......