Different screen resolutions for each work-space?

Question: I'm using i3-wm on my ubuntu laptop. My screen size is 3200x1800. Which is great for something but horrible for other things. (Netflix vs gvim).
I'd like to change the resolution of one of my work-spaces, or multiple ones. But I have no idea if that is even possible... can I use compton to do this or maybe another program?
Comment: That would be "kind of" possible, meaning the change would be automatically. However, in Unity, all workspaces (viewports) together are one big desktop, with one resolution setting. What can be done is to let a background script understand which is the current workspace and alter the reolution accordingly. That would possibly mess up a window arrangement on the different viewports. Not sure if that is helpful to you.
Comment: The mechanism would be like this one http://askubuntu.com/a/560734/72216, only instead of changing the wallpaper, the resolution has to be changed by `xrandr`. I can look into it, but could you tell me your screen name (look for "connected" from  `xrandr`), and the resolutions to be set on which viewport, and the number of viewports? (not sure I need it)
Comment: What you can do is *change* the resolution, depending on the current viewport or workspace. The change would however be the current resolution, since you have only one screen. would that help you?
Comment: Ideally I would like to have, say, workspace 1 on the 3200x1800, but workspace 2 on 1920x1080. And be able to switch between the two workspace's without changing the resolution through any commands or files. If that's what you mean.
Comment: Actually, I think that would be exactly what I want. Since i3 is tiled, everything should retain the same arrangement etc. What would have to be done in this script?
Comment: Awesome, thank you. Yeah, my screens name is "eDP1" and the workspaces are 1-10, with workspace 8,9,10 being set to 1920x1080 and 1-7 at 3200x1800 is what I'd like.
Answer: 1. Assuming you are on Unity
The script below should change your resolution, depending on the current viewport in Unity. I tested it on several computers for a while, and it ran without an error.
I'd suggest however to also test it for a while and see if it runs without a single break; repeated wmctrl commands can sometimes exit "non-zero" incidentally. If so, we need to build in a try / except.
Notes

I tested it on a single-monitor setup. multiple monitors would probably need another way of parsing the output of xrandr.
In the head of the script, you need to set the desired resolution for each of your viewports, I set it like mentioned in your comment, but you can change it anytime. Use the format:
resolutions = [[<horizontal>, <vertical], [<horizontal>, <vertical], ......]

like it shows in the script.
No need to say that you should use supported resolutions, as in the output of xrandr for your monitor.

How to use

The script needs wmctrl:
sudo apt-get install wmctrl

copy the script below into an empty file, save it as screen_res.py
Test run it for a while in a terminal window by the command:
python3 screen_res.py

If all works fine, add it to your startup applications: Dash > Startup Applications > Add...

The script
#!/usr/bin/env python3
import subprocess
import time

# list of resolution per viewport, for each viewport a separate [hor, vert]
# I pre- entered your viewports. quite some! listing takes more space than the script :)
resolutions = [
    [3200, 1800],
    [3200, 1800],
    [3200, 1800],
    [3200, 1800],
    [3200, 1800],
    [3200, 1800],
    [3200, 1800],
    [1920, 1080],
    [1920, 1080],
    [1920, 1080],
    ]

def get_xr():
    return subprocess.check_output(["xrandr"]).decode("utf-8").split()

check = get_xr()
plus = 2 if check[check.index("connected")+1] == "primary" else 1

while True:
    # resolution:
    xr = get_xr()
    res = [int(n) for n in xr[xr.index("connected")+plus].split("+")[0].split("x")]
    # get current viewport
    vp_data = subprocess.check_output(["wmctrl", "-d"]).decode("utf-8").split()
    dt = [int(n) for n in vp_data[3].split("x")]
    cols = int(dt[0]/res[0])
    curr_vpdata = [int(n) for n in vp_data[5].split(",")]
    curr_col = int(curr_vpdata[0]/res[0])+1; curr_row = int(curr_vpdata[1]/res[1])
    curr_vp = curr_col+curr_row*cols
    # check and change resolution if needed
    if res != resolutions[curr_vp-1]:
        new_res = ("x").join([str(n) for n in resolutions[curr_vp-1]])
        subprocess.call(["xrandr", "-s", new_res])
    time.sleep(1)

Explanation

In a loop, the script first checks the screen's current resolution from the command:
xrandr

Subsequently, the script checks the total desktop size (all viewports) from the command:
wmctrl -d

Then, from the resolution i.c.w. the total desktop size, it calculates the number of columns, which is equal to the total desktop size, divided by the horizontal resolution.
Also in the output ofwmctrl -d is the position of the current viewport on the spanning desktop: e.g.: VP: 1680,0.
With this information we can conclude on which column & row we are, and check if the currently set resolution matches the resolution as we defined it in the list in the head section of the script.
If not, the script gives the command to change the resolution with the command:
xrandr -s <xres>x<yres>

2. XFCE version

set up like the version above (also needs wmctrl)

#!/usr/bin/env python3
import subprocess
import time

# list of resolution per viewport, for each viewport a separate [hor, vert]
# below just an example! set resolutions for your own screen
resolutions = [
    [1280, 1024],
    [1280, 960],
    [1280, 1024],
    [1280, 1024],
    ]

def get_xr():
    return subprocess.check_output(["xrandr"]).decode("utf-8").split()

check = get_xr()
plus = 2 if check[check.index("connected")+1] == "primary" else 1

while True:
    # resolution:
    xr = get_xr()
    res = [int(n) for n in xr[xr.index("connected")+plus].split("+")[0].split("x")]
    # get current workspace
    vp_data = subprocess.check_output(["wmctrl", "-d"]).decode("utf-8").splitlines()
    curr_ws = int([l.split()[0] for l in vp_data if "*" in l][0])
    # check and change resolution if needed
    if res != resolutions[curr_ws]:
        new_res = ("x").join([str(n) for n in resolutions[curr_ws]])
        subprocess.call(["xrandr", "-s", new_res])
    time.sleep(1)

Comment: I see you run your code in while-true loop. Isn't there some event you can listen to or some hook that can be triggered when desktop is changed?
Comment: @umpirsky have been looking for it, but never found one. At the same time both `xrandr` and `wmctrl -d` should be relatively light-weight when run once per second. Even on my 12 year old museum piece, I don't notice any effect (XFCE version). Maybe a small break between the two, of e.g. 0.5 sec., would make it even lighter.
Answer: I implemented @Jacob Vlijm's python script for XFCE. It worked well except for an old Windows program running through wine. Every time the script cycled, it would freeze the mouse cursor for less than a second. Checking 1x/sec meant a lot of stuttering. I ported it to a bash script, modifying it to only call wmctrl once per check and only call xrandr if the resolution needs to be changed. Note that it does require wmctrl to be installed.
#!/usr/bin/env bash
#Tested in XFCE 4.12.3 on Ubuntu 18.04
#Requires wmctrl. Install with:
#$ sudo apt-get install wmctrl

#Note: This checks current workspace res 1x/sec. To change rate, change "sleep" parameter below

#Enter appropriate resolution for each workspace, in order, in the same format as below.
RESOLUTIONS=('1920x1080' '1368x768')

check_and_change_res() {
  #echo "Parsing wmctrl -d"
  while read line; do
    #example line from wmctrl:
    #$ wmctrl -d
    #0  - DG: 1368x768  VP: N/A  WA: 0,25 1368x743  1
    #1  * DG: 1368x768  VP: 0,0  WA: 0,25 1368x743  2
    #If your line does not have a "DG:" (desktop geometry) preceding the current resolution, you
    #  will need to change the regex below.
    if [[ ${line} =~ ([[:digit:]]+)[[:space:]]+\*[[:space:]]+DG:[[:space:]]+([[:alnum:]]+) ]]; then
      current_ws="${BASH_REMATCH[1]}"
      current_res="${BASH_REMATCH[2]}"
      target_res="${RESOLUTIONS[current_ws]}"
      #echo "Current workspace: ${current_ws}; Current resolution: ${current_res}; Target resolution: ${target_res}"
      if [[ ! ${current_res} =~ ${target_res} ]]; then
        #echo "Switching resolution to ${target_res}."
        xrandr -s ${target_res}
      fi
    fi
  done
}

while true
do
  check_and_change_res < <(wmctrl -d)
  #This waits for 1 second between checks. To change to a 5-second delay (e.g. performance), use:
  #sleep 5
  sleep 1
done


How can i create responsive text with javafx?

Question: I created a label with a number shown in it and I now want to make this number responsive to the GUI.
How can I do that? Here is my number with its current font-size.
<code>Label label = new Label();
label.setText("12");
label.setFont(Font.font("Comic Sans MS", 35));
</code>
Thanks for your help :)
Comment: What do you mean with *"to make this number responsive to the GUI"*? This could mean making the label vanish as soon as a button is clicked of changing any layout parameter of the label on any event of the GUI...
Comment: if i start the application in a different window-size the size of the number should match the window. At the moment the size of the number stays 35 all the time and is therfore too big for a smaller window.
Answer: If you want change values or params of this label you must use one of avelible javaFx controls: https://docs.oracle.com/javafx/2/ui_controls/jfxpub-ui_controls.htm
For each control you have onActionListners functions where you can make changes.
Hope this help.
Answer: Anchorpane,HBOX etc. are responsive in nature.Put the label inside a HBOX.
Hope this help.


why thymeleaf get URL residual "/user/edit"?

Question: enter image description here

                Photo:

                    <input type="file" id="fileImage" name="image" accept="image/png, image/jpeg, image/jpg">

@Transient
public String getPhotosImagePath() {
    if(id == null || photos == null) return "/images/defaultUser.png";
    return "user-photos/" + this.id + "/" + this.photos;
}

this is my thymleaf code, somewhere else it returned correct results for me but here the path for the photo I received is left with some "/ user / edit" parts. how to fix that
http://localhost:8080/ShopmeAdmin/users/edit/user-photos/13/cfe3d8d31bc1e89fb1d01.jpg
i just want: http://localhost:8080/ShopmeAdmin/user-photos/13/cfe3d8d31bc1e89fb1d01.jpg
Answer: In your return statement, the string "user-photos/" does not have a leading slash (/) and therefore it will be interpreted as a relative path (relative to the current page location).
Assuming ShopmeAdmin is the root context of your application, then you need to add a leading slash to user-photos/:
return "/user-photos/" + this.id + "/" + this.photos;

Thymeleaf has a number of different ways to handle relative and absolute URLs in its link URL syntax, summarized here:

Absolute URLs: http://www.thymeleaf.org
Relative URLs, which can be:

