When should input fields be cleared in modals, if at all?

Question: I have an invoice page with a button to make a payment. The payment button triggers a series of modals for collecting user payment info (credit card/check details, billing details, payment Confirmation).
Is there a standard or best-practice for clearing the fields in series of modals?
For example, should I be including a Cancel button on each modal that will clear all of the fields on all of the modals?
Should clicking the Close button in the upper-right of the modal, or clicking on the modal overlay also clear the fields? Or, should I be leaving the fields populated in case the user accidentally clicks on the overlay or just wants to look at the content behind the modal?
Right now I have a Cancel button on the first modal and a Back button on subsequent modals, but I am leaving the user information in the fields until the payment is processed or the user closes the tab/window.
Answer: Respect the user's time
There will be many reasons why a user wants to dismiss a modal dialog box—other content that they need to check, for reassurance, things they need to look up, interruptions they need to handle first.
Therefore, respect the user's effort and retain the data they entered, as long as only the current user will see this. (Don't confuse others by showing incomplete work that belongs to another user.)
If you think the user might be confused, you can cue them when they re-open the modal:

Do you want to continue your previous entry?

Obviously, don't ask this if there isn't any meaningful data in the previous entry, such as only the date.
Test your solution
Then test it with users to see whether they want to be prompted. You may decide to remove the prompt altogether, or give users the option to "Don't show this again".
I hope that helps you move forward.
Comment: Thanks for the feedback @JeromeR. I'm getting a lot of push-back from the managers/QA people saying that the sensitive data should be cleared, but I agree with your statements about respecting the user's time and effort. I will probably accept this answer, but I will hold off in case there are any other suggestions, since this site's activity is a bit less active that StackOverflow. I appreciate your time and response.
Comment: Security is a legitimate concern. Think about the level of security—don't impose something more stringent on data-entry than on other tasks, such as viewing and reporting. (Do users sign in before they can see or report any data? is that sufficient also for entering data?)


Is there a way to see loot on the ground?

Question: I could swear there is a way to see loot on the ground with a "name bubble".  Often times it drops behind something on screen and in big fights I just forget where it dropped.  Many items blend in the with the background and while I can hunt with the mouse, I'm sure I'm missing stuff.  Is there a way to see all the loot that is on the ground at any given time?
Answer: Hold Alt to show the names of all the loot on the screen.
From here, you can even click on the names that appear to pick the items up, so you don't have to hunt with your mouse in the general area on the ground to find the loot.
Comment: That's it.  I recall now, running everywhere with ALT held down, so that when I toggled mini map with Tab I'd end up leaving the window and cussing.  Ahh... memories...
Comment: Who played Diablo2 and didn't alt-tab never really played diablo2, if you know what I means xD
Comment: @MichelAyres That's why I always changed the hotkey to something else :)
Comment: @MichaelAyres I don't remember accidentally alt-tabbing. However, there were memorable times when I was holding down alt to look at items, and decided to raise more skeletons at the same time. With raise skeleton bound to F4.
Comment: One of the reasons why I changed the "show item names" key to Shift and used Alt for the minimap toggle. I always ran around with the map on, so I hit it once per game and didn't touch it again.
Answer: Try pressing/holding Alt or Tab
:)
Comment: This is wrong. Tab has nothing to do with items.
Comment: Tab defaults to the overlay mini-map
Comment: Just not both at the same time


Use case for Azure App Service Deployment Slots - variation on versions of apps

Question: I read about the Deployment Slots on Azure App Service, and all docs and articles point out that these can be used for something like Prod and Stage versions of an app, with a swap of Stage to Prod to promote it to Prod after testing.
But is that the only use case? For example, we have a web app hosted on Azure App Service. Now we need to make a variation of that app for a specific purpose. It will never be swapped with the production slot. It will just co-exist as basically two separate apps.
Can deployment slots be used like this? Any downsides? It seems to me to be a way to host two or more web apps in an App Service without creating multiple App Services (therefore lower cost).
Answer: Technically I believe it is possible to do what you are suggesting because each deployment slot does host a fully functional version of your application and you can access specific slots using  this routing method. You would simply deploy each environment to its own slot and never swap them.
You can create additional web applications at no cost. You are only paying for the App Service Plan, and you can have as many web apps running on that plan as you want, so you would be better off creating a separate App Service for each of your environments, and since they are all non-production, you can safely run them all in the same App Service Plan.
You can deploy multiple separate WebApps under an App Service Plan. All those WebApps (/websites) will have their own separate default domain (FQDN) and also you can set custom domain for each of those WebApps.
App Service  – Service which enables you to build and host web apps, mobile back ends, and RESTful APIs.
Apps– Your individual Apps (WebApps), these apps run in App Service Plan.
App Service Plan  - An App Service Plan (ASP) defines a set of compute resources for a web app to run.
Since you pay for the computing resources your App Service plan allocates, you can potentially save money by putting multiple apps into one App Service plan. You can continue to add apps to an existing plan as long as the plan has enough resources to handle the load. However, keep in mind that apps in the same App Service plan all share the same compute resources.
If those are separate WebApps, it would be easier to manage separate WebApps than via virtual subdirectories/paths or hostname, or sub-domains. Using App Service Plan feature (provision many apps under the tier) to save cost.
Downsides:

There is a limitation for hosting number of apps in an app service plan bases on plan Tiers you are using, like you can host up to 100 apps in a same app service plan if using the Shared Plan Tier and in the Free Tier, you're charged per app in the app service plan. Refer this for more details.
Azure maintenance requires servers to restart at least once a month or more. If all your apps are on a shared plan, a patch reboot can mean the entire system is down and that all apps compete for resources when starting up simultaneously
Deployment and restarting of apps can cause CPU spikes for the plan (which is a server). If your apps are performance sensitive and you deploy often, you might want more separation.

Note:

Use separate plans as environment boundaries, so a production plan separate from a test plan. "Test" apps go on test plan, "Prod" apps on production to prevent testing from impacting users.
Comment: I have done so (I thought I did already, but I guess I did not!)
Comment: Thanks - I did not realize that it was the App Service Plan that determined the billing - then it does make sense to create multiple App Services and not the deployment slots. I was thinking that I would be charged for each App Service. In the case of the Deployment Slots, I would have left the first one at 100% for traffic and the rest 0%. From what I can see, that would let me use each URL for each slot and the App Service wouldn't sometimes route traffic to one of the other slots - I wouldn't want that. Only through each specific URL for the slot.
Comment: Yes @[mannaggia](https://stackoverflow.com/users/4095326/mannaggia) - Billing charged on app service plan, not based on the deployment slots but there is a limit in number of deployment slots in each App Service Plan and there's no additional charge for using deployment slots. For more details on deployments limits in each app service plan, please refer [here](https://learn.microsoft.com/en-us/azure/app-service/deploy-staging-slots).
Comment: Yes, I did know there was not a cost for deployment slots, and there was a slot limit - but I did not know I could have multiple App Services on the same App Service Plan.
Comment: @mannaggia, Yes! You can deploy multiple App services under an 'App Service Plan'. Please find this [article](https://samcogan.com/what-is-an-azure-app-service-plan-and-what-does-it-do/) given in downsides of my answer which helps you to find number of app services you can host on the same app service plan.
Comment: @mannaggia If the posted answer helped, you may mark it as the answer by clicking the check mark. Doing so can help other community members


Installing printer+scanner dell V105 on ubuntu 12.10

Question: I recently got an old dell V105 printer and wanted to install it on ubuntu, however it could not find specific drivers and with the generic drivers ubuntu proposed, I cannot scan any documents. So, are there any other drivers (f.i. a similar printer from other mark eg lexmark) which I could use for full operation?
Answer: OpenPrinting classes the v105's big brother, the v305, as a "Paperweight". There's extremely little to no chance you'll ever get the printer to do anything useful from a pure Ubuntu environment.
I'm sorry to say that Dell are famously unsupportive of their printers on Linux and in this case there isn't even a driver for OSX.
If you really need it to work, you'd probably be able to use VirtualBox to run a copy of XP and pass the printer through to it... But it'll be slow and buggy. Given the price of printers, it's almost certainly cheaper (in time) to buy a new, Linux supported printer.


How to best spec animations/transitions for engineering team handoff

Question: I have an app prototype built using Pixate which demonstrates the entire flow of the app I am working on. There are transitions between views and animations for certain elements on the page. I have shown the prototype to the engineers who are working on the project but they would like a detailed breakdown of what transitions and animations I am using. How would I best communicate these animations in a spec document? Are there any resources or tools to help with animation specs?
(Here is a catch, all of the engineers are using either Linux or Windows machines, whereas I am using a mac. So the solution should be a cross-platform one.)
Since animation is becoming more prevalent in app design, especially in Material Design, I thought this would be an easy question Google search could answer, but no luck. Any help would be amazing. Thank you in advance.
Aaron J.
Answer:
How would I best communicate these animations in a spec document?

You can't. It's an oxymoron. The best way to communicate animations is to show the animations, as you've done.
Any documentation that tries to explain animation is already once-removed from the source. Plus, there's just no way to actually document all the intricacies that go into it.
It's like making a movie. You can write the script. You can create the storyboards. You can rehearse. But at the end of the day, what comes out at the end is never 100% match to all the documentation you created. Why? Things change. Organizations need to learn to accept that and 'go with the flow' rather than forcing UX teams to become documentation factories.
In some organizations, developers have become accustomed to having everything written out for them. That's just a bad habit that hopefully you can help break.
I'd suggest a document that simply says:

Make the animation behave like the animation in the prototype.

And then work with the side-by-side as much as you can.
Now, perhaps you do have some of the details already...like you know it's a .5s fade. Those you can document. You can do that in an email easy enough.
Answer: There are times when you need to create specs for animations and for those times it is recommended to write the animation in sentences. You can create your own shorthand for communicating your animations to the developers.
Rachel Nabors, an animator was interviewed on the UIE Podcast. She suggests writing sentences for your animations.

"I tend to write out my animations with a formula that goes you list the trailing event, the thing that's being animated, the property.
  How long the animation lasts, and what your easing is. That would be on load the width goes from 25 percent to 100 percent using easing
  over 300 milliseconds. That's the way I write it out in
  documentation. It makes sense to front-end developers and it's still
  legible for designers as well." - Rachel Nabors

Link to podcast:
UIE: Rachel Nabors – Using Animation to Enhance Your UX
Here is another example of annotating animations from Simon Pan's Amazon Prime Music case study:

As you can see this annotation is very detailed and would be very helpful for the developers.
So you can definitely combine the actual animation with a specific animation annotation which can be visual or written out as a sentence for the times when you have to provide a document to the developers.
Answer: First I recommend you to use Framer.js for complete freedom in animation. It is code based prototyping tool for mobile.
Making prototypes is most effective way I've ever experinced while passing app specs to developers/clients. Just simply forward your framer source file to developers they can figure out whats going on there.
note: I not promoter of framer.js, just pro user.


How can I revert an upgrade I had second thoughts about?

Question: I went to upgrade from 22.04 to 23.04 and after hitting Y I had second thoughts as I don't want it to remove some software that isn't in the main release and I'd be happier staying on 22.04. The update was cancelled but now when I do apt update it is trying to upgrade to 23.04 again. Is there a way to tell the system that I want to stay on 22.04?
Comment: If you've applied any upgraded packages from 23.04 or *lunar*, I'd only go backwards using a non-destructive re-install (*you can cancel a release-upgrade during the download, but I'd not advise it once it started installing*). You mention *update was cancelled* which is unusual wording to me, as the *release-upgrade* process is different to the normal upgrading of packages, so it'll be helpful if you're specific - but Ubuntu releases are intended to go to newer release only; as users have backups they can restore if they need to go backwards for a reason (*it's why users create them*).
Comment: I cancelled it during the download process no packages were installed. It was a `release-upgrade` - how do I do a non-destructive re-install?
Comment: If you cancelled whilst it was still downloading packages, you should not need to do a re-install; just revert your sources so they use *jammy* (22.04) not *lunar* (23.04).  I don't have a system handy that was recently *release-upgraded* to check what was done, but I'm sure a copy of the *untouched* sources files are where expected (`/etc/apt/sources.list`) just with a different name (*I've done that myself*), OR you can just edit the file & return the codename to what it was (ie. *jammy*).  You didn't mention Server/Desktop, and I'm mostly desktop user, but I'd expect the same for both.
Comment: Feel free to write your own answer then, explaining what you did. Key to me was you were still downloading, thus no actual changes had occurred (*downloading can take awhile if you have loads of packages*)...  I couldn't recall what it was called (*the old file*) thus why I only commented. You can mention me, or not in answer; but you'll gain *rep*, and may help other users in the future. Well done for solving it.
Comment: That did the trick it was there under `sources.list.curtain.old` thank you.
Answer: For anyone else that happens into the same issue, I found sources.list.curtain.old in /etc/apt/ - I renamed the new one to .new and renamed the old one and it's not trying to update anymore.
Thanks to guiverc for the help.
Answer: You commented that you interrupted during download, so you should first remove the downloaded files to free up space using sudo apt clean.
Now you should set the release channel back to LTS. Open the Update Manager app, and click on settings after it loaded. Now switch to the "Updates" tab, and change "Notify on new Ubuntu update" to "Long-term supported release", and close it. If it asks you to update the source when clicked Close, click on "Update". Here is a picture about it (the language is not English for me, but the buttons are placed in the same places, so you can compare it with yours and I also use the Orchis theme, so the buttons may look different for you):


Image of compact set under piecewise continuous function

Question: Let $a,b>0\in\mathbb{R}$. Let $U$ be an domain in $\mathbb{C}^n$. Let $f:[a,b]\longrightarrow U$ be a piecewise continuous map. Then is $f[a,b]$ compact? If not compact, will it be bounded?
Ok. This is in the following context. I am given a piecewise smooth path $\gamma:[a,b]\longrightarrow U$. Where $\gamma(a)=z$ and $\gamma(b)=w$, for given $z,w\in U$. We are also given a function $\alpha:U\times\mathbb{C}^n\longrightarrow \mathbb{R}$, which is upper semicontinuous. Now it is said that $t\in[a,b]\longrightarrow \alpha(\gamma(t),\gamma'(t))$ is bounded and measurable. I wanted to know why the function is bounded. I know that $\gamma[a,b]$ is compact. And $\gamma$ being upper semicontinuous will attain its maximum on a compact set. But I am not sure about $\gamma'$.
Comment: What does "piecewise continuous" mean here?  How many pieces?  Finitely many? Are the pieces compact?  Open?
Comment: What have you tried?
Comment: The image of a compact space under continuous map is always compact. Regardless of what "piecewise" means and what $U$ is (as long as it is Hausdorff).
Comment: Please provide [additional context](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question/9960#9960), which ideally explains why the question is relevant to you and the community. Some forms of context include background and motivation, relevant definitions, source, possible strategies, your current progress, why the question is interesting or important, etc.
Comment: @SahibaArora I have added the context.
Comment: @kimchilover I have added the context of the question. There are finitely many pieces.
Comment: @user531706 Great. I have retracted my close vote.
Answer: Compact, not necessarily: On $[0,1]$ let $f(x) = x, 0\le x<1,$ $f(1)=2.$ Then $f([0,1]) = [0,1)\cup\{2\}.$
Bounded, yes: First, a lemma: If $f$ is continuous on $(a,b)$ and $f$ has finite limits at the end points, then $f(a,b)$ is bounded.
Proof: Suppose $\lim_{x\to a^+} f(x)=L,$ $\lim_{x\to b^-} f(x)=M.$ Let $\epsilon=1.$ Then there exists $\delta_a>0, \delta_a<(b-a)/3,$  such that $|f(x)-L|<1$ for $x\in (a,a+\delta_a).$ Thus for such $x,$
$$|f(x)| = |f(x)-L+L|\le |f(x)-L|+|L| <1+|L|.$$
Similarly, there exists $\delta_b>0,\delta_b<(b-a)/3,$ such that $|f(x)|<1+|M|$ for $x\in (b-\delta_b,b).$ It follows that $f$ is bounded on the set $(a,a+\delta_a)\cup (b-\delta_b,b).$
Since $f$ is continuous on the compact set $[a+\delta_a,b-\delta_b],$ $f([a+\delta_a,b-\delta_b])$ is compact, hence is bounded. It follows that $f(a,b)$ is bounded.
Now suppose $f$ is piecewise continuous on $[a,b].$ Then there exist points $a=x_0<x_1<\cdots <x_n=b$ such that $f$ is continuous on each $I_k=(x_{k-1},x_k)$ and has finite limits at the end points of $I_k.$ By the lemma, each $f(I_k)$ is bounded. The set $f(\{x_0,\dots x_n\})$ is also bounded. Therefore
$$f([a,b])=f(I_1)\cup \cdots \cup f(I_n)\cup f(\{x_0,\dots x_n\})$$
is bounded.


How to subscribe to a Q&A?

Question: I can't seem to find a way to subscribe to a Q&A to get notified about new answers. I know I can "favorite" a question but that doesn't notify me of updates.
Answer: At the bottom of each question, there is a question feed icon to subscribe to a question.

As the question author, you can also select "☑ Notify [email address] daily of any new answers".
Comment: thanks a bunch, I'll try that

How to subscribe to a Q&A?


Is stutter-step considered a bug?

Question: Many Blizzard games allow to cancel animations, so units can move farther while shooting. Warcraft (DOTA) and Starcraft are good examples where you can invest APM to make your units more effective.
I found this video where some guy demonstrates this for the Demon Hunter. It seems very effective and you can move farther than "normal" kiting where you wait for the animation to finish.
Is this also considered a bug, like the higher DPS with clicking? Should I bother to learn how to do this or will they fix it? I mean it is a bit unfair as melee characters do not have this option.
Comment: It's not a duplicate, it's describing a different behaviour to the click/hold down bug.
Comment: I created both questions as I think they describe two different aspects of the same action. DPS increase is not a requirement for stutter step execution.
Comment: possible duplicate of [Is there a difference in DPS depending on how you attack?](http://gaming.stackexchange.com/questions/68644/is-there-a-difference-in-dps-depending-on-how-you-attack)
Answer: Bashiok the D3 community manager already stated that they did it on purpose:

It's an intentional mechanic, not an exploit or bug. Our intent is
simply to make combat feel good and responsive, but the implementation
to hit that goal in the closed beta build is actually quite old. It's
likely you'll see changes within some future beta push that reflect
more what we're testing now internally, but of course it's possible
that won't be the final implementation either.1
Comment: Is there an equivalent for melee characters? I seems a bit unfair :)
Comment: It also work's for melee characters only that it's not as effective. Every attack with a little range on it can be "exploited" that way.
Answer: Yes.  If the developers wanted you to be able to move a unit that far while shooting, they wouldn't have made it require cancelling an animation.  This is what's called an 'exploit'.
Comment: Do you have a source and will it be fixed? Exploits are not always a bad thing. I want to know if there are plans to remove it from the game.
Comment: @ayckoster Sorry, can't predict the future.  If it's not a major exploit, I would expect them to just leave it the way it is.

Is stutter-step considered a bug?


After replacing a recirculating pump (and pressure regulator), shower won't run hot

Question: We've just had a our pressure regulator replaced, and a new recirculating pump installed.  All 3 showers used to get hot water reasonably quickly (15-20 seconds).  Now the shower furthest from the water heater won't heat up unless a shower or hot faucet in another bathroom is run.  It just runs luke warm at best.  The hot faucet in a sink in the same bathroom is the same - just luke warm, but no problem with flow rate.
What is stopping hot water reaching the shower, unless another bathroom's hot water is on?  Doesn't sound like an air blockage, and it seems that water is still flowing in the shower through the hot pipe, because it gets colder when the temp control knob is turned to "cold".  Weird and annoying!
Comment: Hello, and welcome to Home Improvement. Would you add a diagram of your piping and pumps?
Comment: I would if I had the plans!!  Water Heater (& recirculating pump) in garage on 1 side of 3500 sq ft single story.  All 3 bedrooms on opposite side of house (shaped like 3 sides of a square) with master bath furthest from garage.
Answer: Here's the answer:  The problem was solved when:
1)  The recirculating pump was connected the right way round to suck water back to the water heater from the far side of the house AND...
2)  The new digital timer was programmed correctly and left on AUTO not OFF....!
Still can't figure out why it got worse simply by replacing a non-functioning pump with a good one, that was turned off (taking 2 minutes instead of 15-30 secs).  But as long as it's better now I don't really care!
Answer: If this is one of those "recirculate hot in the cold line" systems, rather than a dedicated recirculating return system, I suspect a check valve is not working. Might also be the case with a dedicated return line too, as those usually return to the bottom of the water heater where things are fairly cold.
So you get mixed hot and cold rather than just hot, as water flows from both the return line (or cold acting as a return) and the hot line.
Possibly the work caused some debris to get into a check valve. Possibly the old pump had a built-in check-valve and the new one does not.
Comment: When the hot faucets / showers etc were first turned on after new recirculating pump was installed, I saw several secs of "rusty" water at each tap.  Presumably there is a dedicated recirculating return system. The water in it had not moved, prob. for 3 years!!  Didn't know I had this pump, & it wasn't plugged into power.  If there is "debris in a check valve", why do I get barely luke warm water from the hot tap/shower, but do get flow, but it won't get hot. However it flows hot within 30 seconds of turning on hot in another bathroom, (where hot water flows in 3-4 secs!)
Comment: So it turns out that the recirculating pump is a "sucker" not a "pumper"!  And further it was installed the wrong way round.  As a sucker, it was connected to the cold water side of the water heater, and when connected the wrong way around, instead of sucking cold water away from the farthest bathroom, it pumped lukewarm water from the bottom of the water heater to the bathroom.  Hence it took a long time and seeming flow to other bathrooms to get hot water to the end of the line!  Now it's the right way around it works.  Hot water in a few seconds.....
Comment: Write that up as an answer. It's perfectly fine to answer your own question on here....
Comment: Famous last words - there was hot water in a few seconds when the plumber was here.  But not since.  Been away so couldn't deal with it until now.  It takes over 2 minutes to get hot water to the far shower and the time is the same whether the recirculating pump is on or off.....  Sounds like this "check valve" issue is on point!!


Url rerwriting using htaccess

Question: i have a url (http://www.example.com/item/?items=26) and i want (http://www.example.com/item/items/26) using htaccess, please any one can help
Thanks
Comment: try like this.
RewriteEngine On
RewriteRule ^item/(.*)$ item/items=$1 [L]
Comment: @user3297972 did you tried the answer given by me ? It should work for you
Answer: Try this:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^items=(.+)$
RewriteRule ^(.*) /item/items/%1? [L]

You can also use this to make it more generic:
RewriteCond %{QUERY_STRING} ^(\w+)=(\d+)$
RewriteRule ^(.*) /item/%1/%2? [R=302,L]

This will check any key and it's value as only numeric.
Reference: https://wiki.apache.org/httpd/RewriteQueryString
Comment: @KailashYadav i have used your second code this will redirect to http://www.example.com/items/26 but i need http://www.example.com/item/items/26 here is my code
Comment: code

RewriteEngine On
RewriteCond %{QUERY_STRING} ^(\w+)=(\d+)$
RewriteRule ^(.*) /item/%1/%2? [R=302,L]
RewriteBase /

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . /index.php [L]
Comment: @user3297072 there must be someother rule which is messing up. Goto this site: `http://htaccess.madewithlove.be/` and enter this as `http://domain.local/item/?items=26` enter htaccess as`RewriteEngine On RewriteCond %{QUERY_STRING} ^(\w+)=(\d+)$ RewriteRule ^(.*) /item/%1/%2? [R=302,L]` and click on check now

Url rerwriting using htaccess


Python battleships: getting a user input for how many ships they want

Question: I am trying to get the game to take an input for how many ships the user would like, and to place that many ships. I have put the coordinates into a list and that is how I am storing them, and checking if it is a hit. But the ships get placed over each other, and with this list method, I don't know how to first of all, check they are not overlapping, and second of all, change it so they aren't.
<code>    from random import randint
    print('Welcome to Battleships for 1 player! Please be careful with entries, as if you get it wrong, you will still lose a go!')
    print('Good luck!')
    print('')
    no_of_goes = int(input("How many goes would you like: "))
    size_of_board = int(input("And how big would you like the board to be: "))
    if size_of_board > 56:
        print("That board will be too big to fit on the screen (max 56)")
        size_of_board = int(input("And choose a more sensible number: "))
    no_of_ships = int(input("And finally, how many ships would you like?: "))
    board = []
    # printing out the board
    for x in range(size_of_board):
        board.append(["O"] * size_of_board)

    def print_board(board):
        for row in board:
            print ("  ".join(row))
    print_board(board)
    # the lists that will become the locations
    ship_rows = []
    ship_cols = []
    # generating random locations
    def random_row(board):
            return randint(0, len(board) - 1)

    def random_col(board):
            return randint(0, len(board) - 1)
    # adding locations to lists
    ships = list(range(no_of_ships))
    for i in ships:
        row = random_row(board)
        col = random_col(board)
        ship_rows.append(row)
        ship_cols.append(col)
        ##
        ## And this is my attempt (didn't work)
        ##
        for row in ship_cols:
            if row == ship_cols and col == ship_cols:
                ship_rows[-1] = random_row(board)
                ship_cols[-1] = random_col(board)
    # allowing to see where ships are and logging how many ships have been hit
    print(ship_rows)
    print(ship_cols)
    ship_count = [1]
    ## I couldn't find a way of ending the game once the ships were sunk, so I stuck in a recursive function (sorry)
    def printing_stars():
        print('You have won!! ' +'*' * 56)
        printing_stars()
    for turn in range(no_of_goes):
        # asking for their guesses
        print('Turn ' + str(turn + 1) + ' out of ' + str(no_of_goes))
        guess_col = int(input("Guess Col:")) - 1
        guess_row = int(input("Guess Row:")) - 1
        for item in ship_rows:
            # If they hit, it gives a '!'
            if len(ship_count) == no_of_ships and guess_row == item and guess_col == ship_cols[ship_rows.index(item)]:
                print("You have won!!!! Congratulations")
                board [guess_row][guess_col] = '!'
                print_board(board)
                printing_stars()

            elif guess_row == item and guess_col == ship_cols[ship_rows.index(item)]:
                print ("Congratulations! You sunk one of my battleships")
                board [guess_row][guess_col] = '!'
                print_board(board)
                ship_count.append(1)
                break
        else:
            # all misses
            if (guess_row < 0 or guess_row > size_of_board - 1) or (guess_col < 0 or guess_col > size_of_board - 1):
                print ("Oops, that's not even in the ocean.")

            elif board[guess_row][guess_col] == "X" or board[guess_row][guess_col] == "!":
                print ("You guessed that one already.")
                turn -= 1
            else:
                print ("You missed my battleship!")
                board[guess_row][guess_col] = "X"
            print_board(board)
            if turn == (no_of_goes - 1):
                print('Game Over')
                break
</code>
Any ideas? Would be very grateful :)
Comment: is this from codecademy?
Answer: Some suggestion for your code :
You could model the player board with a numpy array like this :

Size : i lines and j colums => (i, j)
0 if water
1 if water that was shot by the palyer
2 if ship unharm
3 if ship case is hit

Once they are no more 2, it means there is a winner.
With this system, you can tell a player if he is shooting twice the same spot and you could also generate a display.
Moreover, to randomly position the ship, you could use this procedure :

Set ship size : let's say 4 spots.
Choose randomly 0 or 1 : 0 to place the ship horizontaly, and 1 to place the ship verticaly

Now we have to look if it is placed horizontaly or verticaly.
If it's horizontaly placed :

Choose 2 random number between 0 and j-4 and 0 and i. That will be your ship first spot coordinate, it means, this spot turn to 2, and the 3 spot on after it also.

Example with a 5*5 board, and a position pick of (1,0) for an horizontal ship
<code> 00000
 22220
 00000
 00000
 00000
</code>

I let you take care of the case verticaly, just have to change the random number generation indices.

Then that solution doesn't prevent from getting a ship on an other one. One simple solution, is with this loop :
<code>while True:
    if all ship placed:
        break

    pick number
    Try to place the ship. (with an if statement, check if one of the spot your gonna change is already a 2.)
</code>
That solution should work as long as it is possible to place all the ship on the board. If it's impossible, you'll the loop won't end. Moreover if the number of ship is not limited in regard of the board size, it could be long to place them.
You can then keep improving the method with more complicated scenario. One other solution would be to check after each ship positioning where you still have place to put one.
Comment: Thank you so much for the input! But if it was going to be a valid game, having a 2 as an unharmed ship would defeat the point of guessing where it is wouldn't it? Or it this just how the computer sees it and not how it would appear on the console
Comment: Of course you don't show it like that ! For the computer, you store the data like that, for the user, you create a display_matrix that will show the exact same thing but while replacing the 2 by 0, so the ship stay hidden, and so that you can still see where you shoted.


Media Query Fail inside Facebook Iframe

Question: I am looking to find out why my @media queries are triggering when they are not supposed to, inside a Facebook Canvas iFrame Application.  On a 810px wide page tab, the following media query is getting triggered:
@media only screen and (max-width: 767px) {}

Can someone explain to me why this would be the case?  html and body are showing 810px wide.  It works properly when viewing the same page on its own in a browser, as the query triggers as soon as I scale the browser down to 767px...
FYI this is the iFrame code that Facebook is displaying on my page tab:

ALSO: The queries work just fine on the full app page (http://apps.facebook.com/...), as I have canvas width set to "fluid".  The page tab doesn't seem to use this setting and only has a narrow 520px or wide 810px option.
Thanks for the input!
Answer: I have solved the problem.  It turned out it was the viewport zoom or scale that was causing the queries to trigger.  I did not have the default zoom level set on my browsers, so while it appeared to be 810px wide, it was actually something like 729, due to the zoom.  To ensure users have their viewport zoom set to default, use the meta tag:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Media Query Fail inside Facebook Iframe


Can't build VLCKit Framework on macOS

Question: From the code here:https://code.videolan.org/videolan/VLCKit
And instructions here: https://wiki.videolan.org/VLCKit/#Building_the_framework_for_macOS
I am trying to build the framework, but when building libvlc in Xcode 7.3.1 it just seems to get stuck on:
<code>Build target Build libvlc of project VLCKit with configuration Release
[[1;32minfo[0m] Preparing build dirs
Cloning into 'vlc'...
</code>
Any idea how I can build this?
Answer: This is because libvlc need to clone the 'vlc' project from net first.
The 'vlc' project will be clone into 'libvlc' forder.
when the cloning is finished, it will start compile.

Can't build VLCKit Framework on macOS


Does gradle download a fresh copy of dependencies for each new project?

Question: I have been endlessly searching the internet and reviewing some questions here for the entire past week since I decided to move to Android Studio
I really dont understand why you have to be online at least once in order to build a project in Android Studio
What was so special in Eclipse that it was able to do all the compiling offline and the supposedly better build system (gradle) can't.
Up to now I still dont understand all this fuss I see about gradle, what is it exactly that gradle fetches online when I have all the necessary files required to build my project in my computer?.
This is really frustrating me as I don't guarantee myself to always have internet access
Comment: Possible duplicate of [Build Gradle repository for offline development](http://stackoverflow.com/questions/28436473/build-gradle-repository-for-offline-development)
Answer:

It doesn't need internet connection to built your every project.
If you add additional library dependencies which needs to be downloaded, then it does require internet connection
Gradle is one of the best out there, and open source!
And you can though switch between online and offline. Android Studio helps to do that with ease
Answer: First of all, Gradle has a local cache to store downloaded dependencies. If your new project requires some dependency, which was already used by some other project and stored in cache, then no need to download them again.
The second, why you may need to have an internet connection, is the ability to use on-line repositories, like Maven Central. You don't need to dowload all the jars manually and add them under your application's classpath and then manage it's transitive dependencies. All it's done by Gradle. Sure, Gradle let you provide local dependencies, if you need it, just rely on it as on files in your local filesystem. By the way, you may not specify exactly version of some dependency, but, for example, the latest one (that's called "dynamic version" and could be usefull during development). In that case, Gradle will check, whether the newer version is available and download it automatically.
And the last, if you still need it, you are free to make it running in offline mode.
Comment: Thanks, I think I'm starting to put the pieces together now


Custom variable in OpenERP template

Question: I would need some kind of counter for displaying position of element in list.
e.g. in invoice I have entries and I'm iterating through it like this:
[[ repeatIn(o.invoice_line,'l') ]]

now, I'm displaying, name, price etc. like this
[[ l.name ]] [[l.quantity]]

but I need position in order as well? I tried to have
[[ repeatIn(o.invoice_line,'l') ]]
[[ counter = 1 ]]

and in iteration:
[[ counter ]] [[ l.name ]] [[l.quantity]]
[[ counter = counter + 1 ]]

I'm not sure if I'm doing right thing and if custom variables are even allowed in open erp template
Comment: I think, You want serial number in line like 1. price, quantity 2. price, quantity etc. If you want that than you can create a function which will work like your counter and you can also display number by given return value in that function.
Comment: Where should I add this function? Into report_sxw.py? I would like to avoid modifying core part of openerp and do it by extending it...is it somehow possible?
Comment: yes, in .py side write function that will return integer number. And if you don't want to write code than tags are also available for this. for example that will do like counter. What you want ? Tag or function ?
Comment: tag would be fine. I tried the code above, but nothing was printed out...
Answer: There are two tags useful for printing sequence.

<seq/> and
<seqReset/>

First use reset the sequence using <seqReset/>
In report .rml file, At Column label after write <seqReset/> and in repeatIn use <seq/>
For example:

      <para style="terp_tblheader_Details_Right">Price<seqReset/></para>

And

        <para style="terp_default_9"><seq/> [[ format(line.name) ]] </para>

Hope this will help you.
Comment: Is this possible if I work with Open Office Writer to edit OpenERP templates?

Custom variable in OpenERP template


Configuring arrow keys on media

Question: I just installed Ubuntu and I'm extremely happy about it, I can see myself switching to Linux from Windows permanently.
There's a slight problem however, when I'm watching a movie, arrow keys skip forward by 1 minute. Is it possible to configure this?
If so, how?
Comment: Welcome to AskUbuntu! Could you be a little more specific as to which program you are using when this happens?
Answer: If you're talking about the default video player (called Gnome Videos (was Totem)), this feature is in the Wishlist category. It's marked In Progress after about 4 years, so there's no telling when it might actually arrive. It's not going to happen. According to Bastien Nocera [totem developer]:

I don't want to see options like that in Totem. FWIW, use Shift+Left Arrow if
  you want to skip back by 5 seconds.
... I rejected a patch to make the arrow keys skip time configurable.

If you do wish to configure, you might want to look at alternatives such as VLC, SMPlayer, etc.
In VLC, the option is available, but hidden away. Go to the Tools menu and open Preferences. In the bottom-left corner, change Show Settings from Simple to All, and search for hotkeys:

Set the jump lengths to the duration you want (in seconds).
You can also change the shortcuts for the jumps. (This option is also available in the Simple interface under the Hotkeys section - only the jump duration needs the advanced view.)
Comment: Thanks I've installed VLC do you happen to know where I can find the option to configure the keys?
Comment: That bug report appears more to do with the playback speed, not skipping... I know that mentions it, but this does not fully resolve the issue.
Comment: @Wilf yes, but someone posted a patch which dealt with that *and* one that dealt with skip time configuration. The second patch was rejected. Please read through. Or at least read the line I quoted, which explicitly states why the dev rejected the patch.

Configuring arrow keys on media


When is the center of group contained in the derived subgroup

Question: Let $N$ be a group. Assume that $N$ is torsion-free, finitely generated and nilpotent. I read somewhere that
$$ Z(N) \subset [N,N] \iff N \text{ cannot be written as a direct product of groups } N = A \times B \text{ where }A \text{ is non-trivial abelian.}$$
One implication is clear to me: $\implies$. I prove it by contraposition: assume $N$ can be decomposed as $A\times B$ where $A$ is non-trivial abelian. Then it is clear that $$ Z(N) = Z(A) \times Z(B) = A\times Z(B).$$
On the other hand, we have that
$$ [N,N] = [A,A] \times [B,B] = \{1\} \times [B,B].$$
If we had that $Z(N) \subset [N,N]$, we would need that $A\subset \{1\}$, which is clearly not possible as $A$ was non-trivial. So by contraposition, we have proven the first implication.

Now my problem is with the other implication. I don't know how I can prove the converse. I don't even know how to go about doing that. My gut suggests contraposition again, but then I have to use the assumption that $Z(N) \not\subset [N,N]$ to somehow construct a direct product decomposition of $N$ which has a non-trivial abelian factor, and I don't see how I can go about doing something like that.
Does anyone have any suggestions?
Thanks in advance!
Edit: I added the assumptions that $N$ is torsion-free, finitely generated and nilpotent. These are the only groups I am interested in in the context of my research.
Comment: I suggest that you consider the possibility that the result you are trying to prove is not true, and look for a counterexample.
Comment: Keep looking (3-generated 2-step nilpotent groups).
Comment: Hi @DerekHolt, thank you for your response! I can't seem to find a counterexample. Moreover, I am in fact only interested in groups that are finitely generated, nilpotent and torsion-free. I edited my question to reflect this. Sorry for the confusion!
Comment: I suspect the statement is correct if you replace $[G,G]$ with $\sqrt[G]{[G,G]}$, i.e. the set $\{ g \in G \mid \exists n \in \mathbb{N}: g^n \in [G,G] \}$. That could also be a hint on finding/constructing a counterexample to the original statement...
Comment: It is still not true for torsion-free finitely generated nilpotent groups.
Answer: This claim does not hold. A counterexample (even in the realm of finitely generated, torsion-free and nilpotent groups) is that of the Heisenberg group $H$ of upper triangular $3\times 3$-matrices with entries in $2\mathbb{Z}$. It can easily be seen that in this case
$$ Z(H) \not\subset [H,H].$$
Yet, it is easy to check that $H$ does not have any abelian factor.
The claim can however be proven for groups that are nilpotent, torsion-free and radicable. This has to do with Mal'cev completions and the correspondence between Mal'cev completions and rational Lie algebras.


syncing perlbrew and cpan install locations

Question: I'm using perlbrew to run a local perl in my home directory, and cpan to install new modules.  However, I seem to have something configured wrong.  When I use cpan it always installs libraries to the ~/perl directory, but my perlbrew is located in ~/perl5 directory.  This is causing some issue with creating appropriate PERL5LIB directory, rather I should include perl or perl5 libs and in what order.  I seem to keep running into chicken and the egg problem where including either first results in loading a wrong module or complaints about the wrong version used.  Specifically it complains that the 5.8.8 perl version (first I installed before deciding to upgrade to a slightly-less-ancient version, and still the version of /bin/perl) conflicts with the 10.1 libraries I'm using.
I figure this can likely be fixed by updating configuration files, but I'm not sure what to change.  I look at my cpan config.pm and I don't see anything defining installation direction, in fact I'm not sure how cpan knows to install locally rather then trying to install to the global cpan directory.
Can anyone point me to the appropriate configuration values I need to change to get cpan to update my perlbrew library, rather then getting two separate libraries?
Edit
Okay I'm very blind.  The answer was right in my configuration file at ~/.cpan/CPAN/MyConfig.pm.  I swear I looked at the file a few times, even doing a search for the word perl to hunt down any line that may point to my ~/perl directory, and yet somehow missed the blindingly obvious configuration option I was looking for...not sure how.
Anyways, once I saw it I just had to change where it pointed, which took a little trial in error.  I changed this line:
'makepl_arg' => q[PREFIX=~/perl],

to
'makepl_arg' => q[PREFIX=~/perl5/perlbrew/perls/perl-5.10.1/],

which of course is the location of the perl version I'm using for perlbrew.  This appears to fix my problem, and should have been easy if I wasn't blind.
I do have one annoyance, I have both this line and my PERL5LIB variables, set in ~/.bashrc, effectively hard coded to point to the perl-5.10.1 version of perllib, meaning if I decide to switch to another perl version I would need to update both references or have issues again.  I'm not sure how to make cpan, or my PERL5Lib for that matter, know to infer which version of perl from the perls directory it should use.  That's not too big of a problem to me, I don't think I'll be allowed to upgrade past 5.10.1 (even though I want to) so it's unlikely I'll ever change this value.  Otherwise it works fine now.
Comment: What does `which cpan` output?
Comment: What's the output of `set | grep ^PERL`, and what's the output of `echo 'o conf' | cpan | grep 'make_\|mbuild_'`?
Comment: @ThisSuitIsBlackNot the answer is ~/perl5/perlbrew/perls/perl-5.10.1/bin/cpan.  However, I seem to have found a proper fix as mentioned in my edit.  I'll likely live this open for a few hours just so those that started to answer can see that I found a fix, and/or complain if it's a stupid fix before either closing it or self answering if no one else answers.  If you or ikegami wish to get credit for putting some effort into answering my question either is welcome to post an answer either repeating my fix or potentially pointing out any flaw in my fix and I'll select it to give you credit
Comment: @ikegami nothing returns for the second.  quite a few variables are set for the first, However, I seem to have found a proper fix as mentioned in my edit. As I said in my above comment, I'll self answer in a little while possible, but wanted to give you a chance to jump in with an answer to get credit first if you were interested :)
Answer: Two problems.

Your CPAN is partially configured overriding the location at which it should install modules. Remove this override by clearing makepl_arg.
From within cpan:
o conf makepl_arg ""
o conf commit

From sh:
echo -e -n 'o conf makepl_arg ""\no conf commit\n' | cpan

Your PERL5LIB is telling your perl to look for modules where it shouldn't. Unset it by removing the instruction that sets it in ~/.bashrc.

You may have other problems, but we'd need to know the output of the following sh command to know for sure:
set | grep ^PERL ; echo 'o conf' | cpan | grep 'makepl_\|make_\|mbuild_'

Comment: you are right, it seems it was over configured.  Not sure how that happened, but given the insanity I was going through with systems at the time I configured this I'm not too sure.  I'm afraid I can't give the full content of the set command since the system I'm configuring isn't currently able to connect to internet (long story) so it's a little difficult to copy long messages over; but removing the changes do seem to work fine thank you.
Comment: I'm particularly interested in `PERL_MM_OPT` (should probably be blank), `PERL_MB_OPT` (should probably be blank), `PERL5LIB` (already provided; should be blank), `PERLLIB` (likely blank; should be blank) and `PERL5OPT` (likely blank; should probably be blank). I'm specifically disinterested in any `PERLBREW_*` variables.


Help understanding how to Evaluate divisions

Question: Morning to everyone,
I am trying to understand a problem I came across, which I can solve but I still do not understand the logic behind it.
The problem is as follow

Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries
= [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000]

The equation is represented in the following manner:
a/b = 2 | b/c = 3
I need to find the value of the queries i.e.
a/c and b/a
The output for a/c is 6 and for b/a is 0.5
I understand how this result is achieved but not the logic.
For example: to get a/c we do the following
a/c = a/b x b/c -> (the two b cancel each other) -> you're left with a/c -> which gives you 6 (because a/b =2 and b/c = 3 -> 2x3 = 6)
I have two questions here:

If a/b is equal 2 then when the b gets cancelled, how is a alone
equal 2?(same for b/c)

If the result is a/c why is this represented
as a division but the result is achieved by multiplying?

This obviously shows that I don't have a good grasp on algebra and I will be revising this, my understanding is that this specific type of calculation is part of linear algebra variable division? or is there a specific topic I can read to understand this part specifically (and then start from the basics of algebra)
Thank you
Comment: Do you have a teacher or someoner in a similar position you can discuss this with?  I hope I don't sound unhelpful, but in my experience, understanding basic concepts takes a lot of back and forth discussion, and this is much easier to achieve face to face than by asking online.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: unfortunately I don't. I would like to read something that can allow me to familiarise with this but in the meantime I wanted to know what specific section of math this is so I could get an overview of this.
Answer:
If a/b is equal to 2 then when the b gets cancelled, how is a alone equal 2?(same for b/c)

That's not how it works. Consider
$$\frac ac = \frac ab \times \frac bc = 2\times3 = 6$$
It doesn't tell you anything about $a$ in particular. You know $\frac ac$ is 6 and nothing else. There are multiple solutions to his i.e: multiple choices of $a$ and $c$ that make this work. For instance $a=2$ and $c=\frac13$. But also $a=6$ and $c=1$.

If the result is a/c why is this represented as a division but the result is achieved by multiplying?

You are multiplying fractions. And the result of this product of fractions is again a fraction.

Ask questions in the comments if something is unclear. Cheers!


Using qrcode in Python 3.6 to create batches of QR Codes as images

Question: I'm running Python 3.6 on a Windows 10 machine and would like to create batches of QR codes as PNGs directly from python.  I'll be using the qrcode to create batches of 100 to 200 individual QR codes.  The images will then be used in a mail merge to create individual documents.  I can create individual images using the qr.exe script, but am not able to create the QR code PNGs within Python.
While reading through the documentation for qrcode, I am running into some trouble getting the "Pure Python PNG" working (https://github.com/lincolnloop/python-qrcode/blob/master/README.rst).
Specifically, when I try to install pymaging using PIP at the command prompt
pip install git+git://github.com/ojii/pymaging.git#egg=pymaging
pip install git+git://github.com/ojii/pymaging-png.git#egg=pymaging-png
I get the following reports
Collecting pymaging from git+git://githumb.com/ojii/pymaging.git#egg=pymaging
Cloning git://github.com/ojii/pymaging.git to c:\Users\B\AppDataq\Local\Temp\pip-build-jioh63js\pymaging
Then I get the following error
Error [WinError 2] The system cannot find the file specified while executing command git clone -q git://github.com/ojii/pymaging.git c:\Users\B\AppDataq\Local\Temp\pip-build-jioh63js\pymaging
Cannot find command 'git'
I've looked at the temp folder and do not see any pip* folders.  Do you have any suggestions on how to get pymaging installed?
-- Update --
Once git is installed the commands can be run from git's bash and pymaging is installed.
Comment: do you have `git` installed?
Comment: Thanks!  I downloaded the most recent version of git and from the git bash I was able to install pymaging.
Answer: The documentation for creating batches of QR codes as images in Python 3 was a bit slim, specifically the final steps to writing the actual image files (see qrcode 5.3 documentation), so I wanted to share some code I modified and got working.  The original code for Python 2.7 came from prasopensource's blog.  Below is the script I created for Python 3.6.
<code>import qrcode, os.path
print('What is the name of the file containing the data for the QR codes?')
fname = input().strip()
file = open(fname, "r")
print()
for x in file:
    x = x.rstrip()
    qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L,box_size=10,border=4,)
    qr.add_data(x)
    qr.make(fit=True)
    img = qr.make_image()
    file_name = x + ".png"
    print('Saving %s' % file_name)
    image_file = open(file_name, "w")
    img.save(file_name)
    image_file.close()
file.close()

# INFORMATION ABOUT QRCode SETTINGS
#The version parameter is an integer from 1 to 40 that controls the size of the QR Code (the smallest, version 1, is a 21x21 matrix). Set to None and use the fit parameter when making the code to determine this automatically.

#The error_correction parameter controls the error correction used for the QR Code. The following four constants are made available on the qrcode package:
#ERROR_CORRECT_L
#About 7% or less errors can be corrected.
#ERROR_CORRECT_M (default)
#About 15% or less errors can be corrected.
#ERROR_CORRECT_Q
#About 25% or less errors can be corrected.
#ERROR_CORRECT_H.
#About 30% or less errors can be corrected.

#The box_size parameter controls how many pixels each "box" of the QR code is.

#The border parameter controls how many boxes thick the border should be (the default is 4, which is the minimum according to the specs).
</code>


Can I install two thermostats on one furnace/act unit? I will be using one in living room, the other in a hallway

Question: The reason is that there is a gas fireplace(stove) in the living room that has the pilot on all year. Currently the thermostat is in the hall keeping the back of the house cool. The heat from the fireplace pilot keeps the living room too warm so I want to control the ac unit from the living room in the summer and the heat from the hall in the winter. I am using nest thermostats
Comment: Hello, and welcome to Stack Exchange. My guess is this might work with "dumb" thermostats, but the Nest units would be too intelligent and would get totally confused.
Comment: Wouldn't it be cheaper to just turn the darn gas off to the pilot during the summer??
Answer: I'd suggest looking for a thermostat that supports remote sensors. I personally own ecobees which support up to 64 wireless sensors per unit. You can decide which of the sensors participate in measuring the average temperature for each time slot of the day. I believe Honeywell offers thermostats that support sensors as well in both the wired and wireless variety.
Answer: You could use a simple and cheap single double pole switch. In 1 position the system would use the hall thermostat in the other position the system would use the living room thermostat. The switch can be a very inexpensive one (spdt) with the common going to the furnace and the NO normally open to one. Then the NC normally closed to the other thermostat the system would chose the thermostat based on the switch position. If you have a higher end system a double pole switch may be required with the heat on one pole and the cooling on the other pole but both wired the same with NO, NC and common going back to the furnace / AC control.
Comment: I might add there are also 4PDT and 6PDT switches which simplify the question of which wires need to be switched.
Comment: Where can I get a 6PDT switch.
Comment: Look on line they are not cheap but you only need a low voltage one


Django migration: `AlterUniqueTogether` fails with `constraint does not exist` but I think it's there

Question: I'm trying to run the following migration using Django 2.2:
class Migration(migrations.Migration):

    dependencies = [
        ('actstream', '0002_remove_action_data'),
    ]

    operations = [
        migrations.AddField(
            model_name='follow',
            name='flag',
            field=models.CharField(blank=True, db_index=True, default='', max_length=255),
        ),
        migrations.AlterUniqueTogether(
            name='follow',
            unique_together=set([('user', 'content_type', 'object_id', 'flag')]),
        ),
    ]

The model before the git commit that adds the migration has the following constraint:
unique_together = ('user', 'content_type', 'object_id')

And after the git commit that adds the migration:
unique_together = ('user', 'content_type', 'object_id', 'flag')

(flag is a new field and it's also been added to the unique_together constraint).
When I try to apply the migration, I get the following error message:
psycopg2.errors.UndefinedObject: constraint "actstream_follow_user_id_content_type_id_object_id" of relation "actstream_follow" does not exist

Inspecting my database as it is without the migration, tho, I see the following:

What am I missing?
Thanks!
Answer: Seems to be a duplicate of this:
Django unable to migrate PostgreSQL: constraint X of relation Y does not exist

The problem turned out to be that I converted the database to PostgreSQL from MySQL using the tool pgloader, and this tool converts constraints by creating them as indexes in PostgreSQL, whereas the Django PG backend creates them as constraints. So when the migration runs, it only looks for constraints and doesn't find any.

I fixed this by dropping the index and re-creating it as a true constraint with:

drop index actstream_follow_user_id_content_type_id_object_id;
alter table actstream_follow add constraint actstream_follow_user_id_content_type_id_object_id unique(user_id, content_type_id, object_id);

Comment: If you feel it is a duplicate then why are you copying it here? Just mark your question as duplicate...
Comment: Sorry, I didn't know it was an option. Will do now.


User: XYZ does not have permission='SEND' on address

Question: I am able to authenticate via web console as well as via the bin/artemis producer command with credentials from my LDAP server. When I use the same credentials with mosquitto_pub to the same topic the log says
User: $username does not have permission='SEND' on address $address"

I've verified the resolved roles in the logs as well - they are the same for mosquitto_pub as for artemis producer. In my case they resolve a producer role which has admin privileges.
Is there any difference in authorization depending on the protocols? As it seems the authorization works for the CORE protocol and also for AMQP (I've tested both via artemis producer).
Unfortunately I cannot cross-check that with the artemis producer --protocol MQTT - this fails with "protocol MQTT not supported".
Comment: There shouldn't be any difference with authorization between protocols as they're all doing the same thing ultimately. Also, the `producer` command only supports core and AMQP. Lastly, it might help to get everything working as you expect *without* LDAP first (e.g. using the standard properties files for users and roles & standard security-setting entries). [Gall's Law](https://en.wikipedia.org/wiki/John_Gall_(author)#Gall's_law) and all that.
Answer: As noted in the documentation, the legacy admin permission is not mapped to the send permission:

ActiveMQ 5.x only has 3 permission types - read, write, and admin. These permission types are described on their website. However, as described previously, ActiveMQ Artemis has 9 permission types - createAddress, deleteAddress, createDurableQueue, deleteDurableQueue, createNonDurableQueue, deleteNonDurableQueue, send, consume, browse, and manage. Here's how the old types are mapped to the new types:

read - consume, browse
write - send
admin - createAddress, deleteAddress, createDurableQueue, deleteDurableQueue, createNonDurableQueue, deleteNonDurableQueue, manage (if mapAdminToManage is true)

Therefore, your producer role needs the write permission.
It's not clear why the producer command is working for other protocols (i.e. core & AMQP), but based on what you've provided I believe this is why it isn't working for MQTT.
Comment: The situation does not occur anymore and seems not reproducible to myself. The only thing I did though was to reset my Artemis broker and to reset the LDAP records completely. Thanks for the hints anyway, maybe I had messed up my roles. I'll accept this answer because it seems to be a legitimate cause.


adding a double value to an unsigned 64-bit value yields weird results

Question: int main(int argc, char *argv[])
{
    uint64_t length = 0x4f56aa5d4b2d8a80;
    uint64_t new_length = 0;

    new_length = length + 119.000000;

    printf("new length  0x%"PRIx64"\n",new_length);

    new_length = length + 238.000000;

    printf("new length  0x%"PRIx64"\n",new_length);

    return 0;
}

With the above code. I am adding two different double values to a unsigned 64-bit integer.I am getting the exact same result in both the cases.The output of the program is show below
$./a.out
new length  0x4f56aa5d4b2d8c00
new length  0x4f56aa5d4b2d8c00

I would expect two different results but that is not the case.I have also tried type-casting the uint64_t value to a double as in
new_length = (double)length + 119.000000;

But this too doesn't seem to help.Any idea on what might be the problem?
Comment: possible duplicate of [Why is this true?](http://stackoverflow.com/questions/4094117/why-is-this-true)
Answer: Since you adding a floating-point operand, both operands are implicitly cast to double and the addition is done using floating-point arithmetic.
However, double doesn't have enough precision to exactly hold either of the following values:
0x4f56aa5d4b2d8a80 + 119.0  (requires 63 bits of precision)

0100111101010110101010100101110101001011001011011000101011110111
 <-------------------63 bits of precision---------------------->

0x4f56aa5d4b2d8a80 + 238.0  (requires 62 bits of precision)

0100111101010110101010100101110101001011001011011000101101101110
 <-------------------62 bits of precision--------------------->

Standard IEEE double precision only has 53 bits of precision.
The result is that both of them get rounded to the same final value of:
0x4f56aa5d4b2d8c00  (53 bits of precision)

0100111101010110101010100101110101001011001011011000110000000000
 <-----------------53 bits of precision-------------->

If you want to avoid this rounding, you should avoid floating-point arithmetic altogether by casting the operands to integer. (or just using 119 and 238 instead)
Answer: Floating point arithmetic is not precise. As numbers get bigger, the accuracy of lower digits is reduced.
0x4f56aa5d4b2d8a80 is a Very Large Number.
What is happening in
new_length = length + 119.000000;

Is that length + 119.000000 is getting cast to a double, to do the addition. That double is rounded, rather dramatically, because it's so large. It is then cast again to the integral type uint64_t when it is assigned to new_length.
When you call
new_length = length + 238.000000;

It happens that the rounded result ends up being the same.
What you really want to do is
new_length = length + (uint64_t)238.0;

That will give you the answer you want. It will initially cast the double to an integral type, which is added precisely.
Comment: Floating-point *is* precise.  You can repeat the same experiment over and over and get identical results.  Those results may not align with your expectations based on your experience with the real numbers, but they are certainly precise.


Expandable table in React material ui

Question: I am trying to have expandable list items in a table with constant header. For this I am using Table and ExpansionPanel component from React material ui 1.0.0-beta.34. However, table is not alligning well. All the body data comes under one header TableCell.
Here is my code.
Table component:
    import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Table, { TableBody, TableCell, TableHead, TableRow } from 'material-ui/Table';
import Paper from 'material-ui/Paper';
import { styles } from './styles';
import ExpandableTableRow from 'client/components/expandable-table-row';

class GenericTable extends Component {
    render() {
        const { classes, items, headItems } = this.props;
        return (
            <Paper className={classes.paper}>

                <TableHead>
                    <TableRow>
                         {headItems.map((n, i) => {
                            return <TableCell className={classes.column} key={i}>{n}</TableCell>
                        }) }
                    </TableRow>
                </TableHead>
                <TableBody>
                    {
                        !items.length &&
                        <TableRow>
                            <TableCell colSpan={12} className={classes.center}>

There is no data to display

                            </TableCell>
                        </TableRow>
                    }
                    {items.map((item, i) => {
                        return (
                            <ExpandableTableRow key={i} item={item}/>
                        );
                    })}

                </TableBody>

            </Paper>
        );
    }
}

GenericTable.propTypes = {
    items: PropTypes.array.isRequired,
    headItems: PropTypes.array.isRequired,
};

export default withStyles(styles)(GenericTable);

ExpandableTableRow component:
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import ExpansionPanel, {
  ExpansionPanelSummary,
  ExpansionPanelDetails,
} from 'material-ui/ExpansionPanel';
import Typography from 'material-ui/Typography';
import { styles } from './styles';
import { TableRow, TableCell } from 'material-ui/Table';

class ExpandableTableRow extends React.Component {

    render() {
        const { classes, item } = this.props;
        return (

                <ExpansionPanel>
                    <ExpansionPanelSummary>
                        <TableRow>
                            <TableCell><Typography>{item.a}</Typography></TableCell>
                            <TableCell><Typography>{item.b}</Typography></TableCell>
                            <TableCell><Typography>{item.c}</Typography></TableCell>
                            <TableCell><Typography>{item.d}</Typography></TableCell>
                            <TableCell><Typography>{item.e}</Typography></TableCell>
                            <TableCell><Typography>{item.f}</Typography></TableCell>
                        </TableRow>
                    </ExpansionPanelSummary>

                <ExpansionPanelDetails>
                    <Typography>
                        Expansion panel expanded
                    </Typography>
                </ExpansionPanelDetails>
                </ExpansionPanel>

        );
    }
}

ExpandableTableRow.propTypes = {

};

export default withStyles(styles)(ExpandableTableRow);

I am trying to make this work. Any help is appreciated.
Answer: This is how I solved this problem earlier. I wrapped a Collapse transition inside a TableCell and set it's hidden and in prop. Example:
 <TableCell padding={'none'} colSpan={12}>
    <Collapse hidden={!open} in={open}>
       {
         <ItemComponent/>
       }
    </Collapse>
 </TableCell>

Answer: Im also looking into the same problem. Apparently, material UI has an issue thread regarding expandable table rows. this link might help you.
Edit: React now has docs for Collapsible Table here. https://material-ui.com/components/tables/#collapsible-table

Expandable table in React material ui


Hot to Neutral Short?

Question: My wife called me home from work because the lights in several rooms stopped working.
I came home expecting a tripped circuit breaker or GFCI, but I found no such thing.  Instead, after pulling out my non-contact voltage detector, I discovered that there was indeed voltage on the lines, both in the hot and neutral portions of my wall receptacles.  I checked the lights and they were hot, even with the switch off, which led me to believe again that the neutral and hot were shorted.
I poked around and the only thing plugged in was a surge protector for my TV and various entertainment system devices.  I unplugged all of the devices, leaving the surge protector plugged in, and nothing changed.
I unplugged the surge protector to check that receptacle, and everything seemed fine, so I plugged it back in.  The TV standby light came on, and after checking all of my plugs and lights were working again and the short seemed to be gone.
So, should I be worried?  Was the surge protector just doing its job, or is it bad?  Should I be concerned that the breaker did not trip?
Comment: As @User58220 indicated, a hot-to-neutral short circuit would have tripped the breaker or, if not, burned your house down! More likely, the outlet you found is acting as a bridge to the rest of the outlets and the connections to it are loose. As you unplugged and replugged the surge protector, you probably nudged the wires back in contact. You need to check and probably replace this outlet ASAP before a poor connection heats up and causes a fire! Call an electrician if necessary. I'd highly recommend turning off the breaker to that room until this is taken care of!
Comment: Wouldn't a hot to neutral short lead to noise/light/smoke from a breaker *somewhere*?
Comment: So, now that I think about it, if this is the first outlet on the circuit, and the neutral is loose back to the breaker, then the neutral to the rest of the circuit will be pulled to the potential of the hot, correct?
Comment: Yes, if you had anything on the circuit plugged in and turned on, such as a lamp, it would act as a path from hot to the disconnected neutral. This is very likely what you saw.
Comment: @DoxyLover, yes that seems to make sense.  I am working on replacing the outlet now.  I am still concerned that I sensed voltage in the neutrals and the breaker didn't trip.
Answer: Definitely sounds like an open neutral.  By the sounds of it, the bad/loose connection is in the box where the power strip was plugged in.
Comment: It's the only thing that makes sense now from what I saw, especially considering the breaker didn't trip.  I pulled out the receptacle and one wire came loose just from pulling it out (although it was a black wire, not white).  One of the whites was not super secure either, so my guess is that one was the culprit.  There were 3 pairs coming into the box, all attached to the outlet.  I'm not sure if that was code when the house was built (1992), but it was that way when we moved in.  I replaced the receptacle and pig-tailed the 3 pairs to make a single connection to the outlet.
Comment: @MichaelKaras: Oddly no, they were not back stab, at least like I'm used to.  They were screw terminal, but you insert the wire into a slot and then tighten the side screw to clamp the wires.  With 3 wires in the slots I imagine that there was not enough pressure on all of the wires.  I did pigtail them onto the screw terminals of a new outlet.
Comment: My experience with the screw clamp type wire terminations is that even those are best with just one wire. On many outlets except for best commercial grade outlets the clamp brackets will bend and deform leaving a questionable hold on the wire. The wrap around attachment of the wire under a binder head screw is still the very best termination.
Comment: @JeffB - Can you confirm that the original wiring to that receptacle was using using back stab connections? (It sounds like that was the case since you said when you pulled out the receptacle one wire simply came loose). Back stab connections are known to be unreliable and I do hope when you pigtailed to install the new outlet that you attached the pigtails via screws to the receptacle.

Hot to Neutral Short?


How to convert array of decimal strings to array of integer strings without decimal and vice-versa

Question: I want to achieve the following. How to get the desired output as below?
var arr=["1.00","-2.5","5.33333","8.984563"]

    Desired output: arr=["1","-2","5","8"]

    and vice-versa float to int.

Comment: loop, indexOf() to find "." then substr() to read up to it.
Comment: `arr.map(e => (~~e).toString());` but note that for such a vague description on how the transformation should occur and no ideas by yourself this is just the shortest answer i could think of that fulfills your example. `~~` is imho not good style.
Comment: Or `arr.map(x=>parseInt(x,10)+"")`
Comment: Why are these strings when you want to cast floats to integers?
Answer: You could save the sign, apply flooring to the absolute value, put the sign back and convert the result to a string. Map the whole stuff to a new array.
Vive versa does not work, because you loose information while using integer numbers.

var array = ["1.00", "-2.5", "5.33333", "8.984563"],
    result = array.map(v => ((v >= 0 || -1) * Math.floor(Math.abs(v))).toString());

console.log(result);
Answer: var arr=["1.00","-2.5","5.33333","8.984563"]
arr.forEach(function (item, index, array) {
    array[index] = parseInt(item)
})

Answer:

var arr=["1.00","-2.5","5.33333","8.984563"]

var output = arr.map(n => Math[n < 0 ? "ceil":"floor"](n).toString() )

console.log( output )

Rounding to the closest value to zero using Math.ceil() for negative numbers and Math.floor() for positive numbers.


How to Login User in a dotNet Core Web Application with Razor Pages, but keep the user data hidden (Not in a Cookie)

Question: First of all let me apologize if what I am asking here does not make much sense. Also, thank you for your time. This is my first time righting in here so I hope I do it right.
I have been developing in Asp.Net for a year now, and we used the Session to keep the user data persistent throughout that user session (Like Email, Name, Phone, Company, etc..). And if I'm not mistaken that information was hidden, there for not in a cookie and not visible in the browser.
Now we are starting do develop in .Net Core 3.1 and I'm in charged of recreate the login using this new framework, with the condition that the persistent user data is not stored in a cookie or not visible to the browser, it needs to be safe and hidden.
I have looked in the .Net Core Session and the Auth Cookie, but for both of those options we create cookies that hold all that information in, in both this approaches is the information secure or is vulnerable?
After a while I came across this area in the Microsoft docs:
Introduction to Identity on ASP.NET Core
My question is if I go with this approach can I accomplish what I want, have persistent user data not in a cookie or not visible to the browser.
If what I'm try to accomplish is not possible and a cookie needs to be used, is there a way of keeping that data save and secure?
Or is there another approach to keeping data across the session secure and not visible to the browser?
EDIT:
To give a more practical example, in our dashboard we will filter the data depending on the user, more precisely his type, Company, Area and Channel, this are attributes of every user. When a user logs in and is redirected to the Dashboard he will only see the data that as the same attributes as him. In Asp .Net all I needed to do was save that information in the moment of login inside the Session and then retrieve it when I needed them.
In .Net Core, I have been able to it in 2 different ways, the first was to use the "HttpContext.Session.SetString()" and "HttpContext.Session.GetString()" to save and retrieve the data I needed. The second way was to pass the data inside the Claims when I do "HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authenticationProperties);". Both of this approaches allows me to fetch the information I need and use it. But all the data is inside cookies, visible in the browser.
But For what I'm understanding .Net Core does not allow to save data like that on server-side, so is possible to encrypt the auth cookie so the data stays protected.
My code to login the user is as Follow:
After I authenticate the user I run this to login the user and create the auth cookie.
string userGUID = Guid.NewGuid().ToString();

List<Claim> claims = new List<Claim>()
{
    new Claim(ClaimTypes.NameIdentifier, userGUID),
    new Claim(ClaimTypes.Role, "Admin"),
    new Claim("Company", "User Company"),
    new Claim("Area", "User Area"),
    new Claim("Channel", "User Channel")
};

if (claims != null && claims.Count > 0)
{
    var claimsIdentity = new ClaimsIdentity(
        claims, CookieAuthenticationDefaults.AuthenticationScheme);

    AuthenticationProperties authenticationProperties = new AuthenticationProperties
    {
        IsPersistent = false,
        AllowRefresh = false,
        ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30)
    };

    _httpContextAccessor.HttpContext.SignInAsync(
               CookieAuthenticationDefaults.AuthenticationScheme,
               new ClaimsPrincipal(claimsIdentity),
               authenticationProperties);

}

Once again thank you for your time and please tell me if there is something that I can do to clarify this question.
Comment: My guess is your legacy Login may have used some mechanism similar to a cookie. Session (wich are stored server side) are kind of deprecated because of multi-frontend scalability problem. If you need to store sensitive data on browser you can imagine a system to encrypt them server side with a non symetric algorythm as long you don't need this data in client-side. An exemple of data usage scenario could be helpfull to better target your needs.
Comment: I thank you for the reply, so for what I can understand I can no longer store and access data in server side the same way I could in Asp.Net.
I Edited my question to have more information. Can You give me a example on how to encrypt the cookie? or is it automatically encrypted and secure?
I'm sorry for all the questions, it is my first time trying to create a safe login from the ground up.
Comment: Just another question : Is user can use external authentication provider like Facebook, Google and so on ?
Answer: First I've not done yet Authentication in .Net Core but I far I as know and if I was in your case I will try to use OpenId like per MS recommendation you had mentionned.
If your users are not authenticated by an external provider like Google, Facebook, etc... you will have to create your own Oauth2 Authentication server. A thing I did back in 2016 but in .Net Framework 4 not .Net Core. However while it's still possible today, I will not recommend to invest in .Net Framework as .Net (Core) 5 will make it outdated in Nov 2020. But for your information you can refer to this answer here:
How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2 [closed]
If you want to go on creating your own OAuth Provider I suggest you look at this answer here : OAuth Authorization Service in ASP.NET Core
My though with the "cookie" is it could only store the Authentication token. I mean the OAuth server provides a token each time a user authenticate. This token should be valid for a defined period of time (let's say 20 min). Then this token is invalid after.
To keep user connected you will surely have to implement a mechanism  to automatically renew it. Let's say the token is valid for 20 min if the server received a request while the token is still valid but only for the next 10 min then the server ask the OAuth provider to renew it and give it back to the browser in order to update his "cookie".
As far as I remembered we only used Http Header Authorization field (and no cookie) to send the token on each request and handle its lifetime (expiration/renew) in the browser using javascript ajax request and local storage.


Trying to create a material from string - this is no longer supported

Question: The error is:
Trying to create a material from string - this is no longer supported.
UnityEngine.Material:.ctor(String)
Drawer:CreateLineMaterial() (at Assets/Flying Birds/Scripts/Drawer.cs:27)
Drawer:Awake() (at Assets/Flying Birds/Scripts/Drawer.cs:46)

Line 27 is:
var mat = new Material(

And line 46:
lineMaterial = CreateLineMaterial();

using System;
using UnityEngine;
using System.Collections.Generic;

public class Drawer: MonoBehaviour
{
  public Material lineMaterial;

  struct Line
  {
    public Vector3 from;
    public Vector3 to;
    public Color color;

    public Line( Vector3 from, Vector3 to, Color color )
    {
      this.from = from;
      this.to = to;
      this.color = color;
    }
  }

  static List<Line> lines = new List<Line>();

  static Material CreateLineMaterial()
  {
    var mat = new Material(
       @"Shader ""Lines/Colored Blended"" {
       SubShader { Pass {
           Blend SrcAlpha OneMinusSrcAlpha
           ZWrite Off Cull Off Fog { Mode Off }
           BindChannels {
             Bind ""vertex"", vertex Bind ""color"", color }
       }}}"
    );

    mat.hideFlags = HideFlags.HideAndDontSave;
    mat.shader.hideFlags = HideFlags.HideAndDontSave;

    return mat;
  }

  void Awake()
  {
    if( lineMaterial == null )
      lineMaterial = CreateLineMaterial();
  }

  void OnPostRender()
  {
    lineMaterial.SetPass( 0 );

    GL.Begin( GL.LINES );

      foreach( var l in lines )
      {
        GL.Color( l.color );
        GL.Vertex3( l.from.x, l.from.y, l.from.z );
        GL.Vertex3( l.to.x, l.to.y, l.to.z  );
      }

    GL.End();
  }

  void FixedUpdate()
  {
    lines.Clear();
  }

  public static void DrawLine( Vector3 from, Vector3 to, Color color )
  {
    lines.Add( new Line(from, to, color) );
  }

  public static void DrawRay( Vector3 from, Vector3 to, Color color )
  {
    lines.Add( new Line(from, from + to, color) );
  }
}

Answer: The Material string constructor is now obsolete. You can use the Shader or Material constructor.
public Material(Material source);
public Material(Shader shader);

Put the shader code in a shader file the use Shader.Find to find it.
var mat = new Material(Shader.Find("Transparent/Diffuse"));

Answer: I believe there's no way to create a Material from shader strings in newer versions of Unity (which is arguably good thing).
You will need to create a Shader asset and put your code from CreateLineMaterial there. Then you can write something like:
    var mat = new Material(Shader.Find("Lines/Colored Blended"));

instead in the Material constructor.
Answer: This is a step by step solution for those that are not familiar with shaders.
1) Create a Shader File
To create a new Shader, use Assets > Create > Shader from the main menu or the Project View context menu. A shader is a text file similar to a C# script, and is written in a combination of Cg/HLSL and ShaderLab languages
2) Copy/Paste this Shader Code
The filename of the shader does not matter. Go ahead and copy/paste this shader code into your shader. (Delete any old code that existed when the shader file was created)
Shader "Lines/Colored Blended" {
            SubShader { Pass {
                Blend SrcAlpha OneMinusSrcAlpha
                ZWrite Off Cull Off Fog { Mode Off }
                BindChannels {
                  Bind "vertex", vertex Bind "color", color }
            } } }

3) Find the Shader in your C# code
Now you can write your function, how you like (using the Shader.Find() function):
static Material CreateLineMaterial()
{
    mat = new Material(Shader.Find("Lines/Colored Blended"));

    mat.hideFlags = HideFlags.HideAndDontSave;
    mat.shader.hideFlags = HideFlags.HideAndDontSave;

    return mat;
}

That's it! Your code should work now.
Answer: Creating materials from shader source string is no longer supported. Use Shader assets instead. https://docs.unity3d.com/Manual/class-Shader.html
Source: Unity Docs https://docs.unity3d.com/ScriptReference/Material-ctor.html


How to create an NSDictionary that contains an array for every key?

Question:
I wanted to know how (if it is possible) to create an NSDictionary that holds an NSArray for every key.
Something like that:
@"FirstKey"   - [0], [1], [2], [3]
@"SecondKey"  - [0], [1], [2], [3]
@"ThirdKey"   - [0], [1], [2], [3]
@"FourthKey"  - [0], [1], [2], [3]
Hope you got the idea, thanks ahead!
Answer: You can add NSArray instances (or any other collection) as values of an NSDictionary:
NSDictionary *d = [[NSMutableDictionary alloc] init];
[d setValue:[NSArray arrayWithObjects:
               [NSNumber numberWithInteger:0],
               [NSNumber numberWithInteger:1],
               ...,
               nil]
     forKey:@"FirstKey"];
[d setValue:[NSArray arrayWithObjects:
               [NSNumber numberWithInteger:0],
               [NSNumber numberWithInteger:1],
               ...,
               nil]
     forKey:@"SecondKey"];
//etc.

Alternatively, if you don't have too many keys/values:
NSArray *values1 = [NSArray arrayWithObjects:
                    [NSNumber numberWithInteger:0],
                    [NSNumber numberWithInteger:1],
                    ...,
                    nil];
NSArray *values2 = [NSArray arrayWithObjects:
                    [NSNumber numberWithInteger:0],
                    [NSNumber numberWithInteger:1],
                    ...,
                    nil];
NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:
                     values1, @"FirstKey",
                     values2, @"SecondKey",
                     ...,
                     nil];

Answer: That's totally possibly.  Simplest way is to create your NSArray and then just add that as the object for the key to your NSDictionary
NSArray *myArray = [NSArray arrayWithObjects:@"One",@"Two", nil];
[myDictionary setObject:myArray forKey:@"FirstKey"];

Comment: Is there any way to create that in the instance method?
Comment: Yes, just use `[NSDictionary initWithObjectsAndKeys:[NSArray arrayWithObjects:@"One",@"Two",nil], @"FirstKey", nil];`
Answer: Yes, you can store any object in a dictionary.  For numeric values you will need to store them as NSValue or NSNumber objects.
Comment: I want to create an NSDictionary where every key is a string and holds an NSArray
Comment: Yes, an NSArray is just another kind of object.


Pushing predicate in a view

Question: The scenerio
explain plan for
  select l.etl_id , v.*
  from   v_load_base v, etl_log l
  where  l.is_active = 1
  and    v.ddate between trunc(l.load_from_date) and l.load_to_date
  and    v.starttime_full between l.load_from_date and l.load_to_date;

Produces this execution plan
--------------------------------------------------------------------------------------------------------
| Id  | Operation                      | Name          | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
--------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT               |               |     3 |   444 |       | 31624   (4)| 00:06:20 |
|   1 |  SORT ORDER BY                 |               |     3 |   444 |       | 31624   (4)| 00:06:20 |
|*  2 |   HASH JOIN                    |               |     3 |   444 |       | 31623   (4)| 00:06:20 |
|   3 |    NESTED LOOPS OUTER          |               |     3 |   378 |       | 31413   (4)| 00:06:17 |
|*  4 |     HASH JOIN                  |               |     3 |   348 |       | 31410   (4)| 00:06:17 |
|*  5 |      HASH JOIN                 |               |  1252 |   118K|  2144K| 23428   (4)| 00:04:42 |
|*  6 |       HASH JOIN                |               | 27786 |  1818K|       |   764   (7)| 00:00:10 |
|   7 |        NESTED LOOPS            |               |     8 |   264 |       |     7   (0)| 00:00:01 |
|*  8 |         TABLE ACCESS FULL      | ETL_LOG       |     1 |    21 |       |     3   (0)| 00:00:01 |
|*  9 |         TABLE ACCESS FULL      | MD            |     8 |    96 |       |     4   (0)| 00:00:01 |
|  10 |        TABLE ACCESS FULL       | DS            |   479K|    15M|       |   748   (6)| 00:00:09 |
|  11 |       TABLE ACCESS FULL        | MDS           |  7280K|   208M|       |  7823   (5)| 00:01:34 |
|  12 |      TABLE ACCESS FULL         | TASKS         |  7760K|   140M|       |  7844   (5)| 00:01:35 |
|  13 |     TABLE ACCESS BY INDEX ROWID| ETL_GIS       |     1 |    10 |       |     1   (0)| 00:00:01 |
|* 14 |      INDEX UNIQUE SCAN         | ETL_GIS_UK    |     1 |       |       |     0   (0)| 00:00:01 |
|  15 |    TABLE ACCESS FULL           | DETAILS_TABLE |   292K|  6280K|       |   204   (8)| 00:00:03 |
--------------------------------------------------------------------------------------------------------

The join predicate with the table etl_log was pushed down to the view v_load_base (line 8).
I created a view called v_load_base_active based on the same exact query as the one above.
Querying the new view produces the following plan
explain plan for select * from v_load_base_active;

----------------------------------------------------------------------------------------------------
| Id  | Operation                 | Name           | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
----------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT          |                |     3 |   861 |       | 63583   (8)| 00:12:43 |
|   1 |  NESTED LOOPS             |                |     3 |   861 |       | 63583   (8)| 00:12:43 |
|*  2 |   TABLE ACCESS FULL       | ETL_LOG        |     1 |    21 |       |     3   (0)| 00:00:01 |
|*  3 |   VIEW                    | V_LOAD_BASE    |     3 |   798 |       | 63580   (8)| 00:12:43 |
|   4 |    SORT ORDER BY          |                |   422K|    51M|   110M| 63580   (8)| 00:12:43 |
|*  5 |     HASH JOIN RIGHT OUTER |                |   422K|    51M|       | 51513   (9)| 00:10:19 |
|   6 |      TABLE ACCESS FULL    | ETL_GIS        |  5958 | 59580 |       |    17   (0)| 00:00:01 |
|*  7 |      HASH JOIN            |                |   422K|    47M|  9712K| 51488   (9)| 00:10:18 |
|   8 |       TABLE ACCESS FULL   | LINES_DETAILS  |   292K|  6280K|       |   204   (8)| 00:00:03 |
|*  9 |       HASH JOIN           |                |   422K|    38M|    35M| 48647  (10)| 00:09:44 |
|* 10 |        HASH JOIN          |                |   422K|    30M|       | 27365  (14)| 00:05:29 |
|  11 |         TABLE ACCESS FULL | MD             |  3103 | 37236 |       |     4   (0)| 00:00:01 |
|* 12 |         HASH JOIN         |                |  7301K|   445M|    21M| 24366   (3)| 00:04:53 |
|  13 |          TABLE ACCESS FULL| DS             |   479K|    15M|       |   748   (6)| 00:00:09 |
|  14 |          TABLE ACCESS FULL| MSD            |  7280K|   208M|       |  7823   (5)| 00:01:34 |
|  15 |        TABLE ACCESS FULL  | TASKS          |  7760K|   140M|       |  7844   (5)| 00:01:35 |
----------------------------------------------------------------------------------------------------

The predicate is not pushed. This leads to a major decrease in performance.
I've tried setting a hint explicitly in the view /*+ PUSH_PRED(v) */ but the plan does not change.
How can i make the optimizer push the predicate also within a view ... ?

v_load_base does not contain analytic functions. The first query proves that the predicate can be pushed.

EDIT
notice that oracle does not state in the execution plan that a predicate was pushed with VIEW PUSHED PREDICATE. but, looking at the plan it's clear that oracle transformed the view's sql to include the etl_log predicate.
Answer: I doubt that it was pushing predicate in the first case, because it would be in the plan. More likely it was merging which is controlled by MERGE/NO_MERGE hints. See example below.
With NO_MERGE:
SQL> explain plan for
  2  select /*+NO_MERGE(so)*/ *
  3    from siebel.s_org_ext soe,
  4         (select sx.attrib_08, s.*
  5            from siebel.s_opty s
  6           inner join siebel.s_opty_x sx on s.row_id = sx.row_id) so
  7   where soe.row_id = so.pr_dept_ou_id
  8     and soe.row_id like '1-8ZT%'
  9     and so.db_last_upd between soe.db_last_upd and soe.db_last_upd - 365;

Explained

SQL> select * from table(dbms_xplan.display);
Plan hash value: 1802470607
---------------------------------------------------------------------------------------------
| Id  | Operation                    | Name         | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT             |              |     1 | 13258 |    55   (2)| 00:00:01 |
|*  1 |  HASH JOIN                   |              |     1 | 13258 |    55   (2)| 00:00:01 |
|   2 |   TABLE ACCESS BY INDEX ROWID| S_ORG_EXT    |     1 |  1047 |     3   (0)| 00:00:01 |
|*  3 |    INDEX RANGE SCAN          | S_ORG_EXT_P1 |     1 |       |     2   (0)| 00:00:01 |
|   4 |   VIEW                       |              |  1084 |    12M|    52   (2)| 00:00:01 |
|*  5 |    HASH JOIN                 |              |  1084 |   528K|    52   (2)| 00:00:01 |
|   6 |     TABLE ACCESS FULL        | S_OPTY_X     |  1573 | 15730 |    17   (0)| 00:00:01 |
|*  7 |     TABLE ACCESS FULL        | S_OPTY       |  1084 |   517K|    34   (0)| 00:00:01 |
---------------------------------------------------------------------------------------------

With MERGE:
SQL> explain plan for
  2  select /*+MERGE(so)*/*
  3    from siebel.s_org_ext soe,
  4         (select sx.attrib_08, s.*
  5            from siebel.s_opty s
  6           inner join siebel.s_opty_x sx on s.row_id = sx.row_id) so
  7   where soe.row_id = so.pr_dept_ou_id
  8     and soe.row_id like '1-8ZT%'
  9     and so.db_last_upd between soe.db_last_upd and soe.db_last_upd - 365;

Explained

SQL> select * from table(dbms_xplan.display);
Plan hash value: 4111959163
----------------------------------------------------------------------------------------------
| Id  | Operation                     | Name         | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT              |              |     1 |  1546 |     6   (0)| 00:00:01 |
|   1 |  NESTED LOOPS                 |              |     1 |  1546 |     6   (0)| 00:00:01 |
|   2 |   NESTED LOOPS                |              |     1 |  1536 |     5   (0)| 00:00:01 |
|   3 |    TABLE ACCESS BY INDEX ROWID| S_ORG_EXT    |     1 |  1047 |     3   (0)| 00:00:01 |
|*  4 |     INDEX RANGE SCAN          | S_ORG_EXT_P1 |     1 |       |     2   (0)| 00:00:01 |
|*  5 |    TABLE ACCESS BY INDEX ROWID| S_OPTY       |     1 |   489 |     2   (0)| 00:00:01 |
|*  6 |     INDEX RANGE SCAN          | S_OPTY_M64_X |     1 |       |     1   (0)| 00:00:01 |
|   7 |   TABLE ACCESS BY INDEX ROWID | S_OPTY_X     |     1 |    10 |     1   (0)| 00:00:01 |
|*  8 |    INDEX UNIQUE SCAN          | S_OPTY_X_P1  |     1 |       |     0   (0)| 00:00:01 |
----------------------------------------------------------------------------------------------

So try to force optimizer use merging with you view and see if plan changes.

Pushing predicate in a view