Page-relative: user/login.html
Context-relative: /itemdetails?id=3 (context name in server will be added automatically)
Server-relative: ~/billing/processInvoice (allows calling URLs in another context (= application) in the same server.
Protocol-relative URLs: //code.jquery.com/jquery-2.0.3.min.js

Your current URL (without the leading slash) is relative to the current page (which I assume is the user edit page).
The new URL (with the leading slash) will be context-relative.

A couple of extra notes:
Protocol-relative URLs are out-of-date these days and should probably no longer be used.
I would recommend always using braces, for safety and clarity:
if (id == null || photos == null) {
    return "/images/defaultUser.png";
}


Why isn't my ExtJS Store Association Working

Question: I'm having issues. I want to use the nice ExtJS associations, but they're not working properly.
Issues:

no association showing in the model
no data showing up after load

What are the quirks to watch out for?
Answer: I recently went through a very painful learning curve with the ExtJS associations, and came across some useful articles, as well as my own gotchas. Here is the summary for those who run into the same pains.
Rules for HasMany Associations in ExtJS

Always put your Proxies in your Models, not your Stores, unless you
have a very good reason not to [1]
Always require your child models if
using them in hasMany relationships. [2]
Always use foreignKey if you want to load the children at will
Always use associationKey if you return the children in the same response as the parent
You can use both foreignKey and associationKey if you like
Always name your hasMany relationships
Always use fully qualified model names in your hasMany relationship
Consider giving the reader root a meaningful name (other than "data")
The child model does not need a belongsTo relationship for the hasMany to work

[1] The store will inherit its model's proxy, and you can always override it
[2] To make it easy, and avoid potential circular references, you can require them in app.js
http://extjs-tutorials.blogspot.com/2012/05/extjs-hasmany-relationships-rules.html
Rules for HasOne and BelongsTo Associations in ExtJS

Put the proxy in the model, unless you have a very good reason not to
Always use fully qualified model name
Always set the getterName
Always set the setterName
Always set the associationKey, if the foreign object is returned in the same response as this object
Always set the foreignKey, if you want to load the foreign object at will
Consider changing the instanceName to something shorter
The getter  behaves differently depending on whether the foreign object is loaded
or not. If it's loaded, the foreign object is returned. Otherwise,
you need to pass in a callback to get it.
You should set the name property if you plan to override this association.
You do not need a  belongsTo relationship for a hasMany to work
Set the primaryKey property if the id field of the parent model is not "id"
Sometimes you need to use uses or requires for the belongsTo association. Watch
out for circular references though.
Calling setter() function does
not seem to set the instance. Set object.belongsToInstance = obj  if
calling the setter().

http://extjs-tutorials.blogspot.com/2012/05/extjs-belongsto-association-rules.html
Misc

If you're applying your data to a grid, make sure you call reconfigure() on the grid using the new store
Your "foreignKey" property will be applied as a local filter to the ExtJS store; if you see the data loading over the network, but
not showing in your grid, make sure your model has the foreignKey
value defined as a field, or the local filter will exclude the data
quiety. To test if this is the case, hook into the store's "load"
event and call store.clearFilters(), and see if your data shows up
Comment: +1 for `requires: [...]` as I am stunned to find out that was my problem.  Really irked at ExtJs over that!


Why does the following formula increment a negabinary number (number in base -2)?

Question: In a file I have written the following formula that increments a negabinary number (a number in base -2):
$$2x \oplus ((2x \oplus x) + 1) $$
In this formula $x$ is a negabinary number interpreted as a binary number and we will perform binary operations on it. $2x$ is a simple binary left shift (110 becomes 1100). $\oplus$ is the XOR operator. The $+1$ is also done using binary addition. The final result is then interpreted as a negabinary number.
Negabinary is of the form $a=\sum_{i=0}^{n}{d_i(-2)^{i}}$ where $d_i\in\left\{0,1\right\}$
For example: $3=4-2+1=111_{-2}$
So, using the formula: when we for example increment $5$ ($101_{-2}$ in negabinary) we get (using binary representation)
$$1010 \oplus ((1010 \oplus 101) + 1)=1010 \oplus (1111 + 1)=1010 \oplus 10000=11010$$
which is 6 in negabinary ($16-8-2$).
The rules of the $\oplus$ operator are:
$0 \oplus 0 = 0$
$0 \oplus 1 = 1$
$1 \oplus 0 = 1$
$1 \oplus 1 = 0$
For multi-bit numbers, the $\oplus$ operation is done by applying these rules on the n-th bit of both operands. For example:
$1101 \oplus 0110 =1011$
I fail to find the original paper where I found this formula. Can anyone explain why this works?
Comment: Is $x$ an integer? Rational? Real? Does it matter? $1=(-2)^0$ so its presence in the formula suggests that perhaps $x$ is supposed to be an integer.
Comment: What do $\oplus$ and $+$ represent?
Comment: @Henry   Good point. For that matter, what does $2x$ mean? Is a right shift in negabinary equivalent to multiplication by $2$? It would seem not.
Comment: @JohnWaylandBales Indeed multiplication by two seems a little complicated: three is $111_{-2}^{ }$, negative six is $1110_{-2}^{ }$, twelve is $11100_{-2}^{ }$, but six is $11010_{-2}^{ }$
Comment: @Henry  Right shift would have to be equivalent to multiplication by $(-2)$ so I would assume that $2x$ is the double of $x$. Most of the research seems to be paywalled and I lost my library privileges when I retired (as full professor with 39 years at my institution. Go figure.)
Comment: So $\oplus$ is ordinary binary addition. So is there a distinction between $1111+1$ and $1111\oplus 1$.
Comment: $\oplus$ is the XOR operator. The rules are: $0 \oplus 0=0$, $0 \oplus 1=1$, $1 \oplus 0=1$ and $1 \oplus 1=0$. The n-th bit gets XOR'ed by the n-th bit of the other operand.
Comment: Minor point.  $3$ is $111$ not $110$ in negabinary.  The value of the sum $4-2+1$ was typed wrong.
Comment: I Improved the question.
Comment: $1111 \oplus 1=1110$ while $1111+1=10000$ (binary addition).
Comment: Is there anything unclear?
Comment: I'm putting a bounty on this when I've got enough points to do that.
Answer: When you add $1$ to a binary number $n$, you just change $k(n)$ binary digits at the end of the number where $k(n)$ is the number of consecutives $1$s at the end of $n$, plus $1$.
And so $n + 1 = n \oplus K(n)$ where $K(n) = (2^{k(n)} - 1)$.
Now your strange operation is $x \mapsto 2x \oplus ((2x \oplus x) + 1) = 2x \oplus (2x \oplus x \oplus K(2x \oplus x)) = x \oplus K(2x \oplus x)$, so from $x$ you just switch the last $k(2x \oplus x)$ binary digits of $x$.
$k(2x \oplus x)-1$ is the number of $1$s at the right of $2x \oplus x$, so those are the number of consecutive digit changes at the right of $x$ :
For example, $101$ has $4$ consecutive digit changes (don't forget about the invisible zeroes on both sides), so you switch $5$ digits to get $11010$.
$11010$ has $0$ consecutive digit changes (because its rightmost digit is a $0$), so you switch $1$ digit to get its successor $11011$. Then, there is $1$ change, so you get $11000$ and so on.
Define $f$ and $g$ recursively on strings of binary digits by :
$f(x0) = x1  ,  f(x1) = g(x)0  \\
g(x0) = f(x)1,
g(x1) = x0$
You should be able to recognize that your operation is simply applying $f$ to the string of binary digits. We need one auxiliary function because we need the memory of what the previous digit was to compare it to the current digit and see if we continue to switch or not.
When you interpret the strings as numbers in base $-2$, those functions become defined by :
$f(-2x+0) = -2x+1  ,  f(-2x+1) = -2g(x)+0  \\
g(-2x+0) = -2f(x)+1,  g(-2x+1) = -2x+0$
Finally, a recursion (on the number of $-2$ary digits of $x$) shows that $f(x) = x+1$ and $g(x)=x-1$ for all $x \in \Bbb Z$
Comment: +1, finally had a chance to read through this. Hidden in the middle there is a good description of how incrementing works in negabinary: If you increment a $1$ you carry a decrement to the next place, and if you decrement a $0$ you carry an increment to the next place.


Monitor settings always showup on secondary monitor. How to fix?

Question: I am using a secondary monitor connected to my laptop's VGA output.
However, many app popup dialogs, including Ubuntu's display settings show up on that secondary monitor. This is very annoying because I use it for display and I cannot easily see that monitor when working.
I have Unity menus on the laptop, which is supposed to be my primary. How can I enforce all new windows and monitor settings also show up on primary monitor?
I edited monitors.xml and added primary = yes to all displays which looked like laptop screens (for some reason I have several configurations there). Logged out and back in - same problem. See monitors.xml at http://pastebin.com/zJgstAbf
Comment: I'm not sure of a fix for this problem, but changing the RandR config in `monitors.xml` is unlikely to help.  In my experience, Compiz (the window manager Unity 3D is based on) doesn't do as good a job at placing new windows in multi-head environments as Metacity did.  Since Unity-2D is based on Metacity though, you could try picking it at login as a workaround.
Comment: I see, I did not realize I was using 3D since my graphics card is very basic on this laptop. Looks like I have it running in software mode. Will try to switch to 2D and see if it helps, thanks!
Answer: Looks like switching to Unity 2D helped - now display settings show up on primary monitor.
Wow, this also made my desktop fast again, I did not realize how much slower Unity 3D was until this switch back! Thank you, James!


Tool or command to move multiple files from multiple folders into one place (without overwriting)

Question: I am currently working on recovering some logfiles from random backups that I made.
I have 48 files in 70+ folders.
How can I move these 48 files into one folder, without overwriting files with the same name? Most of these files have the same name, but different size, I checked with fdupes.
Comment: What do you want to do with files that have the same name ?
Comment: I want to keep them, renamed. (I will sort the files by the date it was created, so the name doesn't matter that much)
Answer: Type this command in your terminal (Ctrl+Alt+T to open it) :
find $LOG_DIR -type f | xargs -I {} sh -c 'base=$(basename "$1"); name=${base%.*}; ext=${base##*.}; mv "$1" "$OUTPUT_DIR/$name`date +%N`.$ext"' -- {}

Basically, this will find all your files in $LOG_DIR (that you have to replace with the emplacement of the parent of your 70 folders), extract the name without path (basename), separate the name and the extension and then move them to $OUTPUT_PATH (replace by where you want them to go) and append the number of nanoseconds at this time (data +%N) to the name, so no overwrite.
PS: I've got a little help from there : StackOverflow
Comment: Hi, thanks for the answer!
I have tried the command, though I might have misunderstood the $LOG_DIR thing and the $OUTPUT_PATH.
I have tried this way: ""find $USER Terminalling/a1command/extract_these_files/ ...."" and also: ""find Terminalling/a1command/extract_these_files/..."". Either way i got: ""mv: cannot stat 'thisisalogfile.log': No such file or directory"" or ""mv: target 'Terminalling/a1command/excerpt/757786046thisisalogfile.log' is not a directory"". Here is what i have done: http://pastebin.com/mZGvUp8t
Comment: My bad, this line only work if you're in the same folder than the files you want to move. I'll edit my answer. And what's Terminalling ? A folder ?
Comment: Yes, its a folder. I have tried the command from the parent directory, but same result. (and from within the folder where the file is, it only renamed it) I'm guessing the command needs recursive search in all existing subdirectories, and moving the found files to another folder.
Comment: Try this new line. I tested it with logs in a test folder, launching it from my home.
Comment: mv: cannot create regular file '/thisisalogfile412781517.log': Permission denied.  ---tried the command as it is, from the parent folder
Comment: Your trying to create(or move) a file but you don't have the rights to write in the output folder. And if this is your whole trace, you tried to write in `/`, that's not good. Check your permissions or try with `sudo`.
Comment: Well, I was in a subdirectory inside /home, so its weird that it needs rights to create/move a file. In the meanwhile I have been searching, and found another command, though this one merges files with the same name... """find $HOME/music -name '*.*' -exec cp {} $HOME/new_music/ \;""" do you know of a way of how not to overwrite moved/copied files using that command?
Comment: Those two commands are practically the same. Using `-exec` or `xargs` will produce identical results. Can you pastebin the command and the result please?
Comment: http://pastebin.com/mjuqDGWM
 after that the files got copied in "excerpt" correctly (though some other files were overwritten)
Answer: First use find as indicated above to locate the files you want to move:
find /dir/with/scattered/logs -type f

This will just print the list of files. If you're happy with it, simply use cp with the backup option, this will "make a backup of each existing destination file". Since you said names don't matter that much that should be OK. Backed-up files will have a "~" attached to the name. See man cp for some better control over this functionality.
find /dir/with/scattered/logs -type f -exec cp -b {} /destination/directory \;

This will copy files one by one, which is less efficient than using xargs, but for the amount of files you mention it shouldn't be an issue.


Take-away game problem - find the winning strategy

Question: There are 200 coins in a pile. During a players turn they must take at least one coin and
cannot take more than half of the coins. The person who takes the last coin wins. Devise a
strategy so you always win.
What strategy/method should I use to solve this problem and related problems. Would proof by induction be sufficient or is there some kind of formula. I've played around with this question for a while but haven't had much luck. Any suggestions/pointers would be helpful.
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: Under this rule set, if there is a single coin you have to take it (rule 1) but are banned from taking it because $1\gt \frac 12 \times 1$ (rule 2).
Answer: Commonly, with a game like this one (two-player, symmetric, zero-sum games of perfect information and no possibility of a tie), you can start at the end of the game and work your way backwards, marking each board position as either a winning position or a losing position, defined recursively by the two rules:

A board position is a winning position if you either immediately win or you can move so that the board position on your opponent's turn is a losing position.
A board position is a losing position if you either immediately lose or every option you have to move will put the board in a winning position on your opponent's turn.

For instance:

If on my turn there is one coin remaining, then I win.  Therefore one coin is a winning position.
If there are two coins remaining, then I must take one coin, leaving one left, which is a winning position.  Therefore two coins is a losing position.
With three coins, I can remove one to put the board in a losing position, so three coins is a winning position.

After you do this a few more times, you might notice that the losing positions become pretty rare, and we can further investigate what pattern they follow.  In this case, we find that the losing positions are all the positions with $3(2^n)-1$ coins for $n \geq 0$ an integer.
Once you have that, the winning strategy is fairly apparent.  Whatever position the board is in on your turn, you must take away the right number of coins to leave $3(2^n)-1$ coins on your opponent's turn.  Proving that this is a winning strategy amounts to an inductive proof that having $3(2^n)-1$ coins at the start of your turn is a losing position as defined by the two rules I gave above, which effectively is just noting $$\frac{1}{2}\Big(3(2^n)-1-1\Big) \leq 3(2^{n-1})-1 < \frac{1}{2}\Big(3(2^n)-1\Big).$$
In a game starting with $200$ coins, if we go first, we should take $9$ coins, leaving $3(2^6)-1 = 191$ coins.  Following this strategy each turn will result in our win.
Comment: Note that I have assumed you may take one coin if only one coin is remaining on your turn, even though as Mark Bennet pointed out in a comment, the rules do not actually allow this.  Otherwise all games end in a stalemate as nobody can take the final coin.


Rcursive function with and without return in the recursive step

Question: Can someone explain me the difference between these two codes?
def pal(s):
    if s == "":
        return True
    if s[0] != s[-1]:
        return False
    return pal(s[1:-1])

a = "anna"

print(pal(a))

and
def pal(s):
    if s == "":
        return True
    if s[0] != s[-1]:
        return False
    pal(s[1:-1])

a = "anna"

print(pal(a))

Why the firts one return the right value, that is True, and the second return me None?
Comment: If you have more than 1 iteration, you have a recursive process. In the 2nd code, you just ask to compute the same function , but you don't ask for a return in the end. The thing returned will be the thing inside your "return" block of the 1st iteration, so if you don't call `return` before the `pal(s[1:-1])` the function will just compute the thing but not return anything
Comment: Ok but when I arrive at the last iteration(recursion) with the empty string, shouldn't  it returns "True"?
Comment: It changes the code in **the same way** that it would change the code if you did **the same thing** with **any other** function call. Returning the value vs. just getting that value and ignoring it.
Answer: The first one is returning the value of recursive solution with the line:

return pal(s[1:-1])

Whereas the second one is just returning a void/None, and not the solution of recursive method.


Are my outside HVAC units and condensation drain PVC pipes set up correctly?

Question: I'm a newbie with this stuff, but here's my situation: I have two HVAC units in my home. One sits on top of the patio and one sits on the ground. Both of them are draining condensation from the PVC pipes.
It's been pretty humid so I understand why there's condensation drip from the PVC pipes - but I am not sure if the set up is correct in the first place.
Both of the HVAC units seem to have 2 PVC pipes each coming out from the wall of the house, but all 4 of them are open. The main unit has one that faces outwards and one that has an L-joint that faces down, and the secondary unit has two with L-joints that face down. Only one on each of them are currently draining.
The main unit is draining onto the ground, but puddling as it's a lot of water, and I am concerned about it damaging the foundation over time if that's even a concern. The secondary unit is draining over the patio and just making a trail until it goes to the grass, it's pretty ugly and ideally it would drain somewhere cleanly.
Is this set up even OK as is? I took a look at the drip pans inside the house and both are empty so I think it is fine, is this correct?
Answer: Condensate drip and accumulation are normal, especially during the summer months.
It is also very normal to find the drain lines terminated close to the house as you have described. Whether it is acceptable I guess could be argued based on the volume of water in question and where it is collecting.
If the accumulation of water is getting worrisome, you can buy some small diameter PVC pipe and reroute or extend your existing drain lines. You can even get creative, such as routing them into existing downspout drain lines, or directly burying the condensate drain lines themselves.
If you are worried about exterior-drained condensate freezing, you could bury a standard 4" drainage pipe to redirect your condensate. This pipe could accumulate your condensate via a catch basin, direct piping, or other means. The probability of an entire 4" pipe freezing, especially in the southeastern US, would be approaching zero.
Be sure to maintain a good slope when extending any lines, and drain to daylight any buried lines.
Additionally, you can drain your condensate to some acceptable locations inside your home, such as a plumbing drain (not a plumbing vent stack!).
Use this as a reference:
Comment: Is it normal that both pipes are open by the house at each unit? Is it also normal for the water to be accumulating next to the house? I did mention my concern for foundation problems, but maybe it is not an issue since it is a 70's built home.

I am worried about extending and/or rerouting the pipes because in the winter they could freeze - I have read some other concerns where they ended up cutting the PVC pipes for that.
Comment: What exactly are you asking is normal-- that the pipes are open, or that they drain next to the house? Both are normal, but I don't think you'd want them draining _down the side_ of your house. You'll want at least a little extension away from the structure. Unless you're pumping out some serious condensate, I doubt it could cause any foundation issues. In what area of the country/world do you live?
Comment: Well if they are both normal, I supposed that is fine. It definitely is not draining down the side of the house, but one as I mentioned is pooling on the ground by the house (between the wall and the AC unit) and one is leaving a trail of water on the patio from the pipe to the grass. I live in the Southeast US. Am I pretty much worrying for naught? Also, what significance is the other pipe per pair since only one is leaking?
Comment: @py7133, the second line is most likely your secondary drain line in case your primary gets clogged or otherwise fails. You will probably not ever see water out of the secondary drains unless the primaries aren't draining. I have edited my post to give you more options on drainage if you don't like the water accumulation.
Comment: This is a very informative update, especially with the catch basin/grate idea. This will probably help with the A/C unit on the ground, but I don't think I have a great solution for the one sitting on the patio other than adding more PVC piping. Thanks for your advice!


"Don't throw the game, throw POKéBALLs instead!"?

Question: The original Pokémon Red and Blue games feature a sign that says

Don't throw the game, throw POKéBALLs instead!

There's a video of this sign on YouTube:

I have never understood what this sign means. Is this a piece of wordplay that's going over my head? Is this something that got lost in translation?
Comment: My guess is its a wordplay on "don't rage quit and throw your Game Boy"
Answer: To "throw the game" means to lose on purpose, either through deliberate misplay or lack of preparation.
To "throw POKéBALLs" is a core game mechanic of the series. It would be very difficult to win without doing it.
So yes, it is wordplay. Both in- (referring to competing in Pokémon battles) and out-of-Universe (referring to playing the GameBoy game).

“Don’t throw the game, throw POKéBALLs instead!”?


Is it possible to start chromium with a chrome:// url?

Question: I would like to create a launcher launching:
chromium-browser chrome://inspect

However, this simply opens the chromium as if not url has been specified at all.
Is it even to start Chromium opening a chrome:// url?
Answer: While "normal" url's do work as expected, it seems impossible at first to use the chrome:// urls from a command, and there is nothing in the man chromium-browser man page on this.
However, it is very well possible to work around this, with the help of xdotool.
How it works

install xdotool
sudo apt-get install xdotool

Use the following command in your .desktop file:
/bin/bash -c "chromium-browser&sleep 2&&xdotool type 'chrome://inspect'&&xdotool key Return"

What it will do is open chromium browser, xdotool will type the chrome://inspect url and (simulate) press return.
Effectively this will do exactly what you want.
No need to say that you can replace chrome://inspect with any other of the chrome:// commands.
Note
In the command, there is a small break included of 2 seconds, to make sure the browser is loaded before xdotool starts to type. On my system (not the most recent) it can be changed to sleep 1 and still work perfectly. You can experiment a bit with it.

edit
Alternative
Dirty or not, a solution should always work. I tried the solution above now and then, and found that occasionally, it takes too long for the chromium-browser window to appear. Especially when the computer is heavily occupied, there is a chance xdotool starts typing "blindly".
The solution below is "time-proof" and should work under all circumstances; it makes sure xdotool only starts typing when a new chromium-browser window appears within appr. 15 seconds.
How to use

Copy the script below into an empty file
Save it as run_chrcommand.py
use as command in your .desktop file:
python3 /path/to/run_chrcommand.py

The script
#!/usr/bin/env python3
import subprocess
import getpass
import time

user = getpass.getuser()
get = lambda x: subprocess.check_output(["/bin/bash", "-c", x]).decode("utf-8")
ws1 = get("wmctrl -lp"); t = 0
subprocess.call(["/bin/bash", "-c", "chromium-browser&"])
while t < 30:
    ws2 = [w.split()[2] for w in get("wmctrl -lp").splitlines() if not w in ws1]
    procs = [[p for p in get("ps -u "+user).splitlines() \
              if "chromium-bro" in p and w in p] for w in ws2]
    if len(procs) > 0:
        command = "xdotool type 'chrome://inspect'&&xdotool key Return"
        subprocess.call(["/bin/bash", "-c", command])
        break
    time.sleep(0.5)
    t = t+1

Comment: That's a really ugly hack... but it works! Thanks
Comment: @RemcoHaszing always looking for the clean solution. But if there isn't, tools like `xdotool` are great :)
Comment: @RemcoHaszing Hi Remco, found out that occasionally the window appears too late for `xdotool`. The edit always works. If you need more then one `chromium` command, let me know, then the command should be made an argument.


Is there anything out there that will make it easy for me to allow my users to share their Facebook photos (and videos) on my site?

Question: I see a bunch of .NET open source projects out there that look to be able to get at the users information, but I just want a user to be able to "post" media that's already on Facebook on my site as well.  Other websites seem to allow you to do embedding of their media (I'm really liking oEmbed) but FB seems a bit of a mystery to me.  I have no experience using their API, but I'm guessing it has something to do with the "social graph" part.  Anyone else done this before?  Did you use something or is this easy enough to do without these OS projects?  Any examples anywhere of how someone already did this?  I wouldn't think that I'm the first person to want to do this but have searched Google and didn't come up with anything.
Answer: Have you tried FQL? Using this I was able to get users display pictures on any site I wanted by simply constructing a simple SQL like query.
Comment: So far haven't really tried anything, just been reading about the various methods.  Seems like there's multiple ways to do things, so wasn't really sure what path to even start down.
Comment: I ran stuff like https://api.facebook.com/method/fql.query?query=SELECT%20pid%20FROM%20photo%20WHERE%20aid%20IN%20%28%20SELECT%20aid%20FROM%20album%20WHERE%20owner=me%28%29%20%29%20ORDER%20BY%20created%20DESC%20LIMIT%201,42 or https://api.facebook.com/method/fql.query?query=SELECT%20src_big%20FROM%20photo%20WHERE%20pid%20IN%20%28SELECT%20cover_pid%20FROM%20album%20WHERE%20owner%20=%20me%28%29%20AND%20name%20=%20%27Profile%20Pictures%27%29 I think you're onto something but I'm only getting back
Comment: Keep trying, it was a while ago but the result set just returned a list of image files.  It was something similar to "select * userimages where name LIKE 'Tony Blair'"
Comment: I think maybe I have to call it from code and have an open oAuth or something session?  Truly have no clue if that's correct but sure am stumped on why no queries work for me.
Comment: I think it has to do with the fact that I'm using me() for the uid.  My thinking was that it would insert the current user that is logged in uid.  If I put a number it seems to work.  What the heck is wrong with me()?
Answer: The Facebook .NET SDK makes this very easy for you. You can download it here: http://facebooksdk.codeplex.com
Here is an example of how you would publish a photo using that SDK:
<code>string photoPath = @"..\..\..\Facebook.Tests\bin\Release\monkey.jpg";
byte[] photo = File.ReadAllBytes(photoPath);

FacebookApp app = new FacebookApp();
dynamic parameters = new ExpandoObject();
parameters.message = "The message you want to go with the photo...";
var mediaObject = new FacebookMediaObject {
    FileName = "monkey.jpg",
    ContentType = "image/jpeg",
};
mediaObject.SetValue(photo);
parameters.source = mediaObject;

dynamic result = app.Api("/the_album_id/photos", parameters, HttpMethod.Post);
string photoId = result.id;
</code>
Comment: I don't really need to publish the photo, just get the list of photos that they've already put up.  I think I would only need a list of photo URI's that I would allow them to choose from and then I could just link to the photo from my site.  This is still cool though, I might be able to use that in the future after I get the basic stuff going.


How do I have dark elixir with no storage

Question: I have dark elixir that I use with my dark barracks but I have no storage for it. How do I posses it and use it without storage?
Comment: if my answer solved your problem, can you click the check mark on it? Otherwise, what can I do to make it better?
Answer: If you townhall is level 7 or higher, it can hold dark elixir in it. It can hold 2,500 at th7, 5,000 at th8, 10,000 at th9, and 20,000 at th10+. Therefore you can hold dark elixir even without a dark elixir storage if you have a high enough townhall, but only in a smaller quantity.
Source


Avoid duplicate Patient on resource create

Question: When sending this request multiple times, I get multiple Patients created.
{
  "resourceType": "Patient",
  "identifier": [
    {
      "use": "usual",
      "system": "urn:oid:2.16.840.1.113883.19.5",
      "value": "12345"
    }
  ],
  "active": true,
  "name": [
    {
      "family": "Levin",
      "given": [
        "Omri"
      ]
    }
  ],
  "gender": "male",
  "birthDate": "1980-09-24"
}

My assumption is that when I provide the identifier, it would reject the 2nd call, as that PAtient already exists. But seems that is not the case? How do I avoid these duplications?
(Tried it both on Azure and on Google cloud - both with the same result)
Answer: I had to dig deeper into the docs. And the answer is here - https://www.hl7.org/fhir/http.html#ccreate
In my case adding the header If-None-Exist: identifier=urn:oid:2.16.840.1.113883.19.5|12345 did the trick on Azure. On Google cloud, however, if trying to use V1 of the API we get an error for adding that header:
{
    "issue": [
        {
            "code": "value",
            "details": {
                "text": "invalid_query"
            },
            "diagnostics": "conditional operations are not supported in API version v1",
            "severity": "error"
        }
    ],
    "resourceType": "OperationOutcome"
}

To overcome that we need to use v1beta1. So URL should change
- https://healthcare.googleapis.com/v1/projects/...
+ https://healthcare.googleapis.com/v1beta1/projects/...

Read more about the "v1" and "new v1beta1" difference here
Comment: Note that the beta implementation of conditional operations on GCP is currently not atomic, so if you create duplicate patients in quick succession some duplicates can get through. We are working to improve this functionality before promoting it to v1.
Comment: You can also always do a PUT. A FHIR PUT resource is a conditional PUT. Meaning if the data does not already exist it will create a new data. If it exist already then it will update the existing one. In this case you need to pass the url like -- ```url/identifier=someidentifier``` but as per FHIR standards the server functionality is implemented only in the HAPI FHIR server. So first try it in https://hapi.fhir.org/
Answer: Altarnatively you could use conditional update/create (PUT with search/match criteria) instead of a POST i.e. PUT Patient?identifier=urn:oid:2.16.840.1.113883.19.5|12345 with the same payload you have in your question.
Or you can POST a Bundle of one or more resources, also using PUT with search criteria :

    {
  "resourceType": "Bundle",
  "id": "bundle-transaction",
  "meta": {
    "lastUpdated": "2014-08-18T01:43:30Z"
  },
  "type": "transaction",
  "entry": [
    {
      "fullUrl": "urn:uuid:61ebe359-bfdc-4613-8bf2-c5e300945f0a",
      "resource": {
      "resourceType": "Patient",
      "identifier": [
        {
          "use": "usual",
          "system": "urn:oid:2.16.840.1.113883.19.5",
          "value": "12345"
        }
      ],
      "active": true,
      "name": [
        {
          "family": "Levin",
          "given": [
        "Omri"
          ]
        }
      ],
      "gender": "male",
  "birthDate": "1980-09-24"
      },
      "request": {
        "method": "PUT",
        "url": "Patient?identifier=urn:oid:2.16.840.1.113883.19.5|12345"
      }
    }
  ]
}

When using a Bundle, If no Patient resource with the same identifier already exists then the OperatioOutcome will return a 201 Created otherwise you will get a 200 OK and the resource will be updated, creating a new version of it.
You can read more about bundles here https://www.hl7.org/fhir/bundle.html


RCP/Plugin-Dev: How to add jar to target plattform

Question: I have an Eclipse RCP Application! And I copied the newest xtend lib (2.6.2, and xbase.lib too) to the plugin folder of the target/plattform.
But it still says that I have to copy the xtend lib to the classpath... (eclipse shows failures before running the plugin)
And I cant choose the newer version of the lib in the dependencys tab of my manifest (there was an old version of xtend in the target plattform too).
Is there something more then copying the jar files into the plugin folder to add a lib to your plugin project?
Comment: You can only have Eclipse plugins in the target platform. Is what you copied a plugin?
Comment: First I used the update site fo xtend, then I downloaded the runtime libraries .jar files and copied them into the target plattform. xtend is a plugin for eclipse.
Answer: If you want to add to a target platform from an update site you should open Preferences > Plug-in Development > Target Platform.
Click Edit... to edit the existing target platform.
On the Locations tab click Add... to add a new location.
Choose 'Software site' to add from an update site. Click Next and follow the instructions.
Comment: thank you for your answer! I tryed this but it gives me an error: Unable to locate installable unit org.eclipse.xtend.sdk.feature.group


-JSONValue Failed

Question: My code for JSON parsing:
<code>// Store incoming data into a string
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

// Create a dictionary from the JSON string
NSDictionary *results = [jsonString JSONValue];

NSLog(@"%@",jsonString);
</code>
When I debug the code I am getting the jsonString but getting 0 key value pairs.
And Error as:

-JSONValue failed. Error trace is: (
      "Error Domain=org.brautaset.JSON.ErrorDomain Code=5 \"Unescaped control character '0x0'\" UserInfo=0x4d2e030
  {NSLocalizedDescription=Unescaped control character '0x0'}",
      "Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key: id\" UserInfo=0x4d2e130 {NSUnderlyingError=0x4d2e090
  \"Unescaped control character '0x0'\", NSLocalizedDescription=Object
  value expected for key: id}",
      "Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Expected value while parsing array\" UserInfo=0x4d2e180
  {NSUnderlyingError=0x4d2e110 \"Object value expected for key: id\",
  NSLocalizedDescription=Expected value while parsing array}",
      "Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key: predictions\" UserInfo=0x4d2e250
  {NSUnderlyingError=0x4d2e210 \"Expected value while parsing array\",
  NSLocalizedDescription=Object value expected for key: predictions}"
Answer: Use JSON validator to validate your string whether that is a valid JSON.

-JSONValue Failed


JavaScript's setTimeout doesn't work

Question: I have a simple JS object which emulates traffic lights:
function TrafficLight(redTime, yellowTime, greenTime) {
    var self = this;

    this.__timer = null;
    this.__state = null;
    this.__redTime = redTime;
    this.__yellowTime = yellowTime;
    this.__greenTime = greenTime;

    var setnewtimer = function (delay, func) {
        console.log('SET!');
        if (self.__timer) {
            clearTimeout(this.__timer);
        }
        self.__timer = setTimeout(delay, func);
    };

    TrafficLight.prototype.toRed = function () {
        this.__state = 'red';
        setnewtimer(this.__redTime, function () {
            console.log('RED!');
            self.toGreen();
        });
    };

    TrafficLight.prototype.toGreen = function () {
        this.__state = 'green';
        setnewtimer(this.__greenTime, function () {
            console.log('GREEN');
            self.toYellow();
        });
    };

    TrafficLight.prototype.toYellow = function () {
        this.__state = 'yellow';
        setnewtimer(this.__yellowTime, function () {
            console.log('YELLOW');
            self.toRed();
        });
    };

    TrafficLight.prototype.state = function () {
        return this.__state;
    };

    this.toGreen();
}

But when I make a TrafficLight object (like var a = new TrafficLight(1000, 1000, 1000);), every a.state() call returns green (so traffic light doesn't change its state by timer. What's wrong with my code?
Comment: *"JavaScript's setTimeout doesn't work"* It does, you know. But it's not JavaScript's, it's the browser's.
Answer: You don't call setTimeout correctly.
Change
setTimeout(delay, func);

to
setTimeout(func, delay);

Comment: @OliverWatkins That's true, but in cases like this the first thing I would check was the documentation of the function that isn't working.

JavaScript's setTimeout doesn't work


How to replace set or group of characters with string in Python

Question: I am trying to make a simple script replacing all occurrences of certain group or set of characters (or set of strings) in text.
In this case I will try to replace all letters "a,e,i,o,u" with certain string.
My script:
def replace_all(text, repl):
    text1 = text.replace("a", repl)
    text2 = text1.replace("e", repl)
    text3 = text2.replace("i", repl)
    text4 = text3.replace("o", repl)
    text5 = text4.replace("u", repl)
    return text5

Is there any simpler way of doing it? What if I need to replace bigger group of chars or strings? Chaining it like this does not seem to be really effective then.
This is maybe a primitive question. However, I am still in learning phase so maybe I get it in later lessons. Thank you in advance for any advice.
Answer: My knowledge tells me there are 3 different ways of doing this, all of which are shorter than your method:

Using a for-loop
Using a generator-comprehension
Using regular expressions

First, using a for-loop. This is probably the most straight-forward improvement to your code and essentially just reduces the 5 lines with .replace on down to 2:
def replace_all(text, repl):
    for c in "aeiou":
        text = text.replace(c, repl)
    return text

You could also do it in one-line using a generator-comprehension, combined with the str.join method. This would be faster (if that is of importance) as it is of complexity O(n) since we will go through each character and evaluate it once (the first method is complexity O(n^5) as Python will loop through text five times for the different replaces).
So, this method is simply:
def replace_all(text, repl):
    return ''.join(repl if c in 'aeiou' else c for c in text)

Finally, we can use re.sub to substitute all of the characters in the set: [aeiou] with the text repl. This is the shortest of the solutions and probably what I would recommend:
import re
def replace_all(text, repl):
    return re.sub('[aeiou]', repl, text)

As I said at the start, all these methods complete the task so there is no point me providing individual test cases but they do work as seen in this test:
>>> replace_all('hello world', 'x')
'hxllx wxrld'

Update
A new method has been brought to my attention: str.translate.
>>> {c:'x' for c in 'aeiou'}
{'a': 'x', 'e': 'x', 'i': 'x', 'o': 'x', 'u': 'x'}
>>> 'hello world'.translate({ord(c):'x' for c in 'aeiou'})
'hxllx wxrld'

This method is also O(n), so just as efficient as the previous two.
Comment: What about str.translate()? and why this is a good or a bad idea?
Comment: @PoeteMaudit Never encountered that method before! See my update. I don't know what you mean by "good" or "bad" - you can do whatever you want so long as it is as efficient as is required, which I would expect this method to be.
Comment: I am surprised that you have not encounter before. See this too: https://stackoverflow.com/questions/56378872/replace-multiple-special-characters-most-efficient-way.
Answer: This is a fine place for a regular expression:
import re

def replace_all(text, repl):
    return re.sub('[aeiou]', repl, text)

This will work for the case in your question, where you're replacing single characters. If you want to replace a set of longer strings:
def replace_all(text, to_replace, replacement):
    pattern = '|'.join(to_replace)
    return re.sub(pattern, replacement, text)

>>> replace_all('this is a thing', ['thi','a'], 'x')
'xs is x xng'

Answer: So what you're doing is perfectly valid, however there are better ways.
Here are some solutions, with runtimes taken over 100000 loops.
The main signature:
Targets are the characters you want to replace, repl is the replacement character.
def replace_all(text, targets=['a', 'e', 'i', 'o', 'u'], repl='_'):
    text = # Something here to swap characters as an array
    return ''.join(text) # Stitch it back together

Bytearray
Bytearray Is a mutable data structure that contains a list of the characters themselves. As a data structure, it is seemingly the ideal choice, strings in python are immutable, this works around that to prevent constant construction/destruction.
[chr(c) if chr(c) not in targets else repl for c in bytearray(text, 'utf-8')]

Runs in 0.365
Without bytearray
This operates on a simple list, the list itself is mutable, but the characters are strings, therefore there is some modification of technically immutable structures here.
[c if c not in targets else repl for c in text]

runs in 0.179
Map
This maps the function onto each character in the string.
map(lambda c: c if c not in targets else repl, text)

Runs in 0.265


Mute Rails memcache logging in development env

Question: Would like to mute large amount of dalli output in development log & STOUT.
Answer: Create an initialiser with the following:
<code>Rails.cache.silence!
</code>
Taken from https://github.com/mperham/dalli/issues/207


Issue when apply RIB and Autodispose libs

Question: I have problem when apply Rib (ver 0.9.1) and Autodispose (ver 1.1.0) libs. My RootActivity (extent RibActivity) cannot resolve "LifecycleScopeProvider". I found that LifecycleScopeProvider not exist in ver 1.1.0 but have in ver 0.2.0.
Answer: RIBs are not maintained publicly are are using an old version of the library. You'd need to use the modern names for those items post-1.0.


Working on multiple interdependent projects with Git

Question: My problem is the following:
I am developing 2 Python packages A and B and B uses A. Thus, when I change something in the package A, I often have to make some small changes in package B to adapt function calls etc.
Both my packages are git repositories. I would like to be able to commit changes from both repos in a single commit. However, I want to keep the ability to commit separately in each repo.
I checked git submodules and git worktree but it doesn't seem to be exactly what I need. Do you know some other method?
Thanks.
Answer: I don't think this is possible. A commit is basically a collection of files that live in the objects database, and the commit itself is persisted in that same database, which is located inside of <code>.git/</code>. Therefore, one commit from one repository can't contain files from another, so you can't commit to multiple repositories at once.
If you feel the need to change both repositories in a single commit, maybe they should be merged into a single repository (I understand there might be reasons not to do so). Or maybe you should revisit the way one integrates with the other so that a change in one doesn't always trigger a change in the other. Ultimately, it sounds like you're trying to use the wrong tool for the job.


Two type relationship - problem with append attribute

Question: I have a 2 type of relationship between 2 models. Look at the code
protected $appends = [
    'avatar_name'

];
public function avatar() {
    return $this->hasOne(Avatar::class)->latest();
}

public function avatars()
{
    return $this->hasMany('App\Models\Avatar');
}
public function getAvatarNameAttribute()
{
    return $this->attributes['avatar_name'] = isset($this->avatar->name) ? $this->avatar->name : null;
}

Into Profile model I have only one relationship:
public function profile(){
    return $this->belongsTo(Profile::class);
}

This relationships is clear for me - I need display all avatars for single profile (which he upload) and display one avatar which will be display in navigation or in a comments. Problem is that if I try to change the avatar, avatar_name displays all the time this same value. Profile models have avatar_id field, of course.
@Update
I try check that in tinker, so I wrote
Profile::with('avatar')->find(1)->latest()->first()

But all the time it display this same avatar_name
Answer: In Migration (Avatars):
$table->foreignId('user_id')->constrained('users');

In Profile Model:
public function avatars()
{
    return $this->hasMany('App\Models\Avatar');
}

In  Controller:
$profile = Profile::with('avatars')->find($id);
$avatar = $profile->avatars()->latest()->first();
$avatars = $profile->avatars()->latest()->get();

Output will return like this (Avatar is first and Avatars array is second):

Note: As you can see in example image latest() by default sorts by ID not date time for this you have to specify table (idk why one would do that but in case).
Comment: All in all, you're right. Tomorrow, I'll try do that :)
Comment: it desn't work. If I use `latest()` in hasOne relationship, it always display the latest uploaded avatar. If i remove that it display first. I remove`->latest` from avatars (hasMany) but it nothining change.
Comment: try this updated code and if not resolved add your models for more info.
Comment: @wtsuport $user = User::with('avatars')->find(3);
        $data = $user->avatars()->latest()->first();
Comment: updated code as well give it a try.
Comment: It doesn't work. All the time it's display this same avatar - first or latest, denf's of query. But in controller I want to write `Profile::findOrFail($id)` and I want to have `avatar_name`
Comment: Can you tell if you get one part right atleast where you want to get all the users avatar? And if you want user to select a specific image to be profile picture (among the uploaded) just add a table field as isAvatar (set true if user selects it else defaults to false)


Inverting X axis number labels in chart.js scatter chart

Question: I'm trying to plot a chart using chart.js with inverted order of the X axis. It's a scatter chart. This is the Js code I'm experimenting with:
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
    type: 'scatter',
    data: {
        datasets: [{
            label: '# of Votes',
            fill: false,
            showLine: true,
            cubicInterpolationMode: 'default',
            data: [
              {x: 118, y: 92.82 }, {
              x: 115.8, y: 92.88 }, {
              x: 113.03, y: 93.62 }, {
              x: 110.94, y: 93.84 }, {
              x: 107.93, y: 94.95 }, {
              x: 103.86, y: 97.22 }, {
              x: 101.78, y: 98.54 }, {
              x: 100.68, y: 99.95 }, {
              x: 98.34, y: 102.58 }, {
              x: 96.67, y: 105.9 }, {
              x: 95.47, y: 109 }, {
              x: 94.69, y: 111.41 }, {
              x: 94.18, y: 113.71 }, {
              x: 93.92, y: 115.63 }, {
              x: 93.82, y: 117.25 }, {
              x: 93.67, y: 118.48 }, {
              x: 93.57, y: 120 }
              ],
              pointRadius: 0
        }]
    },
    options: {

    }
});

This is the image I obtain:

What I would like to obtain is having the x axis being inverted, so starting from 120 to 90, in descending order.
I looked around and tried a bunch of solutions but without success.
I have a JsFiddle to reproduce this code:
https://jsfiddle.net/webgio/43phnctq/
Answer: This is intergraded in chart.js by using the reverse option:
options: {
    scales: {
        yAxes: [{
            ticks: {
                reverse: true
            }
        }]
    }
}

Documentation

var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
    type: 'scatter',
    data: {
        datasets: [{
            label: 'sample title',
            fill: false,
            showLine: true,
            cubicInterpolationMode: 'default',
            data: [{ x: 118, y: 92.82 }, {x: 115.8, y: 92.88 }, {x: 113.03, y: 93.62 }, {x: 110.94, y: 93.84 }, {x: 107.93, y: 94.95 }, {x: 103.86, y: 97.22 }, {x: 101.78, y: 98.54 }, {x: 100.68, y: 99.95 }, {x: 98.34, y: 102.58 }, {x: 96.67, y: 105.9 }, {x: 95.47, y: 109 }, {x: 94.69, y: 111.41 }, {x: 94.18, y: 113.71 }, {x: 93.92, y: 115.63 }, {x: 93.82, y: 117.25 }, {x: 93.67, y: 118.48 }, {x: 93.57, y: 120 } ],
            pointRadius: 0
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    reverse: true,
                }
            }]
        }
    }
});
canvas { max-width: 400px; }

<canvas id="myChart"></canvas>

Updated fiddle
Output:


IBM MQ expects username and password when using SSL certificates (Error 2035)

Question: I am stuck at using SSL in IBM Websphere MQ (9.2).
I am building a client library for MQ and to get more familiar with MQ on the server side I have installed IBM MQ Developer edition and ran the supplied scripts to create a 'default' MQ server instance.

Created an client connection for the DEV.APP.SVRCONN server connection
Created a personal certificate by using the IBM Key management tool and named it ibmwebspheremq
Enabled SSL on the Queue Manager (QM1) and labelled it ibmwebspheremq
Updated the SSL configuration for the DEV.APP.SVRCONN channel and set the cipherspec property to TLS 1.2, 256-bit Secure Hash Algorithm, 128-bit AES encryption (TLS_RSA_WITH_AES_128_CBC_SHA256) and made SSL required.

Tested my settings with:
amqssslc -l ibmwebspheremq -k C:\ProgramData\IBM\MQ\qmgrs\QM1\ssl\key  -c DEV.APP.SVRCONN -x 127.0.0.1 -s TLS_RSA_WITH_AES_128_CBC_SHA256 -m QM1

And that gave me:
Sample AMQSSSLC start
Connecting to queue manager QM1
Using the server connection channel DEV.APP.SVRCONN
on connection name 127.0.0.1.
Using SSL CipherSpec TLS_RSA_WITH_AES_128_CBC_SHA256
Using SSL key repository stem C:\ProgramData\IBM\MQ\qmgrs\QM1\ssl\key
Certificate Label: ibmwebspheremq
No OCSP configuration specified.
MQCONNX ended with reason code 2035

Error details (from log):
The active values of the channel were 'MCAUSER(app) CLNTUSER(Wilko)
SSLPEER(SERIALNUMBER=61:9B:A4:3E,CN=DESKTOP-ROH98N2,C=NL)
SSLCERTI(CN=DESKTOP-ROH98N2,C=NL) ADDRESS(DESKTOP-ROH98N2)'. The
MATCH(RUNCHECK) mode of the DISPLAY CHLAUTH MQSC command can be used to
identify the relevant CHLAUTH record.
ACTION:
Ensure that the application provides a valid user ID and password, or change
the queue manager connection authority (CONNAUTH) configuration to OPTIONAL to
allow client applications to connect which have not supplied a user ID and
password.
----- cmqxrmsa.c : 2086 -------------------------------------------------------
22/11/2021 15:51:37 - Process(15880.45) User(MUSR_MQADMIN) Program(amqrmppa.exe)
                      Host(DESKTOP-ROH98N2) Installation(Installation1)
                      VRMF(188.8.131.52) QMgr(QM1)
                      Time(2021-11-22T14:51:37.594Z)
                      CommentInsert1(DEV.APP.SVRCONN)
                      CommentInsert2(15880(1112))
                      CommentInsert3(127.0.0.1)

AMQ9999E: Channel 'DEV.APP.SVRCONN' to host '127.0.0.1' ended abnormally.

EXPLANATION:
The channel program running under process ID 15880(1112) for channel
'DEV.APP.SVRCONN' ended abnormally. The host name is '127.0.0.1'; in some cases
the host name cannot be determined and so is shown as '????'.
ACTION:
Look at previous error messages for the channel program in the error logs to
determine the cause of the failure. Note that this message can be excluded
completely or suppressed by tuning the "ExcludeMessage" or "SuppressMessage"
attributes under the "QMErrorLog" stanza in qm.ini. Further information can be
found in the System Administration Guide.
----- amqrmrsa.c : 630 --------------------------------------------------------

I am kind of stuck, I also saw in the log that there is PEER related info dumped, but I am not sing the SSLPEER settings (I just want to let everyone connect with the same certificate).
EDIT 2:
Output from RUNMQSC QM1 and command DISPLAY QMGR CONNAUTH:
     1 : DISPLAY QMGR CONNAUTH
AMQ8408I: Display Queue Manager details.
   QMNAME(QM1)                             CONNAUTH(DEV.AUTHINFO)

Output from RUNMQSC QM1 and command DISPLAY AUTHINFO(name-from-previous-command):
     3 : DISPLAY AUTHINFO(DEV.AUTHINFO)
AMQ8566I: Display authentication information details.
   AUTHINFO(DEV.AUTHINFO)                  AUTHTYPE(IDPWOS)
   ADOPTCTX(YES)                           DESCR( )
   CHCKCLNT(REQDADM)                       CHCKLOCL(OPTIONAL)
   FAILDLAY(1)                             AUTHENMD(OS)
   ALTDATE(2021-11-18)                     ALTTIME(15.09.20)

Output from DISPLAY CHLAUTH(*):
     4 : DISPLAY CHLAUTH(*)
AMQ8878I: Display channel authentication record details.
   CHLAUTH(DEV.ADMIN.SVRCONN)              TYPE(USERMAP)
   CLNTUSER(admin)                         USERSRC(CHANNEL)
AMQ8878I: Display channel authentication record details.
   CHLAUTH(DEV.ADMIN.SVRCONN)              TYPE(BLOCKUSER)
   USERLIST(nobody)
AMQ8878I: Display channel authentication record details.
   CHLAUTH(DEV.APP.SVRCONN)                TYPE(ADDRESSMAP)
   ADDRESS(*)                              USERSRC(CHANNEL)
   CHCKCLNT(REQUIRED)
AMQ8878I: Display channel authentication record details.
   CHLAUTH(SYSTEM.ADMIN.SVRCONN)           TYPE(ADDRESSMAP)
   ADDRESS(*)                              USERSRC(CHANNEL)
AMQ8878I: Display channel authentication record details.
   CHLAUTH(SYSTEM.*)                       TYPE(ADDRESSMAP)
   ADDRESS(*)                              USERSRC(NOACCESS)

I was expecting not having to provide username and password when using certificates. What am I missing here?
Comment: Please show us the following setting to help us understand how your queue manager is setup. DISPLAY QMGR CONNAUTH / DISPLAY AUTHINFO(name-from-previous-command) / DISPLAY CHLAUTH(*)
Answer: Your queue manager is configured to mandate passwords for any client connections that are trying to run with a resolved MCAUSER that is privileged. That is what CHCKCLNT(REQDADM) on your AUTHINFO(DEV.AUTHINFO) does.
In addition, your CHLAUTH rule for the DEV.APP.SVRCONN channel has upgraded this further to mandate passwords for ALL connections using that channel.
If your intent is to have channels that supply a certificate not be subject to this mandate, then you should add a further, more specific, CHLAUTH rule, something along these lines:-
SET CHLAUTH(DEV.APP.SVRCONN) TYPE(SSLPEERMAP) +
    SSLPEER('SERIALNUMBER=61:9B:A4:3E,CN=DESKTOP-ROH98N2,C=NL') +
    SSLCERTI('CN=DESKTOP-ROH98N2,C=NL') CHCKCLNT(ASQMGR) USERSRC(CHANNEL)

Bear in mind that if this connection is asserting a privileged user id, it will still be required to supply a password from the system-wide setting of CHCKCLNT(REQDADM).
Remember, if you are ever unsure which CHLAUTH rule you are matching against, all those details you saw in the error message can be used to form a DISPLAY CHLAUTH command to discover exactly which rule you have matched. Read more about that in I'm being blocked by CHLAUTH – how can I work out why?
Comment: Is a SSL peer map required when 'disabling' user based authentication?
Comment: No, but it seems like a sensible alternative if you're not using a password for authentication.


My .htaccess file not works properly

Question: I have developed site,I need to run the page as index instead of index.php..i used the .htaccess file too,but unable to achieve a solution..Is there any thing wrong with the code or do i need to do changes..Any helpwould be appreciated..
    <Files ~ "^\.(htaccess|htpasswd)$">
deny from all
</Files>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
order deny,allow

Answer: Try this way to remove your .php from files
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Answer: Actually you only have to specify RewriteEngine on only once. Then make sure of the following:

mod_rewrite is installed and enabled
Make sure your AllowOverride directive is not set to None. You can find valid options for AllowOverride here.

My .htaccess file not works properly


Can fiberglass insulation cause leaks?

Question: I've recently bought a 100 year old wood frame house from a DiY guy who took decent care of the place. He didn't put any insulation in the attic though and my home inspector said insulation is a great easy home improvement project with very little downside or risk.
So among a few other projects, I started buying a batt of 19 faced insulation every time I go to the store, and then laying it piece by piece. My plan was to then buy 30 r insulation unfaced and lay it on top.
But...
We've had some exceptionally hot weather this summer. Today there's a fierce thunderstorm, and I'm sitting by the chimney and I hear drip... Drip... Crap. I run up to the attic, and I have two significant leaks. One from the chimney flashing, and one from the attic vent. Rest of the attic is bone dry.
I run to the basement and there's a stream of water running from the wall. I used to see lots of condensation on the floor but this is visible moving water. Woah, that's new.
Obviously these need fixed, and obviously my insulation needs to air dry now. But the timing has me suspicious. Did I cause the leak? Did the attic overheat and cause something to shift? Or did the ancient chimney just finally wedge the wood frame enough for water?
Should I pull the insulation out and can the whole project? Or fix the leaks and forge ahead?
Thanks for any help.
Comment: There's no correlation between the insulation and the leaks in the roof. Those are just leaks you need to fix. The running water in the basement is an entirely different problem. And a potentially huge one. I'd suggest you focus on fixing these water issues first for no other reason that water will cause a lot of damage if not taken care of sooner than later.
Comment: What type/style of vent?
Comment: _Today there's a fierce thunderstorm,_ Umm, there you go, uncommonly intense downpour, water pooling against flaky flashing and of course it's going to leak. Insulation isn't going to cause this to happen, it's just going to happen every time you have this much water hitting your roof. And lots of water going into the ground causes a fracture in the basement wall to stream water. I know a guy whose basement used to flood every time there's an intense thunderstorm, he wrote articles about basement water pressure and the need to have drainage. Again, not the insulation, but the rainstorm.
Answer: Correlation is not causation.
No, the insulation did not make your roof leak around the chimney nor at the vent. Being 100 years old (and odds are great someone did something sketchy during one of those years, though even the best construction/repair jobs don't last forever) did that. Rather than chase chimeras, fix the leaks.
Comment: Thanks. I know the leaks have to be fixed, but I didn't want to reopen them again by not fixing the cause. Just a coincidence! Phew... To the insurance company.

Can fiberglass insulation cause leaks?


Python 3.3 installation error - abort installation

Question: When I try to upgrade python3 version, I am getting the following error
sudo apt-get build-dep python3.2
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  autoconf blt blt-dev debhelper dh-apparmor diffstat gettext html2text
  intltool-debian libbluetooth-dev libdb5.1-dev libffi-dev libfontconfig1-dev
  libfreetype6-dev libgdbm-dev libgettextpo0 libjs-sphinxdoc libjs-underscore
  libncursesw5-dev libreadline-dev libreadline6-dev libtinfo-dev libunistring0
  libxext-dev libxft-dev libxrender-dev libxss-dev libxss1 m4 po-debconf
  python-sphinx quilt sharutils sphinx-common tcl8.5 tcl8.5-dev tk8.5
  tk8.5-dev x11proto-render-dev x11proto-scrnsaver-dev x11proto-xext-dev xvfb
0 upgraded, 42 newly installed, 0 to remove and 0 not upgraded.
Need to get 16.6 MB of archives.
After this operation, 53.1 MB of additional disk space will be used.
Do you want to continue [Y/n]? y
Abort.

Why am I getting aborted? I referred this link to upgrade python3.
I would like to remove python 3.2 after installing 3.3 version
Edit 1:
Also tried with Y (capital y). But not working.
Comment: maybe try with upper case `Y`?
Comment: Also tried it. but not working
Answer: I am not sure what was the error. But now I have succeeded the above problem.
What I have done is,
Step 1) Restarted my PC
2) Ran the following commands
sudo apt-get update
sudo apt-get upgrade
wget http://python.org/ftp/python/3.3.2/Python-3.3.2.tar.bz2
tar -xvjf ./Python-3.3.2.tar.bz2
cd ./Python-3.3.2
./configure --prefix=/opt/python3.3
make && make install
mkdir ~/bin
ln -s /opt/python3.3/bin/python ~/bin/py
echo 'alias py="/opt/python3.3/bin/python3"' >> .bashrc
sudo apt-get install build-essential
sudo apt-get install build-essential libncursesw5-dev libreadline-dev libssl-dev libgdbm-dev libc6-dev libsqlite3-dev tk-dev
sudo apt-get build-dep python3.2

And then it is now installed. But still can't install the virtualenv. And have raised as a new question in this link


Why does "lighter" @font-face still appear as the "normal" weight @font-face

Question: I'm trying to use the "lighter" version of my font, but in firefox and chrome it still appears as the "normal" weight.
Here is my font.css:
@font-face {
font-family: Avenir;
font-weight: normal;
src: url("AvenirLTStd-Medium.otf") format("opentype");
}

@font-face {
font-family: Avenir;
font-weight: bold;
src: url("AvenirLTStd-Black.otf") format("opentype");
}

@font-face {
font-family: Avenir;
font-weight: lighter;
src: url("12-Avenir-Light.ttf") format("opentype");
}

Here is what I'm using to activate the "lighter" weight on the H2 in #home:
body {
    background: none repeat scroll 0 0 #DADAD2;
    font-family: 'Avenir',sans-serif;
    font-weight: normal;
}

#home .six.columns h2 {
    color: #FAFAFA;
    display: block;
    font-size: 1.8em;
    font-weight: lighter;
    letter-spacing: 0.3em;
    margin-top: 25%;
    text-align: center;
}

You can see what I'm talking about here (just hover over one of the product images):
https://fine-grain-2.myshopify.com/
Comment: Changing the `font-weight` value to any of `500`, `600`, `700`, `800`, `900`, and `bold` definitely changes the text. All other values appear as "normal". I'm not saying that's *correct*; I'm just adding some extra detail.
Comment: @JamesA.Rosen Are you speaking about on my website? I know its really weird because the "lighter" value should change the text to the thinner font variation.
Comment: I agree. I was confirming and adding some extra detail in the hopes that it might be useful to someone else.
Comment: Related: http://stackoverflow.com/questions/10627810/chrome-19-not-recognising-font-weight-lighter. Unfortunately, using `100` solved that problem, which it doesn't here. Are you sure the font in question has a lighter version?
Comment: I still have no idea why it was happening, but I've come up with a hackey solution.
Answer: font-weight: lighter is telling the browser to use a lighter font than an inherited weight. So if a parent element has font-weight: bold, and it's child has font-weight: lighter - the child will have a regular weight (i.e. lighter than bold).
"lighter" is not a synonym for a font-weight of 100.
@font-face is used to define your font weights, so terms like 'bolder' and 'lighter' have no meaning. You should use numerical values to define your fonts and the lighter/bolder keywords when you want to use the fonts.
Comment: Wonderful explanation!, thanks to you I finally was able to understand what was happening.
Comment: What the H$@L :)
Answer: If you want to keep the font-family consistent, in this case 'Avenir' and not 'Avenir-light' you can use the following syntax:
@font-face {
    font-family: Avenir;
    font-weight: 100;
    src: url("12-Avenir-Light.ttf") format("opentype");
}

This syntax allows you to keep the font-family name consistent and the normal weight will display correctly. The CSS for the target element would then be:
.targetElement{
    font-family: Avenir;
    font-weight: lighter;
}

Comment: Thanks, this is more consistent solution.
Answer: I found a little hack that differentiates between the lighter and normal font weights.
I just changed my Avenir lighter @font-face from:
@font-face {
    font-family: Avenir;
    font-weight: lighter;
    src: url("12-Avenir-Light.ttf") format("opentype");
}

to:
@font-face {
    font-family: AvenirLight;
    font-weight: normal;
    src: url("12-Avenir-Light.ttf") format("opentype");
}

For some reason it was using the "lighter" font weight for normal and lighter. After I made this change the normal Avenir started using the real normal weight, and when I want to use the lighter weight I just change the font-family to AvenirLight
Comment: This is not consistent solution, see other answer.
Comment: This is a trick that you may need to use to get light typeface, depending on font family and browser. You are effectively declaring a typeface as if it were a font family (and use a "normal" typeface of that "family"). FontSquirrel does this all the time in its font generator. Consider reporting this to the font vendor; the causes of this problem are obscure and might depend on font file format. In any case, when trying use `font-weight`, use the numeric value given by the font vendor, not the relative keyword `lighter`.
Comment: Hi. Pretty same issue here, but with a different font. I used `font-weight: lighter` as well and it basically overwrites my second definition for `font-weight: normal`. Fix is to use the numeric values. Then all is fine. In this sense, I confirm the very last statement of @JukkaK.Korpela


how to create horizontal drop-down menu with javascript for asp.net website?

Question: i am developing i website using master page this master page doesn't has any menus but i want to create a javascript menu for one of the content page and this page will navigate to other pages the will have the same menu always appeared there.
i am using c# and asp.net so how to do that and make this menu also fixed among all selected items (and see which one selected by some css) .
i hope that i described well what i need because i am so confused so sorry for that.
Comment: I'm sorry, I don't really understand your question...
Comment: sorry for that look i need a menu that will appear only in one of the content page i mean this content page will take the style of the master page +new menu that will appear only there (we can consider at this time this content page as another master page) is it clear now or what?
Comment: As far as I can understand you want to have a dropdown menu listing all your pages, and if the user click on it, her/his browser should navigate to that page. Is that correct?
Comment: yeah correct but i mean  i want this menu appear in all pages
Comment: put the code in the master page
Comment: AH, now I understand. But I see someone has already answered this question. @speciallife
Comment: yeah right but still there is a missing point for me i need to understand it , it is how to make this menu fixed in all page do i need to write the code of menu in all pages?
Answer: You don't need JS for this. There are many solution for this you just did not used the right keywords. Try search for: horizontal drop down menu css
The first step is to create a nested ul-li-ul-li structure:

Lorem

Mauricii

        Periher

Hellenico

Genere

Indulgentia

Tyrio

Quicumque

Then apply a few CSS rules.
#coolMenu,
#coolMenu ul {
    list-style: none;
}
#coolMenu {
    float: left;
}
#coolMenu > li {
    float: left;
}
#coolMenu li a {
display: block;
    height: 2em;
    line-height: 2em;
    padding: 0 1.5em;
    text-decoration: none;
}
#coolMenu ul {
    position: absolute;
    display: none;
z-index: 999;
}
#coolMenu ul li a {
    width: 80px;
}
#coolMenu li:hover ul {
    display: block;
}

Further code: http://www.cssnewbie.com/horizontal-dropdown-menus/
Other solution: http://matthewjamestaylor.com/blog/centered-dropdown-menus
Comment: See: http://stackoverflow.com/questions/6786511/how-to-fix-a-div-to-top-of-page-with-css-only
Comment: good thnx for that but how to make this menu fixed at the top of page while navigating among links and know which item is active now
Comment: Thnx Mr @Peter Kiss i will try your solution and i think it will solve my problem ,My regards :)


Solve for $x$: $(x+2)^{\log_2(x+2)}=8(x+2)^2$

Question:
Solve for $x$: $(x+2)^{\log_2(x+2)}=8(x+2)^2$.

Useless attempt:
$$(x+2)^{\log_2(x+2)}=8(x+2)^2,$$
$$(x+2)^{\frac{1}{\log_{x+2}(2)}}=8(x+2)^2.$$
Don't know what to do with this...
I can't figure out a way to solve this equation. I require a hint as to how to proceed with solving it.
Answer: Hint:
Take logarithm with base $2$ on both sides.
we will end up with $$(\log_2 (x+2))^2 = 3 + 2 \log_2 (x+2)$$
now, we just have to solve a quadratic equation.
Answer: Let $\log_2(x+2)=y$, then $x+2=2^y$. The given equation can be written as
$$2^{y^2}=8 \cdot 2^{2y} =2^{2y+3}.$$
Now solve
$$y^2=2y+3.$$


How to paginate in listview from one page to the other?

Question: I would like to know how to paginate in my listview from my first page to the second and so on and so forth. I have read abt using the Endless Adapter but that isn't a good idea since my data could go up to 1000. Preferably would be to press a 'Next' button and my listview would load the 2nd set of data.
Thanks in advance
Answer: Just clean your list and refill it with the next set of data on the button's click. Add a constraint for your list to have, for example, 20 or 30 items.
Comment: Hey thanks for the answer. I know I have to do that. But is there any example code that I can follow?
Comment: Sorry, have no code to show you.. Just try to search through some ListView documentation, I believe it will be not that hard. Good luck!


Inventory: Items don't show up & are picked up twice

Question: I'm very new to Unity, so I hope someone can help me.
I'm trying to code an inventory for my game. I've worked with this tutorial on YT: https://www.youtube.com/watch?v=AoD_F1fSFFg&list=PL9JG3IlUvOUH_7EHF-dTCanunbDcq-iBQ&index=19&ab_channel=SoloGameDev
I made a few changes, like opening and closing the inventory window with I key instead of a button & picking up objects with E key instead of having to click on them.
Now two problems occured for me:

The picked up items are not displayed in the inventory window
The items are picked up twice

I've searched the internet for a solution but I didn't manage to make my code work as I'm not sure where I have to change it. I guess I have to change something in InventoryManager/InventoryOpener? I hope someone can help me because I really want to understand this. Thank you very much :)
Here's all my code related to the inventory:
Item.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[CreateAssetMenu(fileName ="New Item", menuName ="Item/Create New Item")]

public class Item : ScriptableObject
{
    public int id;
    public string itemName;
    public Sprite icon;
}

ItemController.cs:
 using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class ItemController : MonoBehaviour
    {
        public Item Item;
    }

ItemPickup.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemPickup : MonoBehaviour
{
    public Item Item;
    public GameObject PickupText;

    void Start()
    {
        PickupText.SetActive(false);
    }

    void Pickup()
    {
        if(Input.GetKeyDown(KeyCode.E))
        {
            InventoryManager.Instance.Add(Item);
            Destroy(gameObject);
            PickupText.SetActive(false);
            Debug.Log(Item.itemName + " added to inventory");
        }
    }

    void OnTriggerEnter(Collider col)
    {
        PickupText.SetActive(true);
        Debug.Log("Player is in pickup range");
    }

    void OnTriggerStay(Collider col)
    {
        Pickup();
    }

    void OnTriggerExit(Collider col)
    {
        PickupText.SetActive(false);
        Debug.Log("Player is outside pickup range");
    }

}

InventoryOpener.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InventoryOpener : MonoBehaviour
{
    public GameObject inventory;
    private bool isOpen;

    void Start()
    {
        isOpen = !isOpen;
    }

    void Update()
    {
        if(Input.GetKeyDown(KeyCode.I))
        {
            if(isOpen == true)
            {
                Debug.Log("Inventory closed");
                inventory.SetActive(false);
                isOpen = false;
            }
            else
            {
                Debug.Log("Inventory opened");
                inventory.SetActive(true);
                isOpen = true;
            }

        }
    }
}

InventoryManager.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class InventoryManager : MonoBehaviour
{
    public static InventoryManager Instance;
    public List<Item> Items = new List<Item>();

    public Transform ItemContent;
    public GameObject InventoryItem;

    private void Awake()
    {
        Instance = this;
    }

    public void Add(Item item)
    {
        Items.Add(item);
        Debug.Log("An item was added to the item list");
    }

    public void Remove(Item item)
    {
        Items.Remove(item);
    }

    public void ListItems()
    {
        foreach (Transform item in ItemContent)
        {
            Destroy(item.gameObject);
        }

        foreach (var item in Items)
        {
            GameObject obj = Instantiate(InventoryItem, ItemContent);
            var itemName = obj.transform.Find("ItemName").GetComponent<Text>();
            var itemIcon = obj.transform.Find("ItemIcon").GetComponent<Image>();

            itemName.text = item.itemName;
            itemIcon.sprite = item.icon;
        }
    }
}

Answer: Well, quickly looking through the video you linked, at 11:43 they start making a method in the InventoryManager.cs called SetInventoryItems() and they then call it at the end of ListItems() method. You don't have this method defined. This should solve the issue of items not being displayed in the inventory
About the items being picked up twice, are you sure that they are added to the Items list twice? Or are the logs just being displayed twice?
Comment: Oh maybe I missed that part. I will try that! Thx.
About picking up twice: In the ItemManager I can see they are picked up twice because each item shows up in the list twice.
Comment: That is strange that the items are added twice. DId you get the items to show in the inventory?


How to reconcile record descriptions in single table

Question: I have a large table of data where part number descriptions were not entered consistently, now I need to figure out a way to reconcile them without using an update statement for each one, here is an example:
Part number Description
abcd1       red lamp
abcd1       red lamp w/ plug
abcd2       blue lamp
abcd2       blue lamp w/ plug
abcd3       green lamp
abcd3       green lamp w/ plug

How can I take the first description and insert it into all the subsequent records with the same part number? Actually it doesn't have to be the first so long as they can all be grouped into a single record. The records are sales orders of sorts, there is a date column which is why there are multiple records with the same part number. Thanks!
Comment: Unless you have some criteria to accurately and repeatedly select the same 'first' description, you are not going to be able to do this.  How are you defining the 'right' description in a generic way?
Comment: How come you are able to have different descriptions for the same partnumber ? Looks like bad table design to me. There should only be one description for each partnumber it looks like you are missing an entire table in your design
Comment: Are there any additional columns that help determine which description is "first"?  I'm guessing you ordered them that way in the example, but some sort of order number or key would help.
Comment: Perhaps editing the question to include the desired results table would help.
Comment: Is the desired result to have a new row for part number "abcd1" with the description "red lamp red lamp w/ plug"?
Comment: It's actually not imperative to use the first description I just thought that was the most logical, as long as they can all be grouped into a single record.
Comment: *as long as they can all be grouped into a single record*  --  Then why bother with the description at all?  Just aggregate on the part number?
Comment: Your problem is that your SalesOrder table is badly designed. There should be a table `Parts`that looks like `PartID int, Partnumber varchar(), Description varchar(), ...`and in your SalesOrder you should have just one field to link to a part, a field called PartID. This way you never have this problem again. Read up on `Normalization` because this design will keep giving problems
Comment: There is no such thing as a "first" description in a table, unless another column specifies the ordering.
Answer: Assuming you have a date or sequential id, you can use an updatable CTE:
with toupdate as (
      select t.*,
             first_value(description) over (partition by partnumber order by ?) as first_description
      from t
     )
update toupdate
    set description = first_description
    where description <> first_description;

However, you should really be focused on fixing the data model.  You should have a parts table, with one row per part and a description that is stored in exactly one place.  That would be the correct way to structure the data.
If descriptive information about the parts can change over time, then you make this a type-2 dimension, with an effective and end date.


Mysql - Update first row in table where a column has a null value

Question: I have a database with a list of API key. I need to associate an email and a name with these. I want my query to update the name and email on the first row that has null as the email.
id    key            name  email

'1', '3046GUGYi7ab', NULL, NULL
'2', 'TXQzL33HVp1W', NULL, NULL
'3', 'YIK6DAnTVU4n', NULL, NULL

My attempt is this, But apparently, you cant use the same table in a subquery.
UPDATE key_table
set email="email@example.com", `name`="test"
where id = (Select min(id) from key_table
            where email=null);

I'm sure there is a simpel soultion for this? Any ideas?
Answer:
My attempt is this, But apparently, you cant use the same table in a
  subquery.

UPDATE key_table
set email="email@example.com", `name`="test"
where id = (Select min(id) from key_table
            where email=null);

You need to wrap the inner query within a extra subquery if you use the same table name.
The query below should work.
Query
UPDATE
  key_table
SET
    email = "firstname.lastname@example.com"
  , name = "test"
WHERE
  id = (
        SELECT
          min_id
        FROM (
           SELECT
             MIN(id) AS min_id
           FROM
             key_table
           WHERE
             email IS NULL
        )
         AS key_table
      )

Answer: Try this
UPDATE key_table
SET email="email@example.com", `name`="test"
WHERE ID=1;

This will only affect the first row and change the value
Hope this helps


Rails 3.2, javascript executing twice

Question: I have a brand new rails app that has the following code:
application.js
//= require jquery
//= require jquery_ujs
//= require_tree .

thing.js (lives in same path as application.js)
alert("This is running");

index.html
<%= javascript_include_tag "application" %>

When I navigate to the page, I see the alert twice. Anyone know why? I have no pre-compiled assets.
Comment: Oh my god. I just spent HOURS pulling my hair out over this. Turned out that when I upgraded to rails 4, it added `= javascript_include_tag "application", 'data-turbolinks-track' => true` in addition to my original `= javascript_include_tag "application"`. Deleting my original and keeping the new turbolinks one saved the day.
Answer: the application layout already includes the application.js file, so this arises because the application.js is getting included twice.

Rails 3.2, javascript executing twice


Google Colab: mounted Drive but unable to read files

Question: I am doing Stanford's course CS231n on deep learning and am using Google Colab.
The initialization code and all the files are given, so all i need is just to hit "run" on the given code.
I have followed step be step the official instructions and successfully mounted Google Drive, yet i get an error when trying to read the files:
"cp: cannot stat 'cs231n/assignments/assignment1/cs231n/': No such file or directory /content".
And then some more errors.
The files are located in my drive as in the path "FOLDERNAME".
The errors i get:

How it should be:

Official instructions:
https://cs231n.github.io/assignments2020/assignment1/
How can i solve it?
Thanks!
Answer: I am having the exactly same problem as you were. And here is my solution:

delete the folder named cs231n
follow the tutorial again

3. change the path %cd drive/My\ Drive into %cd drive/MyDrive

As you can see, default setting of the folder is 'MyDrive'(without space in midddle) but not 'My Drive'(My\ Drive).

Then, everything should run as your expectation.
Cheers.
Answer: Based on the course instructions, it sounds like you need to expand the course archive in your Drive.
Quoting here:

Create a folder in your personal Google Drive and upload assignment1/
folder to the Drive folder. We recommend that you call the Google
Drive folder cs231n/assignments/ so that the final uploaded folder has
the path cs231n/assignments/assignment1/.

If you already did that, I'd check the Drive web UI to make sure that the paths line up with the course instructions, and to move the files around if there's a mismatch.