text:
Q: Pivot table from wide to long gives error in R I want to change the table format from wide to long. I got two dataframes. The first dataframe has 15 variables of interest and the second dataframe has 23 variables of interest. I tried to convert it to a dataframe with two or three columns (per 7 long columns to 1 wide column) with a timeframe of 1 to 7. If I do this for two variables the code works perfectly fine but when I add a third variable it gives an extra row per ID with the value NA. And I dont want to simply na.omit the dataframe because it will also delete missing data that was actually already in the data set. I will first show the dataframes of 15 and 23 columns respectively.
structure(list(ID = c("ID1", "ID10", "ID11", "ID12", "ID13"),
    AI_1 = c(0.393672183448241, 0.296109333767922, 0.31961673567578,
    0.520204263001733, 0.361215896677733), AI_2 = c(0.4876954603533,
    0.309960002123076, 0.227268892979164, 0.194175420670027,
    0.256393554215028), AI_3 = c(0.411717908455957, 0.445886231347992,
    0.433471105477564, 0.507417309543222, 0.429431082438377),
    AI_4 = c(0.309769862660288, 0.370013553008003, 0.207184572401005,
    0.1934679395598, NA), AI_5 = c(0.149826889496538, 0.393414429902431,
    0.144257239122978, 0.0831932654836405, NA), AI_6 = c(0.2448558592586,
    0.318940511323733, NA, 0.115391861884329, NA), AI_7 = c(0.123606753324621,
    0.131112361225666, NA, 0.141420940969022, NA), AI_VAR_1 = c(0.154977788020905,
    0.0876807375444826, 0.102154857724042, 0.270612475245176,
    0.130476924012699), AI_VAR_2 = c(0.237846862049217, 0.0960752029161373,
    0.0516511497159746, 0.0377040939923819, 0.0657376546430145
    ), AI_VAR_3 = c(0.169511636143347, 0.198814531305715, 0.187897199283942,
    0.257472326024082, 0.184411054564196), AI_VAR_4 = c(0.0959573678125739,
    0.136910029409606, 0.0429254470409874, 0.0374298436375145,
    NA), AI_VAR_5 = c(0.0224480968162077, 0.154774913655455,
    0.020810151039384, 0.00692111942183149, NA), AI_VAR_6 = c(0.0599543918132674,
    0.101723049763444, NA, 0.0133152817891321, NA), AI_VAR_7 = c(0.0152786294674538,
    0.0171904512661696, NA, 0.0199998825445637, NA)), row.names = c(NA,
5L), class = "data.frame")

structure(list(ID = c("ID1", "ID10", "ID11", "ID12", "ID13"),
    AI_1 = c(0.393672183448241, 0.296109333767922, 0.31961673567578,
    0.520204263001733, 0.361215896677733), AI_2 = c(0.4876954603533,
    0.309960002123076, 0.227268892979164, 0.194175420670027,
    0.256393554215028), AI_3 = c(0.411717908455957, 0.445886231347992,
    0.433471105477564, 0.507417309543222, 0.429431082438377),
    AI_4 = c(0.309769862660288, 0.370013553008003, 0.207184572401005,
    0.1934679395598, NA), AI_5 = c(0.149826889496538, 0.393414429902431,
    0.144257239122978, 0.0831932654836405, NA), AI_6 = c(0.2448558592586,
    0.318940511323733, NA, 0.115391861884329, NA), AI_7 = c(0.123606753324621,
    0.131112361225666, NA, 0.141420940969022, NA), AI_VAR_1 = c(0.154977788020905,
    0.0876807375444826, 0.102154857724042, 0.270612475245176,
    0.130476924012699), AI_VAR_2 = c(0.237846862049217, 0.0960752029161373,
    0.0516511497159746, 0.0377040939923819, 0.0657376546430145
    ), AI_VAR_3 = c(0.169511636143347, 0.198814531305715, 0.187897199283942,
    0.257472326024082, 0.184411054564196), AI_VAR_4 = c(0.0959573678125739,
    0.136910029409606, 0.0429254470409874, 0.0374298436375145,
    NA), AI_VAR_5 = c(0.0224480968162077, 0.154774913655455,
    0.020810151039384, 0.00692111942183149, NA), AI_VAR_6 = c(0.0599543918132674,
    0.101723049763444, NA, 0.0133152817891321, NA), AI_VAR_7 = c(0.0152786294674538,
    0.0171904512661696, NA, 0.0199998825445637, NA), x1.time = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_), activity1 = c(0,
    0.357638888888889, 0.448611111111111, 0.238888888888889,
    0.45625), activity2 = c(0.303472222222222, 0.235416666666667,
    0.213888888888889, 0.263888888888889, 0.239583333333333),
    activity3 = c(0.232638888888889, 0.233333333333333, 0.248611111111111,
    0.247916666666667, 0.335416666666667), activity4 = c(0.228472222222222,
    0.2875, 0.288888888888889, 0.315277777777778, NA), activity5 = c(0.348611111111111,
    0.353472222222222, 0.25625, 0.298611111111111, NA), activity6 = c(0.215972222222222,
    0.356944444444444, NA, 0.173611111111111, NA), activity7 = c(0.123611111111111,
    0.149305555555556, NA, 0.185416666666667, NA)), row.names = c(NA,
5L), class = "data.frame")

This is the code that I used for the two variables
df4 <- df %>%
  pivot_longer(-c(ID),
               names_to = c(".value", "Time"),
               names_pattern = "(AI|AI_VAR)_*(\\d)")

Then I obtain the following dataset
structure(list(ID = c("ID1", "ID1", "ID1", "ID1", "ID1", "ID1",
"ID1", "ID10", "ID10", "ID10", "ID10", "ID10", "ID10", "ID10",
"ID11", "ID11", "ID11", "ID11", "ID11", "ID11"), Time = c("1",
"2", "3", "4", "5", "6", "7", "1", "2", "3", "4", "5", "6", "7",
"1", "2", "3", "4", "5", "6"), AI = c(0.393672183448241, 0.4876954603533,
0.411717908455957, 0.309769862660288, 0.149826889496538, 0.2448558592586,
0.123606753324621, 0.296109333767922, 0.309960002123076, 0.445886231347992,
0.370013553008003, 0.393414429902431, 0.318940511323733, 0.131112361225666,
0.31961673567578, 0.227268892979164, 0.433471105477564, 0.207184572401005,
0.144257239122978, NA), AI_VAR = c(0.154977788020905, 0.237846862049217,
0.169511636143347, 0.0959573678125739, 0.0224480968162077, 0.0599543918132674,
0.0152786294674538, 0.0876807375444826, 0.0960752029161373, 0.198814531305715,
0.136910029409606, 0.154774913655455, 0.101723049763444, 0.0171904512661696,
0.102154857724042, 0.0516511497159746, 0.187897199283942, 0.0429254470409874,
0.020810151039384, NA)), row.names = c(NA, -20L), class = c("tbl_df",
"tbl", "data.frame"))

**And this is the code is use for the extra variable (activity)
df4 <- df3 %>%
  pivot_longer(-c(ID),
               names_to = c(".value", "Time"),
               names_pattern = "(AI|AI_VAR|activity)_*(\\d)")

Then I get the following dataframe:
structure(list(ID = c("ID1", "ID1", "ID1", "ID1", "ID1", "ID1",
"ID1", "ID1", "ID10", "ID10", "ID10", "ID10", "ID10", "ID10",
"ID10", "ID10", "ID11", "ID11", "ID11", "ID11"), Time = c("1",
"2", "3", "4", "5", "6", "7", NA, "1", "2", "3", "4", "5", "6",
"7", NA, "1", "2", "3", "4"), AI = c(0.393672183448241, 0.4876954603533,
0.411717908455957, 0.309769862660288, 0.149826889496538, 0.2448558592586,
0.123606753324621, NA, 0.296109333767922, 0.309960002123076,
0.445886231347992, 0.370013553008003, 0.393414429902431, 0.318940511323733,
0.131112361225666, NA, 0.31961673567578, 0.227268892979164, 0.433471105477564,
0.207184572401005), AI_VAR = c(0.154977788020905, 0.237846862049217,
0.169511636143347, 0.0959573678125739, 0.0224480968162077, 0.0599543918132674,
0.0152786294674538, NA, 0.0876807375444826, 0.0960752029161373,
0.198814531305715, 0.136910029409606, 0.154774913655455, 0.101723049763444,
0.0171904512661696, NA, 0.102154857724042, 0.0516511497159746,
0.187897199283942, 0.0429254470409874), activity = c(0, 0.303472222222222,
0.232638888888889, 0.228472222222222, 0.348611111111111, 0.215972222222222,
0.123611111111111, NA, 0.357638888888889, 0.235416666666667,
0.233333333333333, 0.2875, 0.353472222222222, 0.356944444444444,
0.149305555555556, NA, 0.448611111111111, 0.213888888888889,
0.248611111111111, 0.288888888888889)), row.names = c(NA, -20L
), class = c("tbl_df", "tbl", "data.frame"))

My question is: how can I change the code of pivot_longer where I can get rid of the extra NA value per ID

A: You could drop_na the rows based on the "Time" column like this:
library(dplyr)
library(tidyr)

df3 %>%
  pivot_longer(-c(ID),
               names_to = c(".value", "Time"),
               names_pattern = "(AI|AI_VAR|activity)_*(\\d)") %>%
  drop_na(Time)
#> # A tibble: 35 × 5
#>    ID    Time     AI AI_VAR activity
#>    <chr> <chr> <dbl>  <dbl>    <dbl>
#>  1 ID1   1     0.394 0.155     0
#>  2 ID1   2     0.488 0.238     0.303
#>  3 ID1   3     0.412 0.170     0.233
#>  4 ID1   4     0.310 0.0960    0.228
#>  5 ID1   5     0.150 0.0224    0.349
#>  6 ID1   6     0.245 0.0600    0.216
#>  7 ID1   7     0.124 0.0153    0.124
#>  8 ID10  1     0.296 0.0877    0.358
#>  9 ID10  2     0.310 0.0961    0.235
#> 10 ID10  3     0.446 0.199     0.233
#> # … with 25 more rows

Created on 2022-10-12 with reprex v2.0.2


text:
Q: Command-line to switch between profiles in gnome-terminal I created a new profile for gnome-terminal and I can switch between "Implicit" profile and the new created profile as you can see in the below image:

Now I wonder how can I switch between profiles using a command-line/script or maybe using a shortcut for this.

Note: Solutions like:
gnome-terminal --tab-with-profile=Implicit && exit

are excluded because I prefer not to close and open another terminal or get another terminal window in this process of changing the profile.

A: To switch to the "implicit" profile:
xdotool key Alt+t p Return

To switch to the second profile:
xdotool key Alt+t p Down Return

xdotool  is not installed by default in Ubuntu, so it must to be installed first.
Of course, for these commands can be added custom keyboard shortcuts.

A: There is no shortcut that allows you to change the profile within the terminal (without navigating the menus as you said in comments), without the use of the GUI. Quoting the manual (stable, development 3.9):

You can change the profile in your current Terminal tab or window by selecting a profile from Terminal ▸ Change Profile.

(You can propose this as suggestion in the bug tracker)

A: I was looking to do the same and finally got a script working, I put it up on my GitHub.
Like I explain in the README.md, it doesn't actually switch, but loads a profiles configuration into the Default profile. To do this, the configuration of each profile is saved to file on the first run of the script.
The script makes it seem like you're switching between profiles, which is good enough for me. Hope it helps anyone...

A: Depending on your purpose, you may find this script to be useful:
https://github.com/xyrix/gnome-terminal-profile-switcher
It does a sort of monkey patch and generates a new profile for each terminal, then sets some environment variables to expose a program for switching the theme of the profile for your current terminal.
Hopefully the example safe_ssh script will make things clear :-). I've been using it for just over a year now and it's helped me not destroy the company's live database ^_^

A: If you have a list of servers that you access often, I believe the easiest solution would be to simply invoke a second window just for that box's session.
First, make a separate gnome-terminal profile for each remote location that you use often. Then, in each profile, specify that the terminal should execute the SSH login command for that box, instead of a plain shell.
ssh alice@athena

Finally, write a short script to kick off a new remote window given a profile ID.
#!/bin/bash
if [[ $# -ne 1 ]] ; then
  echo "Give me a server/profile name!"
  exit 1
fi
gnome-terminal --window-with-profile=$1
exit 0

Using this strategy you can "infinitely" vary the look of each box's terminal window, and kick them off from a single "control" terminal. For example, if we call this script "rlv", then we can spawn a remote window by simply invoking the script with a profile name.
>> rlv athena

If you ever fat-finger a host name, or neglect to set up a profile for that host, then you'll just get another default-profile window on the local box. There's a way to code the script to avoid this, by putting the login into the script itself, rather than in the gnome-terminal :
#!/bin/bash
if [[ $# -ne 1 ]] ; then
  echo "Give me a server/profile name!"
  exit 1
fi
gnome-terminal --window-with-profile=$1 -e "ssh $1"
exit 0

...but then you lose the flexibility of defining your login username for that box. That additional feature of the script I leave as an exercise to the reader.

A: A lot of great answers already but I wanted to add one more variation using xdotool that does not require the menu bar to be visible...
The key combo shift+F10 will open a pop-up menu (the equivalent of right-clicking on terminal) and from there the profile can be changed.
e.g. xdotool key shift+F10 r 3 to get to the third profile
I've also found that this method does not require setting a delay for xdotool (which I found necessary for the menu bar method) so it's therefore a little faster.
I tend to change profiles a lot so I wrap this into a function:
function chp(){
      xdotool key --clearmodifiers Shift+F10 r $1
}

so I can just call chp N to switch to the Nth profile.
Some more tips and idiosyncrasies of my setup:

*

*By adding a chp command to my .bashrc I can force new tabs to always switch to the default profile

*I color code my ssh sessions based on host but I don't like my ssh alias to open new tabs or windows AND I want the profile to change back to the default when I exit ssh.  My solution:
      alias somehost="chp 2; ssh user@somehost; chp 1"

*I give xdotool the flag --clearmodifiers so that if I happen to be holding a modifier key (when opening a tab/window, exiting ssh, etc.), it won't interfere with xdotool.

*I prepend my profile names with numbers so that if I add a new one, it doesn't shift all the others due to the alphabetizing of the profile menu

A: I've just noticed that my original solution has been already rejected in the question. While there seems no simple way to change the profile, you can change background / foreground color by using setterm command.
So, this setterm -term linux -background black -foreground green would give you black background with green text. The only problem is that ls has colorized output, so you might wanna turn ls coloring off. Otherwise it resets to previous color scheme
Original post: There is a sort-of way around. From man gnome-terminal :

--window-with-profile=PROFILENAME
             Open a new window containing a  tab  with  the
             given profile.  More than one of these options
             can be provided.

Here's example from my machine. I have three profiles: B&G(black on green), ForPrinting(black font, white background), and Default. So what I do is in current window type gnome-terminal --window-with-profile=ForPrinting . Then I can either kill old window from command line or switch and close it graphically.
B&G profile doesn't work. Probably because & is not a valid character, so keep that in mind when naming profiles.

A: It would be great of gnome-terminal offered a "next profile" command and shortcut; unfortunately, it does not.
A workaround for those with Alt+T disabled (Edit > Preferences > Enable mnemonics - unchecked) is: F10 left left down right and select the profile. Ouch.

A: Even though the question is about GNOME Terminal and the command line, it's worth knowing that MATE Terminal (a GNOME Terminal fork) allows profile switching via a simple keyboard shortcut.

A: The very ugly solution I've ended up using is
unset x y
eval $(xwininfo -id $(xdotool getactivewindow) |
       sed -n -e 's/^ \+Absolute upper-left X: \+\([0-9]\+\).*/x=\1/p' \
              -e 's/^ \+Absolute upper-left Y: \+\([0-9]\+\).*/y=\1/p')
xdotool mousemove $(($x + 50)) $(($y + 50))
xdotool click 3; xdotool key --repeat 3 Up; xdotool key Right; xdotool key --delay 50 Down; xdotool key --delay 50 Return

(This selects the second profile, but you could change that to say the htir profile by changing the second "key Down" command to xdotool key --delay 50 --repeat 2 Down.
What's this doing:

*

*find the the top left coordinates of the current window (eg. the gnome terminal in use).

*move the mouse to be over that terminal

*right click and navigate the context menu to select the second profile.

You'll need xdotool installed sudo apt install xdotool.
Kind of extraordinary that the terminal itself doesn't doesn't allow configuration via the terminal!

A: This is a rather old post, but because it kept coming up while I was searching to solve this same issue, I thought I would post my solution.
This involves a small python script and remapping the CTRL+ALT+T button to run the script instead of simply launching the terminal.
Create a text file, I named mine terminal.py and make sure it is executible. Place the following code in it. This will open the terminal windows using all available profiles in sequence making sure that the one marked "default" is the first in the list.
#!/usr/bin/python
#
# Launch a gnome-terminal window trying to assign each new window
# to a different profile.
#
import json
import os
import commands

profiles=[]

try:
    profileList = commands.getoutput("gsettings get org.gnome.Terminal.ProfilesList list").replace("'",'"')
    profileDefault = commands.getoutput("gsettings get org.gnome.Terminal.ProfilesList default").replace("'",'"')

    profiles.append(json.loads(profileDefault))
    ls = json.loads(profileList)
    ls.remove(profiles[0])
    profiles+=ls

    # find the next available terminal number
    # when terminals are closed, gaps in the numbers can happen
    # terminals are numeric and the lowest slot is filled first
    terminals = commands.getoutput("ls /dev/pts/  | grep -E '^[0-9]+$'").split("\n")
    next = 0
    try:
        while terminals.index(str(next))>=0:
            next += 1
    except:
        pass

    # determine the profile to use
    prof = next % len(profiles)

    # launch the terminal with the specific profile
    cmd="gnome-terminal --window-with-profile='%s'" % (profiles[prof])
    os.system(cmd)
except:
    # if anything fails, launch a default terminal
    print("error")
    os.system("gnome-terminal")

Use the keyboard settings utility to assign a new shortcut to this script. For me I reassigned CTRL+ALT+T because that is the shortcut I am use to for opening a terminal window.
Be sure to create several profiles in your terminal. This script will make use of all of your profiles. So the more you create, the more variations on windows you can get access too. I have several that are all identical except for the background color. This helps me recognize them as I alt-tab through them.

A: How to have a different color scheme in each new Terminal Window
The accepted answer using xdotool works, but introduces bugs. Here's a cleaner way.
First the explanation, then the code.
Explanation

*

*There is a way to create a new terminal window with the specified profile if you know the UUID.
gnome-terminal --profile='7e95bbb3-a584-469d-8ae1-75a08287f55a'

So if we can inject this command in some way, we're done. We'd like this to happen in all these cases:

*

*when we open the terminal using a shortcut CtrlAltT

*when we open the terminal using the icon in the taskbar

*when we open the terminal using the search

*The gnome-terminal resides in /usr/bin/gnome-terminal and might be updated by the distro.

/usr/local/bin is for normal user programs not managed by the distribution package manager, e.g. locally compiled packages. You should not install them into /usr/bin because future distribution upgrades may modify or delete them without warning.
Source

*The $PATH checks /usr/local/bin before /usr/local:
$ echo $PATH
/home/generic/miniconda3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

So we can create a file /usr/local/bin/gnome-terminal which will take precedence. If we ever need to circumvent our version, we'd have to use the full path to the original /usr/bin/gnome-terminal.

*Create that file and paste the code below. Then make it executable with sudo chmod +x /usr/local/bin/gnome-terminal.
Code
#!/bin/bash
set -euo pipefail
# get list of possible profiles, then choose one line at random
line="$(dconf list /org/gnome/terminal/legacy/profiles:/ | grep -e '^:' | shuf -n 1)"
# then remove the leading colon and trailing slash
line="${line#:}"
line="${line%/}"
#/usr/bin/gnome-terminal --profile='7e95bbb3-a584-469d-8ae1-75a08287f55a'
# but also pass all arguments. The profile chosen will always be the last one if there are multiple arguments, so we allow the input to override our setting.
/usr/bin/gnome-terminal --profile="$line" "$@"

Example Looks
I'm using some profiles from https://mayccoll.github.io/Gogh/

Maybe you could also use update-alternatives as a similar alternative approach. I have not tested that.

A: Actually gnome-terminal's --tab-with-profile can be useful if used right.
In .bashrc set something like:
if [ -z "${choose_term_profile}" ]; then
  if [ -z "${SSH_TTY}" ]; then   #is not from ssh
    #      ${SSH_CONNECTION} , ${SSH_CLIENT}
    if [ "`xtermcontrol --get-bg`" = "rgb:ffff/ffff/ffff" ]; then
      #if php date_sun_info sunset/sunrise
      choose_term_profile=1 gnome-terminal --tab-with-profile=black && exit
    fi
  fi
fi

To change without new tab, but have to be like typing, on Wayland:
sudo ydotool key shift+F10
#if it is not root (sudo) it may be "Aborted (core dumped)"
sleep 1; sudo ydotool key r
sleep 1; sudo ydotool key 2
#                      or 1 for first profile

xdotool has the same syntax.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jetty: default servlet context path I need to set Servlet (only servlet not handler because of some reasons) to work with files outside war. Here https://stackoverflow.com/a/28735121/5057736 I found the following solution:
Server server = new Server(8080);

ServletContextHandler ctx = new ServletContextHandler();
ctx.setContextPath("/");

DefaultServlet defaultServlet = new DefaultServlet();
ServletHolder holderPwd = new ServletHolder("default", defaultServlet);
holderPwd.setInitParameter("resourceBase", "./src/webapp/");

ctx.addServlet(holderPwd, "/*");//LINE N
ctx.addServlet(InfoServiceSocketServlet.class, "/info");

server.setHandler(ctx);

This solutions works and this is what I need. However, it stops working as soon as I change LINE N to ctx.addServlet(holderPwd, "/foo/*");. I tried "/foo/","/foo" but result is the same - I get not found. Why? How can I make it work with this certain context? I use jetty 9.2.15 because of the same reasons.

A: The DefaultServlet is designed to look at the request URI after the contextPath.
In your example code when you changed the url-pattern of your servlet from / to /foo/* the resulting file being looked for on disk is now includes the /foo/ portion.
In other words, a request URI of /css/main.css results in the file (on disk) it expects to find as ./src/webapp/foo/css/main.css
Your example has a few flaws.  It's not a wise have an empty resource base for your ServletContextHandler, as the ServletContext itself needs access to that configuration value.
You would fix that by removing ...
holderPwd.setInitParameter("resourceBase", "./src/webapp/");

and using ServletContextHandler.setBaseResource(Resource) instead ...
ctx.setResourceBase(Resource.newResource(new File("./src/webapp")));

This will allow the following ServletContext methods (used by countless servlet libraries) to work as well

*

*String getRealPath(String path)

*URL getResource(String path)

*InputStream getResourceAsStream(String path)

*Set<String> getResources(String path)
Finally, to make this setup sane in the ServletContextHandler, you'll add the default Servlet name, on the "default url-pattern", which happens to be implemented as the DefaultServlet.
Like this:
// Lastly, the default servlet for root content
// It is important that this is added last.
String defName = "default"; // the important "default" name
ServletHolder holderDef = new ServletHolder(defName, DefaultServlet.class);
holderDef.setInitParameter("dirAllowed","true");
ctx.addServlet(holderDef,"/"); // the servlet spec "default url-pattern"

Now, if you also have a need to serve static content from request URI /foo/* out of a directory not belonging to the webapp, you can do that too.
That will require you to setup another DefaultServlet that does not participate in the ServletContext.
An example of this setup is ...
package jetty;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.resource.PathResource;

import java.io.File;
import java.nio.file.Path;

public class ManyDefaultServlet
{
    public static void main(String[] args) throws Exception {
        Server server = new Server();
        ServerConnector connector = new ServerConnector(server);
        connector.setPort(8080);
        server.addConnector(connector);

        // The filesystem paths we will map
        Path homePath = new File(System.getProperty("user.home")).toPath().toRealPath();
        Path pwdPath = new File(System.getProperty("user.dir")).toPath().toRealPath();

        // Setup the basic application "context" for this application at "/"
        // This is also known as the handler tree (in jetty speak)
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        context.setBaseResource(new PathResource(pwdPath));
        server.setHandler(context);

        // Fist, add special pathspec of "/home/" content mapped to the homePath
        ServletHolder holderHome = new ServletHolder("static-home", DefaultServlet.class);
        holderHome.setInitParameter("resourceBase",homePath.toUri().toASCIIString());
        holderHome.setInitParameter("dirAllowed","true");
        // Use request pathInfo, don't calculate from contextPath
        holderHome.setInitParameter("pathInfoOnly","true");
        context.addServlet(holderHome,"/foo/*"); // must end in "/*" for pathInfo to work

        // Lastly, the default servlet for root content
        // It is important that this is last.
        String defName = "default"; // the important "default" name
        ServletHolder holderDef = new ServletHolder(defName, DefaultServlet.class);
        holderDef.setInitParameter("dirAllowed","true");
        context.addServlet(holderDef,"/"); // the servlet spec "default url-pattern"

        server.start();
        server.join();
    }
}

This uses a second DefaultServlet, using a unique resource base for that DefaultServlet only, and mapped to a url-pattern that ends in /*.
Finally, the init-parameter for this second DefaultServlet is told to use the pathInfo of the Request URI and not split on the contextPath like it normally does.

For more information on what this whole pathInfo, request URI, contextPath, and url-patterns ending in /* are all about, see the useful answer by @30thh

This stand alone DefaultServlet declaration does not participate in the ServletContext and libraries will not be able to see or access the content from that DefaultServlet via the ServletContext methods.  However all incoming HTTP client requests can request the content easily via that url-pattern.


text:
Q: Linked linked destructor raises segmentation fault I am trying to delete a linked list using the destructor.
But this code is giving a segmentation fault:
~Node()
{
    Node *current = this ;
    Node *previous = NULL;
    while(current != NULL)
    {
        previous = current;
        current = current->next;
        delete previous;
        previous = NULL;
    }
}

What am I doing wrong here?

A: You may not delete the current node itself because otherwise the code invokes undefined behavior.
Instead you could write
~Node()
{
    delete next;
}

And if the list is defined as a pointer to the head node then you need to write
delete head;

Here is a demonstration program
#include <iostream>

class Node
{
private:
    int data;
    Node *next;

public:

    explicit Node( int data, Node *next = nullptr ) : data( data ), next( next )
    {
    }

    ~Node()
    {
        std::cout << "Deleting " << data << "...\n";
        delete next;
    }
};

void push_front( Node *&head, int data )
{
    head = new Node( data, head );
}

int main()
{
    Node *head = nullptr;
    const int N = 10;

    for (int i = 0; i < N; i++)
    {
        push_front( head, N - i );
    }

    delete head;
}

The program output is
Deleting 1...
Deleting 2...
Deleting 3...
Deleting 4...
Deleting 5...
Deleting 6...
Deleting 7...
Deleting 8...
Deleting 9...
Deleting 10...

A: You should exclude the current node from the delete operator, as the code is already a response to such a delete. Doing it again is like running in circles.
So modify your code to this:
~Node()
{
    Node *current = this->next; // exclude current node
    Node *previous;

    while (current != NULL)
    {
        previous = current;
        current = current->next;
        previous->next = NULL; // avoid the delete below to propagate through list.
        delete previous;
    }
}

There is no need to set previous to NULL, since it will run out of scope. But it is needed to detach previous from its successors, so to avoid the the destructor will follow that chain again.
This code assumes that this is the first node of the list, which would be the natural thing to execute delete on. If for some reason you would execute delete on a node somewhere in the middle of a list, with the aim to discard the whole list, then you would need to repeat the above loop also for the nodes that precede the current node.


text:
Q: Why does this code yield an error with regards to the pow function? #include <stdio.h>
#include <math.h>
int exp_for_level(int n) {
    return (int)(100 * pow(n, 2.3));
}

int main(){
    int x;
    x = exp_for_level(6);
    printf("%d", x);
    return 0;
}

I receive the following error when I run this code on an online compiler
/tmp/cc28S7ML.o: In function exp_for_level':
main.c:(.text+0x19): undefined reference to `pow'
collect2: error: ld returned 1 exit status

How do I rectify this?
After I couldn't get it to work on the online compiler, I followed advice from some other threads on
The file is stored under a file grades.c on my mac
I've tried entering this
$ gcc - Wall - lm -o grades grade . c

into my terminal and i just get zsh error: command not found
Any ideas on what the issue is here too?
The online compiler I'm using is
https://www.tutorialspoint.com/compile_c_online.php
EDIT: in my post, in main I'd miswritten the function as exp_to_level instead of exp_for_level. Didn't copy paste the entire code as it's too long. I narrowed it down and retyped it to the portion that yields the error.

A: There are some errors in your code, you have defined a function exp_for_level but you use exp_to_level.
Then your x variable is not defined
If you fix your code like this:
#include <stdio.h>
#include <math.h>
int exp_for_level(int n) {
    return (int)(100 * pow(n, 2.3));
}

int main(){
    int x = exp_for_level(6);
    printf("%d", x);
    return 0;
}

and you compile:
gcc -Wall powtest.c -o powtest -lm

it works.
About the error on the online compiler:
The undefined reference error occurs because you are missing -lm linker option.
Edit the online compiler command clicking on Project->Compile Options:

About this problem on your local machine:

After I couldn't get it to work on the online compiler, I followed
  advice from some other threads on The file is stored under a file
  grades.c on my mac I've tried entering this
$ gcc - Wall - lm -o grades grade . c

into my terminal and i just get zsh error: command not found

you don't have the compiler installed.
You should install clang, Have a look to this question

A: First of all your function name is wrong in the main take a look here exp_for_level
 and in main its exp_to_level change one of them then also add int x in main to solve the issue.


text:
Q: _tkinter.TclError: unkown option "-bd" I have the following two files:
main.py

    import tkinter as tk
    import hashlib, json
    from tkml import element
    f = open("users.json", "r")
    users = json.loads(f.read())
    f.close()
    f = open("users.json", "w")

    window = tk.Tk()
    window.title("Hello wold")
    window.geometry("600x800")
    pages = {}#initialize this variable
    currentPage = ""#initialize this variable
    def goTo(pageName):
        global pages, currentPage
        pages[currentPage].unloads()
        pages[pageName].load(window)
        currentPage = pageName
    pages = {
        "SignInOrCreateAccount": element(tk.Frame(),
                                         [
                                             element(tk.Button(text = "sign in", command = lambda : goTo("SignIn")), [], lambda widget, parent : widget.place(parent, anchor = "NW", relx = 0, rely = 0, x = 30, y = 30)),
                                             element(tk.Button(text = "create account", command = lambda : goTo("CreateAccount")), [], lambda widget, parent : widget.place(parent, anchor = "NE", relx = 0, rely = 0, x = 30, y = 30))
                                         ], lambda widget, parent: widget.place(parent, relx = 0, rely = 0, relwidth = 1, relheight = 1))
    }
    currentPage = "SignInOrCreateAccount"
    pages[currentPage].loads(window)
    def saveUsersChanges():
        global f, users
        json.dump(users, f)
    def attemptSignIn(username, password):
        if username in users:
            if hashlib.sha256(password.encode()).hexdigest() == users[username]["password"]:
                pass # left off here
    def onClose():
        global f
        saveUsersChanges()
        f.close()
    window.protocol("WM_DELETE_WINDOW", onClose())
    tk.mainloop()

and tkml.py

    class element:
        def __init__(self, widget , children, load, unload = lambda widget: widget.place_forget()):
            self.widget = widget # the tk widget
            self.load = load # load just this widget using lambda function
            self.unload = unload
            self.children = children # child widgets
        def loads(self, parent): # load this widget and all child widgets
            self.load(self.widget, parent)
            for child in self.children:
                child.loads(self)
        def unloads(self): # unloads widget and all child widgets
            self.unload(self.widget)
            for child in self.children:
                child.unloads()

when I attempt to run it I get a very long error:

    Traceback (most recent call last):
      File "main.py", line 27, in <module>
        pages[currentPage].loads(window)
    _cnfmerge: fallback due to: 'element' object is not iterable
    Traceback (most recent call last):
      File "/usr/lib/python3.8/tkinter/__init__.py", line 111, in _cnfmerge
        cnf.update(c)
    TypeError: 'element' object is not iterable

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "main.py", line 27, in <module>
        pages[currentPage].loads(None)
      File "/home/runner/Phoebe-Hacking-Puzzle/tkml.py", line 10, in loads
        child.loads(self)
      File "/home/runner/Phoebe-Hacking-Puzzle/tkml.py", line 8, in loads
        self.load(self.widget, parent)
    _cnfmerge: fallback due to: 'element' object is not iterable
    Traceback (most recent call last):
      File "/usr/lib/python3.8/tkinter/__init__.py", line 111, in _cnfmerge
        cnf.update(c)
    TypeError: 'element' object is not iterable

    During handling of the above exception, another exception occurred:

        Traceback (most recent call last):
          File "main.py", line 27, in <module>
            pages[currentPage].loads(window)
          File "/home/runner/Phoebe-Hacking-Puzzle/tkml.py", line 10, in loads
            child.loads(self)
          File "/home/runner/Phoebe-Hacking-Puzzle/tkml.py", line 8, in loads
            self.load(self.widget, parent)
        Traceback (most recent call last):
          File "main.py", line 27, in <module>
            pages[currentPage].loads(window)
          File "/home/runner/Phoebe-Hacking-Puzzle/tkml.py", line 8, in loads
            self.load(self.widget, parent)
          File "main.py", line 24, in <lambda>
            ], lambda widget, parent: widget.place(parent, relx = 0, rely = 0, relwidth = 1, relheight = 1))
          File "/usr/lib/python3.8/tkinter/__init__.py", line 2439, in place_configure
            self.tk.call(
        _tkinter.TclError: unknown option "-bd"

I have tried debugging by wading into tkinter's source code and while I have successfully tracked down the line of code that the error comes from, I have no idea where this -bd has come from or what it means. I am new to tkinter, always having used pygame in the past, so there is a good chance I am simply using a function wrong, I would appreciate any help anyone can provide.
PS: I am running my code off repl.it if that makes any difference.


text:
Q: Django prefetch_related ValueError Can't make prefetch_related to work.
These are models:
class Document(models.Model):
    document_type = models.CharField(max_length=1, choices=DOCUMENT_TYPE)
    document_id = models.PositiveIntegerField()
    branch = models.ForeignKey(Branch)

class OrderManager(models.Manager):

    def get_queryset(self):
        qs = super(OrderManager, self).get_queryset()
        return qs.filter(document_type=DOCUMENT_ORDER)

class Order(Document):

    objects = OrderManager()

    @property
    def items(self):
        return OrderItem.objects.filter(document=self)

    class Meta:
        proxy = True

class OrderItem(Item):

    objects = OrderItemManager()

class Item(models.Model):
    document = models.ForeignKey(Document, related_name='items')

Now when call:
Order.objects.all().prefetch_related('items')

error:
ValueError: 'items' does not resolve to an item that supports prefetching - this is an invalid parameter to prefetch_related().

items is in related_name, why i get this error?
Order is proxy model.
EDIT:
When do this:
Document.objects.all().prefetch_related('items')

it works.
Need solution to make it work from Order model.


text:
Q: EF: When executing a command, parameters must be exclusively database parameters or values When executing stored procedure without return value but with a user-defined table type like this:
var dbStrings = new SqlParameter("@data", SqlDbType.Structured)
{
    TypeName = new StringListType().Name,
    Value = new StringListType().DataRecordsFrom(listOfStrings.Select(p => p.Value).ToList())
 };
_dbContext.Database.ExecuteSqlCommand("exec [dbo].[InsertRecords] @SID, @filerType, @data", sid.ToString(), "Field", dbStrings);

I get an error

When executing a command, parameters must be exclusively database parameters or values

How can I execute stored procedure through DbContext with multiple input parameters (some UDTT)?

A: In this case you need to (as error message tells you) create an array of SqlParameter and pass this when calling ExecuteSqlCommand.
var sqlParams = new SqlParameter[]
{
    new SqlParameter("@SID", sid.ToString()),
    new SqlParameter("@filterType", "Pin"),
    new SqlParameter("@data", SqlDbType.Structured)
    {
        TypeName = new StringListType().Name,
        Value = new StringListType().DataRecordsFrom(listOfStrings.Select(p => p.Value).ToList())
    }
};

_dbContext.Database.ExecuteSqlCommand("exec [dbo].[InsertRecords] @SID, @filterType, @data", sqlParams);


text:
Q: Are bots different from crawlers from python Django point of view Actually i am confused with the terminology. I am studying the scrapy and i think its for crawling the website and extract some data.
But i want to make some python programs which does something like the actual users does. I mean like automating tasks.
E,g Go to www.myblah.com and then get the cheapest product in some category and if that is less than my preset amount , then send me email.
Now i dont know whether these type of things come under crawling or something else.
Can i do that in scrapy or we have other libraries for doing those kind of tasks.

A: Scrapy is framework that can be used to create a bot or a crawler (aka spider).  A crawler is specific kind of bot, but a bot isn't necessarily a crawler.  Crawlers are defined by being designed to explore the graph of pages (nodes) and their embedded URLs (edges) although they may be restricted from following particular URLs.
Automating tasks is the work of a bot.  Whether Scrapy will work for that will depend on what information is needed and how actions have to be taken.  Many sites are heavy on javascript these days, so if the bot can't execute javascript and correctly provide cookies it may not be able to get the information to it's task.  Some web automation tasks may require a browser plug-in or even GUI automation tools may be needed.


text:
Q: 'without' in tag question! I'm having a difficult time dealing with the word 'without' in the sentence below:
He passed the exam without your help, ... he?
Please help me clarify which will be the best fit in this context - 'did' or 'didn't'? (as I notice that 'without' has negative meaning).

A: I am new to this but this is what I think:
If I expand the question, it'd be:
He DID pass the exam without your help, _______ he?
Moreover, without your help this is not a verb which means that it cannot be used, (IDK I am just a Primary 6 pupil) hence, it is didn't he. In addition, grammatically, you cannot add DID before without your help. Hence, it grammatically does not make sense if you put 'did he'. Without your help is a piece of additional information so yeah...

A: If without is an adverb, I (a native speaker) would treat it as giving the sentence a negative meaning. For example, I would use did he in the sentence:

He made do without, did he?

I am not at all sure that other native speakers would agree with me.
But if without is a preposition, it doesn't make a sentence negative. So for your question, the tag is:

He passed the exam without your help, didn't he?

A: It is better to use didn't he?
We usually use question tags to ask someone to agree with our statement. In this case we use positive statement + negative tag or negative statement + positive tag.
He passed the exam without your help, didn't he?
Never, rarely, seldom, hardly, scarcely etc. have negative meanings. The statements with these adverbs are negative ones. So the question tags are positive. He seldom comes here, does he?
Sometimes we can use positive statement + positive tag when we don't know if the answer is 'yes' or 'no'. In this case the sentence should be 'He passed the exam without your help, did he?
You can visit https://www.youtube.com/watch?v=0g8LD4zA4ZI


text:
Q: Using AFNetworking for Web Service data retrieval Learning steeply on this one so I'd say it's 99% my mistake somewhere.
Trying a simple procedure for my first app.
I want to get data from the web service and output something to a label.
I'm a .NET developer so web service has been done and returns JSON data as expected in a browser.
{"GetVenuesForBrandResult":[{"brandID":0,"createdDate":"/Date(-62135596800000+0000)/","venueID":2,"venueName":"HMV Records"}]}
After looking at SO, decided to use AFNetworking, version 2.0, loaded as a pod.
So everything works in terms of getting the data but 2 questions please;
1) the output view in Xcode shows data thus;
GetVenuesForBrandResult=({brandID = 0;createdDate = "/Date(-62135596800000+0000)/";venueID = 2;venueName = "HMV Records";
    }
    );
Is this just XCode5 formatting for display purposes? And will my data be json in real terms?
2) How do I consume this?
Tried checking for isKindOfClass to be an nsarray or nsdictionary and these if conditions are never met. Which led me to suspect Q1 is the issue.
Your help to an Xcode newbie is appreciated.

as per Paul's excellent hint, the relevant part of my code is here;
the web service link is hard coded for now for test purposes
NSString *urlstring =     @"http://hiddenurl/shopBeaconService/Service1.svc/GetVenuesForBra nd/1";
        //NSString *str2 = self.email.text;
        //NSString *str3 = @"/";
        //NSString *str4 = [self.password text];
        //NSString *urlstring = [NSString stringWithFormat:@"%@%@%@%@",str1,str2,str3,str4];

        NSURL *url = [NSURL URLWithString:urlstring];

        NSURLRequest *request = [NSURLRequest requestWithURL:url];

        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        operation.responseSerializer = [AFJSONResponseSerializer serializer];
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,id responseObject)
         {
             NSLog(@"%@",responseObject);

            // NSDictionary *item = [responseObject objectForKey:@""];
            // NSString *title = [item objectForKey:@"venueName"];

             //NSLog(@"venue= %@",title);
         } failure:nil];

        [operation start];

A: The response object when you use the AFJSONResponseSerializer is an NSDictionary.  What you are seeing in your log is the output from [responseObject description]  - a method that prints a description for logging purposes.
Ray Wenderlich has a good tutorial on AFNetworking


text:
Q: XSD how to select more than one enumeration value I'm very new with xml schemas.
I want to select more than one enumeration value but it doesnt work. I tried to add xs: list but that didn't work too.
Here is an extract from my xsd:
 <xs:element name="charakter">
                            <xs:complexType>
                                <xs:simpleContent>
                                    <xs:extension base="xs:string">
                                        <xs:attribute name="haltung" use="required">
                                            <xs:simpleType>
                                                   <xs:restriction base="xs:string">
                                                             <xs:enumeration value="hoher Pflegeaufwand"/>
                                                             <xs:enumeration value="ideal für Garten"/>
                                                             <xs:enumeration value="ideal für Wohnungshaltung"/>
                                                             <xs:enumeration value="hoher Bewegungsbedarf"/>
                                                        </xs:restriction>
                                            </xs:simpleType>
                                        </xs:attribute>
                                    </xs:extension>
                                </xs:simpleContent>
                            </xs:complexType>

                        </xs:element>

So how is it possible to select more than one value?
Thanx for your reply.

A: Your desire to validate comma-separated strings in an attribute conflicts with xs:list requirement that its values be space-separated.
You might try using regular expressions to achieve your goal, but better would be to redesign your XML so that haltung is not an attribute but rather an element with child elements.


text:
Q: What are bounded equations? The question for my practice final is "Decide whether the set of points in $\mathbb{R}^3$ described by the equation $x^2+y^2-z^2=1$ is bounded or not."
To be honest, I do not know what bounded means in this case so it would be helpful if someone can describe what it means to be bounded.

A: The points $(1,n,n),n=1,2,\cdots$ are all in the solution set. Since this sequence is unbounded, the set of solutions is unbounded.

A:
A subset $S\subseteq\mathbb R^3$ is bounded if it is contained in a ball with finite radius; that is, if there exists an $\mathbf x\in\mathbb R^3$ and $r\in\mathbb R_{> 0}$ so that for all $\mathbf y\in S$, we have $|\mathbf x-\mathbf y|< r$.

In this question, our set $S$ is given by $$S=\{(x,y,z)\in\mathbb R^3\mid x^2+y^2-z^2=1\}\subset\mathbb R^3.$$
Now the question is whether we could find an $\mathbb x\in\mathbb R^3$ and $r\in\mathbb R_{>0}$ so that the condition in the definition is fulfilled. Consider what it would mean if the condition were true. For one thing, it would imply that the set cannot have points with infinitely big $z$ values. But, for any $z\in\mathbb R$, the point $(1,z,z)$ always lies in the set! This means that $z$ can actually grow arbitrarily large. Do you see where we get a contradiction here?

Here's an image of the required set (generated by Mathematica), for $-5\leq x,y\leq 5$. For $S$ to be bounded, we need there to be a ball of finite radius containing this set. Intuitively, you should see easily that this is impossible.


text:
Q: List of links split into columns I'm fetching links with an ajax call and the content is dynamic.
I want to make the links flow: top to bottom for 10 links and into a new column for an other 10 links etc..
I need something that would look like this: http://jsfiddle.net/89JKM/18/, but that would work cross-browser. Also if the number or links was for example 15 then the first columns of 10 should fill up before it fills up the second colums with 5 and leave the last column empty. I believe that a jQuery script would do the trick or if there is some cool CSS-magic.

A: Well, here's one approach:
function cssSupportFor(prop) {
    if (!prop) {
        // you have to supply a property to test
        return false;
    }
    else {
        var styles = document.body.style;

        // testing for native support:
        if (prop in styles) {
            // returns the property
            return prop;
        }
        else {
            // tests for vendor-prefixed support:
            var vendors = ['Moz', 'Webkit', 'Ms', 'O'],
                // upper-cases the first letter of the property for camel-casing
                Prop = prop[0].toUpperCase() + prop.substring(1);
            for (var i = 0, len = vendors.length; i < len; i++) {
                if ((vendors[i] + Prop) in styles) {
                    // returns the vendor-prefixed property
                    return vendors[i] + Prop;
                }
                else if (i == (vendors.length - 1)) {
                    // if no vendor-prefixed support, or native support, returns false
                    return false;
                }
            }
        }
    }
}

// if there's support for the tested property then it's implemented here
if (cssSupportFor('columnCount')) {
    var prop = cssSupportFor('columnCount');
    $('#linklist')[0].style[prop] = 3;
}
// otherwise the following jQuery kicks in to achieve much the same
else {
    var aElems = $('#linklist a'),
        cols = Math.ceil(aElems.length / 10);

    for (var i = 0, len = cols; i < cols; i++) {
        var d = $('<div />', {
            'class': 'col'
        }).appendTo('#linklist');
        $('#linklist > a:lt(10)').appendTo(d);
    }
}

JS Fiddle demo.
References:

*

*jQuery:

*

*appendTo().

*:lt() less-than selector.

*'Plain'/native JavaScript (all from the Mozilla Developer Network):

*

*CSSStyle declaration.

*element.style.

*Math.ceil().

*string.substring().

*string.toUpperCase().


text:
Q: Creating a dumb component I was wondering if there is any difference in performance when dealing with dumb component in React, since there are 2 possible ways to achieve the same result.
function Comp(props) {
    ...
}

const Comp = props => {
    ...
}

A: Really they are two ways to define a function and there should be no difference in the performances.

A: There's definitely no difference between the two in your example. Hence this code also gets compiled and you end up having the same thing:
function CompA(props) {}
const CompB = props => {}

gets transpiled to:
function CompA(props) {}
var CompB = function CompB(props) {};

edit: There is difference in both functions tho. In performance they are the same but in behavior the code is different. We have hoisting and different context involved.
edit2: Well, it looks like there IS a difference. Check out https://jsperf.com/react-stateless-compare


text:
Q: ArXive file, how do I read the source? I have an important file here but I do not know how do I extract it so that I can read it in WinEdt 9. I have Win 8.1.
What (at best signed one) file should I download and install to unzip it?
What filename extension should I give to the file now named 1907.00284 ?
I need a plain file named .tex at the end.

A: Rename the file 1907.00284 to 1907.00284.tar.gz and then use a decompression tool of your choice, e.g. 7-zip is very good for windows
If you have linux subsystems installed:
tar -xzvf 1907.00284.tar.gz


text:
Q: How can I speed up this double for loop? This is code that multiply each column by column number.
like this.
[[1,1,1],
 [2,2,2],
 [1,2,3],
 ...]

=>
[[1,2,3],
 [2,4,6],
 [1,4,9],
 ...]

And I want to reduce the time it takes to run this code.
The time should be a half of this code's running time.
(now it is about 0.04 sec, but it should be about 0.02 sec!)
But, also it must still be "double for loop".
How can I speed up this with keeping the structure??
import numpy as np
import time
x = np.ones((10000,3), dtype = np.int32)
start_time = time.clock()
y1 = np.empty((10000,3), dtype = np.int32)
for a in range(10000):
    for b in range(3):
        y1[a,b] = x[a,b]*(b)
print(time.clock() - start_time)


text:
Q: Symmetry group of a sphere in $\mathbb{R^3}$ It's obvious that the sphere is an absolutely symmetric  surface. It remains the same for any reflection over the planes which include its diameter and also for any rotation of arbitrary angle $\theta$ cw or ccw.
Does it follow from this that the symmetry group of the sphere in $\mathbb{R^3}$ is one of infinite order? And is this observation enough if it's true, or is there a way to categorize all this infinite symmetries to write them down? Are there more than the ones I mentioned?

A: The symmetry group of the sphere, including reflections, is known as the orthogonal group $O(3)$. The symmetry group with rotations only is the special orthogonal group $SO(3)$. Both have infinite order, which does indeed follow from your observations that rotations by any real angle and reflections about any plane are part of the symmetry group. The rotations form $SO(3)$, and the rotations and reflections form $O(3)$, without any missing symmetries.


text:
Q: How to make a video capture of both a VM Host and running virtual machines? I have the following configuration:

*

*Windows 8 Hyper-V host;

*Windows 8 Guest;

*Windows 7 Guest.

What I want to do is a comparison video between Win 7 and Win 8 and how things have changed. For this I need video capturing software like Camtasia. However, I don't know if Camtasia or any other software supports the following feature:
I want to capture whatever I currently see on my monitor, including maximizing and switching between VMs. As far as I know, though, if I maximize one of the guest VMs, the video capturing software, which is running on the host, would record only the desktop of the Host. Is the only solution to just keep the guests not maximized or is there an alternative?


text:
Q: Why can't I mix C++ universal references with standard reference? I'm trying to understand C++11's universal references, and wrote the following code:
#include <cstdio>

template <typename L, typename R>
static void Run(L&& lhs, const R& rhs) {
  lhs += rhs;
}

static void Run2(int&& lhs, const int& rhs) {
  lhs += rhs;
}

int main() {
  int a = 0;
  int b = 3;
  Run(a, b);
  printf("%d\n", a);
  // This does not compile.
  Run2(a, b);
  printf("%d\n", a);
  return 0;
}

Note that Run() works, but the line calling Run2() will fail to compile.  I can't really figure out why.  The error I get is no known conversion from 'int' to 'int &&' for 1st argument.
I'm sure the compiler is right, but I can't figure out under why.  It seems to be Run() and Run2() are doing the same things right?
Btw, changing Run2() to be templated with a single parameter also does not work.

A: "Universal references" can only happen in contexts where the type of the reference is deduced, such as in a template type context T&&. In this case, T can either be deduced as int for an rvalue argument, and so you have int&& as the argument type; or as int& for your lvalue argument, which would give the type int& && that per reference collapsing rules becomes just int&. In your Run2 function, the type is directly int&& and so it cannot bind to any lvalue unless you use std::move.

A: Rvalue references cannot bind to lvalues.
The special rule for creating forwarding references is that a deduced template parameter T may be deduced as T = U& when it appears in a function parameter T&&, which makes the function parameter type be U& (thanks to reference collapsing from U& &&). However, the types of the parameters of Run2 are not deduced, so the first parameter is directly an rvalue reference.
Changing Run2 to a function template with a single template parameter means that the argument deduction will fail, since there is no consistent set of types that fits both arguments.

A: The first one is a universal reference (as it described in the book of Scott Meyers Effective Modern C++) and the second one is rvalue reference
In order to make it work you need to call it like this:
Run2(std::move(a), b);

A: Run(a,b)
calls a function where typename L==int& and R==int
so
static void Run(L&& lhs, const R& hrs)
is template instantiated as
static void Run(int & && lhs, const int& hrs)
or actually because of reference collapsing, it becomes
static void Run(int& lhs, const int& hrs)
Run2 expects an rvalue reference for lhs which it can only get from casting or being given an unnamed variable (temporary). In, your case, you could call the function using a cast:
Run(std::move(a), b)


text:
Q: python compiler package explain I searched hard, but could hardly find any information on how to use the python compiler package (https://docs.python.org/2/library/compiler.html) and how to create a Visitor class that can be feed into the compiler.walk(https://docs.python.org/2/library/compiler.html#compiler.walk) method.
Can someone help me please? Thanks in advance.

A: Since the compiler package is deprecated, you should probably also take a look at the ast package.
Good docs on the Python ast can be found in "Green Tree Snakes - The Missing Python AST docs".
A very extensive example of it's use is Transcrypt's Generator class.

A: You create a visitor class by defining a subclass of compiler.visitor.ASTVisitor and then defining a method visitXXX for each type of node that you want your visitor to handle (where XXX is the name of the node type - the possible types of nodes are listed in the table in the documentation you linked).
Any such method will take one argument (two if you count self), which will be the node object representing the visited node. The attributes available on such an object are also listed in the table. If you want the visitor to proceed further into the tree, you should call visit on each child node of the node.

In the compiler.visitor.walk() method, it accepts 2 paramenters, tree and visitor. What are those?

tree is the AST that you want to process and visitor is an instance of the visitor class that you created to process that AST.

And how can i obtain those?

You obtain the AST by calling compiler.parse on some Python source code and you obtain the visitor by writing a visitor class and creating an instance of it.
Here's an example using a visitor that simply counts the number of addition operators in a piece of Python code:
import compiler

class PlusCounter(compiler.visitor.ASTVisitor):
    def __init__(self):
        self.count = 0

    def visitAdd(self, node):
        self.count += 1
        self.visit(node.left)
        self.visit(node.right)

plus_counter = PlusCounter()
compiler.walk(compiler.parse("1 + 2 * (3 + 4)"), plus_counter)
print(plus_counter.count)

And here's the same example using the non-deprecated ast package, which works basically the same way, but has a slightly different AST structure. Unlike the above code, this one will actually work in Python 3:
import ast

class PlusCounter(ast.NodeVisitor):
    def __init__(self):
        self.pluses = 0

    def visit_Add(self, node):
        # We don't need to visit any child nodes here because in the ast package
        # the AST is structured slightly differently and Add is merely a child
        # node of the BinOp node, which holds the operands. So Add itself has
        # no children that need to be visited
        self.pluses += 1

plus_counter = PlusCounter()
plus_counter.visit(ast.parse("1 + 2 * (3 + 4)"))
print(plus_counter.pluses)


text:
Q: Programmatically create a new table from anothers (Postgres) I have 32 tables with the exactly the same schema (i.e. same columns names, etc.) in a PostgreSQL 9.1 data base, and I want to create a new table from them (so I can unify the queries).
I know that I can use a INSERT SELECT technique, table by table, but I was wondering if its a better way of do that. Maybe a for loop?
Thanks in advance

A: Maybe something like this should work, if your tables really have the same column names and types:
SELECT 'INSERT INTO myschema.mynewtable SELECT * FROM ' || table_schema || '.' || table_name || ';'
  FROM information_schema.tables
  WHERE table_schema='myschema' AND table_name LIKE 'old%';

This will output the INSERT statements you can then execute to insert the data from the old tables. It would be possible to automatically execute them using a PL/SQL procedure. But if you need to do that just once, I think it's easier to execute them manually.


text:
Q: Dygrpaphs: browser not responding when showRangeSelector = true on large data set When I use dygraphs on a dataset of 50,000 points it works beautifully.
However, when I try to enable the rangeSelector the browser becomes non responsive.
This does not happen when I work with a smaller dataset (~5000 points).
Any ideas on how to solve this ?

A: It's a bug in Dygraphs, there are some tips here: https://code.google.com/p/dygraphs/issues/detail?id=468


text:
Q: Java JList How To Handle Different Model Classes? I have a Jlist and it's model class can differ. And I want to take action according to JList's model class. I tried something like this:
        private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
        Object selectedObject = jList1.getModel().getClass();
        switch (selectedObject) {

        case ResponsePlayerSearch.class:
            //do something with this class. for example run get player function from this class:
            selectedObject.getPlayerName();
            break;
        case ResponseLeagueSearch.class:
            //do something with this class
            break;
        case ResponseTeamSearch.class:
            //do something with this class
            break;
        case ResponseCoachSearch.class:
            //do something with this class
            break;
        default:

    }

}

But ide throws an error : patterns in switch statements are a preview feature and are disabled by default. (use --enable-preview to enable patterns in switch statements)
How should I handle a situation like this? Should I use switch case or something else? Or how should I use switch case for handling different classes?
Edit(To give more details) :
Basically what I'm doing is searching some values from an api. First, users have to select a type(team,player,league or coach) and according to this type they can search any word they want. So as an example, let's say user searched for a team. Then program makes the call and getting the response. Then this response is converting to a model. Which is ResponseTeamSearch for this type. After that JList's model class is changing according to this model. Then JList is getting populated by the values of response.
By the way this is the creation code of Jlist:
jList1 = new javax.swing.JList();
 jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTIO;

jList1.addListSelectionListener(new
javax.swing.event.ListSelectionListener() {
  public void valueChanged(javax.swing.event.ListSelectionEvent
evt)
{
    jList1ValueChanged(evt);
  }
    });

  jScrollPane1.setViewportView(jList1);


text:
Q: Bold content takes longer to load I have an Angular application with a page that contains:

TextBold text

The bold class is defined as
.bold {
  font-weight: bold;
}

When the page loads, 'Text' first appears, and then 'Bold text' appears.
If I apply any other css class to the span this problem doesn't happen, it has something to do with the fonts but I can't figure out what is happening and how to fix it.

A: Avoid including font cdn or specifying font-weight:bold .
Download your required font from google fonts site. It will give you choice to download various styles of same fonts. i.e italic, bold, semibold, etc.
When you use this method it does not take time to load your fonts and your issue will be solved.


text:
Q: How to use ffmpeg to add jpeg image before and after the video I am using the latest version 2.8.5 ffmpeg on Windows and I want to add 5s intro jpeg frame at the beginning of the video starts, and a 5s jpeg end frame at the end of the video.
I found a lot of example online, but seems all of them are using previous version of ffmpeg, and none of them works with the latest version.
Can anyone tell me how I can do that with the latest version.

A: Try
ffmpeg -loop 1 -t 5 -i intro.jpg -loop 1 -t 5 -i end.jpg -f lavfi -t 5 -i anullsrc -i video -filter_complex "[2:a]asplit[i][e];[0][i][3:v][3:a][1][e]concat=n=3:v=1:a=1[v][a]" -map [v] -map [a] output.mp4

With 1-second fades:
ffmpeg -loop 1 -t 5 -i intro.jpg -loop 1 -t 5 -i end.jpg -f lavfi -t 5 -i anullsrc -i video -filter_complex "[2:a]asplit[i][e];[0]fade=in:st=0:d=1[0f];[1]fade=out:st=4:d=1[1f];[0f][i][3:v][3:a][1f][e]concat=n=3:v=1:a=1[v][a]" -map [v] -map [a] output.mp4


text:
Q: How to do difficult calculations on dataframes Sample Data
df = pd.DataFrame({'sales': ['2020-01','2020-02','2020-03','2020-04','2020-05','2020-06'],
                   '2020-01': [24,42,18,68,24,30,11],
                   '2020-02': [24,42,18,68,24,30,12],
                   '2020-03': [64,24,70,70,88,57,13],
                   '2020-04': [22,11,44,3,5,78,14],
                   '2020-05': [11,35,74,12,69,51]}
print(df)
     sales  2020-01  2020-02  2020-03  2020-04  2020-05
0  2020-01       24       24       64       22       11
1  2020-02       42       42       24       11       35
2  2020-03       18       18       70       44       74
3  2020-04       68       68       70        3       12
4  2020-05       24       24       88        5       69
5  2020-06       30       30       57       78       51

My Code & Formula
To get L3, my code is below (L3 : sum of last 3 months table)

Values = df.values[:, 1:]
L3 = []
RANGE = Values.shape[0]

for a in range(RANGE):
    if a == 0:
        result = Values[a,a]
    else:
        if a < 3:
            result = np.sum(Values[0:a+1,0:a+1])
        else:
            result = np.sum(Values[a-2:a+1,a-2:a+1])
    L3.append(result)

df["L3"] = L3

print(df)
     sales  2020-01  2020-02  2020-03  2020-04  2020-05  2020-06   L3
0  2020-01       24       24       64       22       11       64   24
1  2020-02       42       42       24       11       35       24  132
2  2020-03       18       18       70       44       74       70  326
3  2020-04       68       68       70        3       12       70  350
4  2020-05       24       24       88        5       69       88  435
5  2020-06       30       30       57       78       51       57  433

L3(2020-01) = 24
--------------------
     sales  2020-01
0  2020-01       24
--------------------

L3(2020-02) = 132 (sum of 2x2 matrix)
--------------------
     sales  2020-01  2020-02
0  2020-01       24       24
1  2020-02       42       42
--------------------

L3(2020-03) = 326 (sum of 3x3 matrix)
--------------------
     sales  2020-01  2020-02  2020-03
0  2020-01       24       24       64
1  2020-02       42       42       24
2  2020-03       18       18       70
--------------------
L3(2020-04) = 350 (sum of 3x3 matrix)
--------------------
     sales  2020-02  2020-03  2020-04
0  2020-02       42       24       11
1  2020-03       18       70       44
2  2020-04       68       70        3
--------------------

PROBLEM
sometimes dataframes are dirty.
(After sorting the raw data by month, I create a dataframe with pandas crosstab.
If there is no data for some months, the rows and columns are twisted as shown below.)
how to get 'L3" below data frame?
example,
df = pd.DataFrame({'sales': ['2019-12','2020-01','2020-02','2020-03','2020-04','2020-05','2020-06'],
                   '2020-01': [0,24,42,18,68,24,30],
                   '2020-02': [6,24,42,18,68,24,30],
                   '2020-03': [7,64,24,70,70,88,57],
                   '2020-05': [13,11,35,74,12,69,51],
                   '2020-06': [14,64,24,70,70,88,57]})

     sales  2020-01  2020-02  2020-03  2020-05  2020-06
0  2019-12        0        6        7       13       14
1  2020-01       24       24       64       11       64
2  2020-02       42       42       24       35       24
3  2020-03       18       18       70       74       70
4  2020-04       68       68       70       12       70
5  2020-05       24       24       88       69       88
6  2020-06       30       30       57       51       57

Expected Output

     sales  2020-01  2020-02  2020-03  2020-05  2020-06   L3
0  2019-12        0        6        7       13       14    0
1  2020-01       24       24       64       11       64   24
2  2020-02       42       42       24       35       24  138
3  2020-03       18       18       70       74       70  326
4  2020-04       68       68       70       12       70  292
5  2020-05       24       24       88       69       88  383
6  2020-06       30       30       57       51       57  347

A: You can use .reindex to make the shape of the dataframe equal width/height and then do the computation:
from itertools import count

# make the shape of dataframe equal:
df = df.set_index("sales")
if len(df.index) > len(df.columns):
    df = df.reindex(df.index, axis=1, fill_value=0)
else:
    df = df.reindex(df.columns, axis=0, fill_value=0)

# do the computation:
c = count(1)
df["L3"] = df.apply(
    lambda x: df.iloc[max(0, (cnt := next(c)) - 3) : cnt, max(0, cnt - 3) : cnt]
    .sum()
    .sum(),
    axis=1,
)

print(df)

Prints:
sales    2019-12  2020-01  2020-02  2020-03  2020-04  2020-05  2020-06   L3
sales
2019-12        0        0        6        7        0       13       14    0
2020-01        0       24       24       64        0       11       64   24
2020-02        0       42       42       24        0       35       24  138
2020-03        0       18       18       70        0       74       70  326
2020-04        0       68       68       70        0       12       70  292
2020-05        0       24       24       88        0       69       88  383
2020-06        0       30       30       57        0       51       57  347


text:
Q: MenuItem command called when clicking IsCheckable checkbox My XAML:
<MenuItem Command="{Binding ShowRequestsCommand}" HorizontalAlignment="Stretch" IsCheckable="True" IsChecked="{Binding ShowUrgentEvaluationRequestNotification, Source={x:Static Properties:Settings.Default}, Mode=TwoWay}">
    <MenuItem.Header>
         <StackPanel Orientation="Horizontal">
             <Border Background="Red" CornerRadius="5" Padding="3,1,3,1" Margin="1,1,5,1" HorizontalAlignment="Left" MinWidth="18"></Border>
             <TextBlock>Beställningshanteraren</TextBlock>
         </StackPanel>
    </MenuItem.Header>
</MenuItem>

So it's a MenuItem with some stuff in the header, it is checkable, and that value is supposed to have some functionality elsewhere, it also has a command.
My problem is that when you click the checkbox, the command is called, which is not my intention, and it seems wrong for any situation honestly. You should be able to click the checkbox without activating whatever the MenuItem is supposed do do. I get the same result if I add a click event on the menuitem instead.
Why does WPF work like this? Is there a workaround?


text:
Q: Maximum sum when going through matrix for number of turns You have a matrix and you may start at any point.
You can go in any one of the 8 directions(down,down-left,left,left-up etc.).
For every position you're at, you add that position's value to a sum.
After you've been to a position, it's value becomes 0.
The challenge consists of creating a recursive algorithm for returning the highest sum starting from the given point.
My question is: My method doesn't work.Can you help me modify my method so it can work?
This is my code:
public int travel (int i, int j,int k,int sum)
    {
        //value temporarily takes the position's value
        int value;

        //if position is out of matrix bounds
        if(i>=x||j>=y||i<0||j<0)
        {
            return 0;
        }
        else
        {
            //makes the value in point (i,j) = 0
            value=M[i][j];
            M[i][j]=0;

            //if the number of turns has been reached
            if(k==turns)
            {
                //restores value at position
                M[i][j]=value;
                return M[i][j];
            }
            else
            {
                //loop for going to all 8 neighbors
                for(int line=-1;line<2;line++)
                {
                    for(int col=-1;col<2;col++)
                    {
                        //if the position is the same
                        if(!(col==0&&line==0))
                        {
                            sum=Math.max(travel(i+line,j+col,k+1,sum), sum);
                        }
                    }
                }

                //restores value at position
                M[i][j]=value;

                //returns sum so far
                return sum+M[i][j];
            }
        }
    }

For matrix:
    9 2 7 4
    2 8 3 7
    5 1 2 4
    1 9 8 3

turns: 3
starting point: (0,0) (of value 9)

It should return 31. The path is down-right,up-right,down-right (9+8+7+7=31)

A: Working code:
   public static int travel (int i, int j,int k)
   {
    //value temporarily takes the position's value
    int value;

    //if position is out of matrix bounds
    if(i>=x||j>=y||i<0||j<0)
    {
        return 0;
    }
    else
    {
        //makes the value in point (i,j) = 0
        value=M[i][j];
        M[i][j]=0;

        //if the number of turns has been reached
        if(k==turns)
        {
            //restores value at position
            M[i][j]=value;
            return M[i][j];
        }
        else
        {
            int sum = 0;
            //loop for going to all 8 neighbors
            for(int line=-1;line<2;line++)
            {
                for(int col=-1;col<2;col++)
                {
                    //if the position is the same
                    if(!(col==0&&line==0))
                    {
                        sum=Math.max(travel(i+line,j+col,k+1), sum);
                    }
                }
            }

            //restores value at position
            M[i][j]=value;

            //returns sum so far
            return sum+M[i][j];
        }
    }
}

The problem with your code is the sum parameter. Because, after a turn, the sum value has been updated, and you also pass this updated value to the next turn, which made the whole thing getting bigger and bigger


text:
Q: Gulp error with yeoman webapp generator using gulp-jade I have a hard time integrating jade with yeoman's gulp webapp generator.
The watch task is already working as expected but once I try to build the project I get the following error:
stream.js:94
      throw er; // Unhandled stream error in pipe.
            ^
TypeError: path must be a string

I assume it is because I changed the html task to return gulp.src('.tmp/*.html') (it was 'app/*.html' originally, which runs without an error but of course ignores my jade templates).
My gulpfile:
'use strict';
// generated on 2014-04-17 using generator-gulp-webapp 0.0.7

var gulp = require('gulp'),
    jade = require('gulp-jade');

// load plugins
var $ = require('gulp-load-plugins')();

gulp.task('styles', function () {
    return gulp.src('app/styles/main.sass')
        .pipe($.rubySass({
            style: 'expanded',
            compass: true,
            loadPath: 'app/bower_components'
        }))
        .pipe($.autoprefixer('> 5%', 'last 3 versions', 'ff >= 20', 'ie 9'))
        .pipe(gulp.dest('.tmp/styles'))
        .pipe($.size());
});

gulp.task('templates', function() {
    var YOUR_LOCALS = {};

    return gulp.src('app/*.jade')
        .pipe(jade({
            locals: YOUR_LOCALS,
            pretty: true
        }))
        .pipe(gulp.dest('.tmp'))
        .pipe($.size());
});

gulp.task('scripts', function () {
    return gulp.src('app/scripts/**/*.js')
        .pipe($.jshint())
        .pipe($.jshint.reporter($.jshintStylish))
        .pipe($.size());
});

gulp.task('html', ['templates', 'styles', 'scripts'], function () {
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');

    return gulp.src('.tmp/*.html')
        .pipe($.useref.assets())
        .pipe(jsFilter)
        .pipe($.uglify())
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe($.csso())
        .pipe(cssFilter.restore())
        .pipe($.useref.restore())
        .pipe($.useref())
        .pipe(gulp.dest('dist'))
        .pipe($.size());
});

gulp.task('images', function () {
    return gulp.src('app/images/**/*')
        .pipe($.cache($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('dist/images'))
        .pipe($.size());
});

gulp.task('fonts', function () {
    return $.bowerFiles()
        .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
        .pipe($.flatten())
        .pipe(gulp.dest('dist/styles/fonts'))
        .pipe($.size());
});

gulp.task('clean', function () {
    return gulp.src(['.tmp', 'dist'], { read: false }).pipe($.clean());
});

gulp.task('build', ['html', 'images', 'fonts']);

gulp.task('default', ['clean'], function () {
    gulp.start('build');
});

gulp.task('connect', function () {
    var connect = require('connect');
    var app = connect()
        .use(require('connect-livereload')({ port: 35729 }))
        .use(connect.static('app'))
        .use(connect.static('.tmp'))
        .use(connect.directory('app'));

    require('http').createServer(app)
        .listen(9000)
        .on('listening', function () {
            console.log('Started connect web server on http://localhost:9000');
        });
});

gulp.task('serve', ['connect', 'styles', 'templates'], function () {
    require('opn')('http://localhost:9000');
});

// inject bower components
gulp.task('wiredep', function () {
    var wiredep = require('wiredep').stream;

    gulp.src('app/styles/*.sass')
        .pipe(wiredep({
            directory: 'app/bower_components'
        }))
        .pipe(gulp.dest('app/styles'));

    gulp.src('app/*.html')
        .pipe(wiredep({
            directory: 'app/bower_components'
        }))
        .pipe(gulp.dest('app'));
});

gulp.task('watch', ['connect', 'serve'], function () {
    var server = $.livereload();

    // watch for changes

    gulp.watch([
        'app/*.html',
        'app/**/*.jade',
        '.tmp/styles/**/*.css',
        'app/scripts/**/*.js',
        'app/images/**/*'
    ]).on('change', function (file) {
        server.changed(file.path);
    });

    gulp.watch('app/**/*.jade', ['templates']);
    gulp.watch('app/styles/**/*.sass', ['styles']);
    gulp.watch('app/scripts/**/*.js', ['scripts']);
    gulp.watch('app/images/**/*', ['images']);
    gulp.watch('bower.json', ['wiredep']);
});

Any suggestions?

A: Apparently the error came from gulp-useref having problems with my build blocks.
Changing all blocks to use {app,.tmp} as it's search path fixed the behaviour, e.g.:
// build:js({app,.tmp}) scripts/vendor/modernizr.js
script(src='bower_components/modernizr/modernizr.js')
// endbuild

A: I encountered the same problem.
To fix your wiredep task, add this after the gulp.src('app/*.html') block:
gulp.src('app/*.jade')
    .pipe(wiredep({
        directory: 'app/bower_components'
    }))
    .pipe(gulp.dest('app'));

This will update the // bower:js ... // endbower blocks in your .jade files when your bower.json changes, triggered by the watch:
gulp.watch('bower.json', ['wiredep']);

at the end of your gulpfile.
Eg.
When I add "jquery": "~1.11.0" as a dependencies in my bower.json (and save).
In my /app/layout.jade file, this:
body
    // bower:js
    // endbower

Gets replaced with:
body
    // bower:js
    script(src='bower_components/jquery/dist/jquery.js')
    // endbower

If you want to use build:js without adding ({app,.tmp}) to all of your blocks, in your html task, add both app and .tmp to the source.
Your .js and .css are in the app directory, so when you changed the source to .tmp/*.html instead of app/*.html, your two $.filters didn't find any files.
To work around this, make the gulp.src() an array containing both paths.
Replace:
gulp.task('html', ['templates', 'styles', 'scripts'], function () {
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');

    return gulp.src('.tmp/*.html')
    ...

With:
gulp.task('html', ['templates', 'styles', 'scripts'], function () {
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');

    return gulp.src(['app/*.html', '.tmp/*.html'])
    ...


text:
Q: how do i get amount of datagram queued in a unix domain socket I need to get the amount of datagrams queued/pending in a unix datagram socket and yet to be received. I see that max_dgram_qlen gives what is the maximum of datagrams that can be queued in the receive buffer after which it will be blocked.
But, is there a way to how much datagrams is already queued for unix datagram socket via some socket options or via reading some linux files. Please let me know. Thanks.

A: read /proc/net/udp
From the man page:

/proc/net/udp
Holds a dump of the UDP socket table. Much of the information is not of use apart from debugging. The "sl" value is the kernel hash
  slot for the socket, the "local_address" is the local address and port
  number pair. The "rem_address" is the remote address and port number
  pair (if connected). "St" is the internal status of the socket. The
  "tx_queue" and "rx_queue" are the outgoing and incoming data queue in
  terms of kernel memory usage. The "tr", "tm->when", and "rexmits"
  fields are not used by UDP. The "uid" field holds the effective UID of
  the creator of the socket. The format is:
sl  local_address rem_address   st tx_queue rx_queue tr rexmits  tm->when uid
1: 01642C89:0201 0C642C89:03FF 01 00000000:00000001 01:000071BA 00000000 0
1: 00000000:0801 00000000:0000 0A 00000000:00000000 00:00000000 6F000100 0
1: 00000000:0201 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0


text:
Q: Inconsistent behavior with drag-and-drop of network files in JavaFX I see an odd behavior in JavaFX that I can't seem to explain or know how to resolve. My application involves importing files for processing. Users can either drag-and-drop files into the application, or use a standard browse dialog to select the files they want to import.
Our clients have the files they are going to import located on shared network drives with really long pathnames. The application itself runs locally on their machine.
The odd behavior is as follows:

*

*When a file with the long path name located on a shared network drive is selected using the standard browse dialog, it is detected and processed fine.

*When the same file is dragged from explorer into application, no file is detected and nothing happens.

public class DnDTest {

    @Start
    public void start(final Stage stage) {
        final VBox container = new VBox();
        final VBox dndZone = new VBox();
        final TextArea txtArea = new TextArea();
        final var bttn = new Button("Browse");
        dndZone.getChildren().add(new Label("Drop files here..."));

        dndZone.setPrefSize(200, 100);
        container.getChildren().addAll(dndZone, txtArea, bttn);
        container.setSpacing(10);

        dndZone.setOnDragDropped(evt -> {
            final var files = evt.getDragboard().getFiles();
            // Does NOT work. files is EMPTY
            if (files != null)
                txtArea.setText(getText(files));
        });

        dndZone.setOnDragOver(evt -> evt.acceptTransferModes(TransferMode.ANY));
        dndZone.setOnDragEntered(evt -> evt.consume());
        dndZone.setOnDragExited(evt -> evt.consume());

        bttn.setOnAction(evt -> {
            final var fileChooser = new FileChooser();
            final var files = fileChooser.showOpenMultipleDialog(stage);
            // WORKS for the same file.
            if (files != null)
                txtArea.setText(getText(files));
        });

        final Scene scene = new Scene(container);
        stage.setScene(scene);
        stage.show();
        stage.sizeToScene();
    }

    private String getText(final List<File> files) {
        return files
            .stream()
            .map(f -> f.getName())
            .collect(Collectors.joining("\r\n"));
    }
}

There are no problems with local files or with network files that have shorter path names. This problem appears when running on Windows 10 machines, but I don't know if it's limited to that OS.
Examples of some paths that cause issues are:
\\lab12jkd987.files.askon.ac.uk\Lab12Jkd987\Data\Microscopy\FixedCell\Joseph Diere\2022\2022_04_28_HMEC_FcRnGFPTransfected_FcRnAntagonists-AF555\2022_04_28_HMEC_FcRn-GFPTransfected_HAMsMediaOnly_1

\\lab12jkd987.files.askon.ac.uk\Lab12Jkd987\Data\Microscopy\FixedCell\Joseph Diere\2022\2022_04_13_BMDM_Dextran-AF555_JA01-AF647_Tf-AF488\2022_04_13_BMDM_Dextran-AF555p60c120_JA01-AF647p10c0_Tf-AF488p10c0-8

\\lab12jkd987.files.askon.ac.uk\Lab12Jkd987\Data\Microscopy\FixedCell\Joseph Diere\2022\2022_03_22 BMDM ReImaging_818C5+Mutants\2022_03_22 BMDM-M0_818C5-A647p10c0_JA03-A555p10c0_Tf488p10c0-9

Can anyone explain what is going on and how to get the behavior for the same file consistent between the two selection methods?


text:
Q: IN Clause in SQL Query I had one SQL Query:
SELECT NAME
FROM CATEGORY_LANGUAGE
WHERE
CATEGORY_ID IN (11, 22)
AND LANGUAGE_ID=1

IN THIS QUERY:
11 -> aa
22 -> bb
I want records to be returned like this:
aa
bb
While running the query returns:
bb
aa
Kindly, let me know to further elaborate my question.

A: Here is something new:
SELECT NAME
FROM CATEGORY_LANGUAGE
WHERE
    CATEGORY_ID IN (11, 22)
    AND LANGUAGE_ID=1
ORDER BY
    field(CATEGORY_ID, 11, 22)

This is catered to mysql.  Just make sure the ids are in the same order in the field() function as they are in the in() function.

A: If you always want to sort by category_id:
SELECT NAME
FROM CATEGORY_LANGUAGE
WHERE
CATEGORY_ID IN (11, 22)
AND LANGUAGE_ID=1
ORDER BY CATEGORY_ID

If, on the other hand, you always want to have the same order as in your IN-Clause, I'd use some kind of INSTR() magic (depends on your RDBMS, this works for Oracle; I put the hyphens in for readability and to avoid possible errors if one category_id is a prefix of another):
SELECT NAME
FROM CATEGORY_LANGUAGE
WHERE
CATEGORY_ID IN (11, 22)
AND LANGUAGE_ID=1
ORDER BY INSTR('11-22', TO_CHAR(CATEGORY_ID));

Explanation: TO_CHAR() converts CATEGORY_ID to a string, and INSTR() returns the index where the second string was found in the first - here, we use it to extract the sort order for our category_id from '11-22'.

A: The SQL code
CATEGORY_ID IN (11, 22)

is merely syntactic sugar for
(CATEGORY_ID = 11 OR CATEGORY_ID = 22)

The SQL engien is free to evaluate these predicates in any order is sees fit (hint: OR is associative).
It may look like a set, relation, table, tuple, list, bag etc but isn't.
SQL only really has one data structure: the table. Therefore, put your values into rows of a staging table (could be a CTE). A table doesn't have any intrinsic ordering so if this is a requirement you will need to give your stating a sort order attribute. You can then JOIN the staging table to your target base table.
Here's some Standard SQL as an example:
WITH STAGING (CATEGORY_ID, SORT_ORDER)
     AS
     (
      SELECT CATEGORY_ID, SORT_ORDER
        FROM (
              VALUES (11, 0),
                     (22, 1)
             ) AS STAGING (CATEGORY_ID, SORT_ORDER)
     )
SELECT C1.NAME, S1.SORT_ORDER
  FROM CATEGORY_LANGUAGE AS C1
       INNER JOIN STAGING AS S1
          ON C1.CATEGORY_ID = S1.CATEGORY_ID
 WHERE LANGUAGE_ID = 1
 ORDER
    BY SORT_ORDER;

A: SELECT
  NAME
FROM
  CATEGORY_LANGUAGE
WHERE
  CATEGORY_ID IN (11, 22)
AND
  LANGUAGE_ID=1
ORDER BY NAME ASC

Maybe it is just an order problem


text:
Q: Codeigniter, $_SESSION arrays i'm trying to use native $_SESSION arrays in Codeigniter beacause i can't use $_COOKIES arrays,
so i made my own class but seems that Codeigniter continue to save data on cokkies cause if i disable browser cookies i can't retrieve $_SESSION data :O !! incredible....i can't understand why?
is codeigniter stopping or removing all $_SESSION data setted ?
is there someone that is still using only $_SESSION arrays ,aborting default $_COOKIE arrays option? i mean ,i would like to have session data not cookie data but it seems to be impossible :O!!!??!!
i have renamed CI original Session.php library as Cookie.php,and than i made two personal classes into application/libraries and i load them by default into autoloader.php
1) Personal Library - Session.php
session_start();

class Session {

     function set_data($key,$data)
    {

      if(!$key)
      { echo 'first param passed is null in session set_data';}
      if(!$data)
      { echo 'second param passed is null in session set_data';}
     if(isset($key) && isset($data))
     {
         if(isset($_SESSION[$key]))
         {
             unset($_SESSION[$key]);
         }

      return $_SESSION[$key] = $data;

     }
  function keep_data($key)
    {

       if(!$key)
      { echo 'first param passed is null in session keep_data';}

       if(isset($_SESSION[$key]))
       {
         return htmlentities($_SESSION[$key]);
       }
    }

2) Personal Library - Settings.php
class Settings {

     function setsitelanguage()
    {
        $CI =& get_instance();

        if($CI->session->keep_data('lang'))
        {
            $CI->config->config['language'] = $CI->session->keep_data('lang');
        }
        else
        {
          $CI->config->config['language'] = "en";
        }

    }

than i have 2 controllers

1) Controller Home.php
class Home extends Controller {

    function Home()
    {

        parent::Controller();

               $this->settings->setsitelanguage();

        }

    function index()
    {
        $this->load->view('home/home_view');

    }
        function session()
        {
           echo   $this->session->keep_data('lang');
        }

}

2) Controller Auth.php
class Auth extends Controller {

     function usersetlang()
    {

               $lang = $this->uri->segment(3);

              return $this->session->set_data('lang',$lang);

        }
}

as shown in http://mysite/index.php/home/session, i can retrieve my language site stored with session.php by auth.php
the only problem is that is not enough using global $_SESSION[] ,because if i try to retrieve data disabling my browser cookies $_SESSION[] data doesn't appears !!!

A: $_SESSION variables may not be in the cookies themselves, but PHP still needs to be able to track the user's session in order for the $_SESSION variables to be persistent, and it uses cookies for that tracking.
PHP does try to maintain session state if cookies are turned off, by passing the session variable in the URL, but it isn't very reliable.
Bottom line - if you want session data in a web environment, you'll need cookies turned on. Sorry.
You say you can't use cookies, but you didn't really explain why. It's fairly unusual these days for people to want to turn off cookies, as they're used virtually everywhere.

A: We could use the $_SESSION if we do session_start();
The thing is, $_SESSION won't work across pages on codeigniter.
Quick fix:
Since the pages in mvc are triggered by the controller, we could do this
public function __construct(){
    self::$instance =& $this;
    foreach (is_loaded() as $var => $class) {
        $this->$var =& load_class($class);
    }

    $this->load =& load_class('Loader', 'core');

    $this->load->initialize();

    log_message('debug', "Controller Class Initialized");
    session_start();
}

to the CI_Controller class on system/core/Controller.php
It worked!

A: Yes you can do that
create this table:
CREATE TABLE IF NOT EXISTS  `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(16) DEFAULT '0' NOT NULL,
user_agent varchar(50) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text NOT NULL,
PRIMARY KEY (session_id)
);

and change this in the config:
$config['sess_use_database'] = FALSE;
to
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions'; should match the name of your table.
To clarify - by default, CI's session system uses a cookie to store the data. Don't know why, it just does. You can change this for security etc by using the database table instead.
You access session values exactly the same, but aren't restricted by cookie maximum file sizes, or security risks.
You can of course use normal $_SESSIONS and create your own script - remember CI is a framework, you aren't required to use all of it.

A: Since when does CodeIgniter "block" $_SESSION? If you want to use a session, you have to start it. To do that you need to write session_start() somewhere. why not in your index.php?
CodeIgniter is just PHP, not some evil dark magician.

A: There's a cookie that stores PHPSESSID browser side.

A: If you can't propagate the session id via cookies, you can do so via URL.
See: http://www.php.net/manual/en/session.idpassing.php


text:
Q: Use the cordova-plugin-file-transfer to download a image, not find the image in android device Why i use the cordova-plugin-file-transfer to download a image, i could use the entry.toURL in the image src, the image could display, but i can't find the image in my android devices: the path 'file:///data/data/com.example.hello/cache/123.png' not found

A: Tried out something like this in the past and faced the same issue. Looks like the phone needs to be rooted to make it work. Checkout this github link for working sample on this. It downloads file from server using file transfer plugin and saves it in device using file plugin.


text:
Q: Getting statistics of the activity of my engine One of my application is an engine that executes some complex calculations. These calculations may take several hours. I want to know the activity of this engine among time.
If you are using Hudson CI server, there is such a feature in Administration > Usages statistics option. Here is an example:

In my application, I already have a function that returns the number of calculations. So my idea is to periodically call this method, for example every 10 minutes (using Quartz) in order to retrieve the number of running calculations and store it in a int[]. Every day, this int[] is stored in an external file, and cleaned. So after some days, the content of this file will look like:
data.20101008=1;2;1;0;1;1;0;0;0;0;....;0
data.20101009=1;0;1;1;0;0;0;0;3;2;....;0
data.20101010=1;2;1;0;1;1;2;3;4;4;....;2
...

(I simplified a little this processing, as I want to update this file more frequently, in case of engine shutdown, or something like that)
To summarize, my idea is to store in a properties file the number of running calculations for a specific day. Eventually, I can provide a function that returns this data as a Map<Date, int[]>.
Finally, I will use JFreeChart to display these data in a graphical
What do you think of this idea? Any advice to enhance this process?
Note that this functionality is one a nice to have feature, so I don't want to build too complex systems.
I am using Java 6.

A: For simple ad-hoc monitoring by a human operator, you can simply use JMX. With JConsole (ships with the JDK) you can connect to a running java process and it will do nice graphs of CPU and memory usage, number of live threads, any many more. Using MBeans, you can expose current values over JMX, and use JConsole to chart them  (while it is connected, of course).

A: Instead of a properties file and JFreeChart, maybe consider using a RRDTool Java implementation like RRD4J. From the RRDTool website:

RRDtool is the OpenSource industry standard, high performance data logging and graphing system for time series data.


text:
Q: How can I compute the result of the magnitude of edges of an square image? if I have an image with 11x11 pixels and In the center of the image is a square of 5x5 pixels. The gray level of the background is 0 and the gray level of the square is 50. How can I compute the result of the magnitude of edges given by the compass operator for this image taking into account that the image is not noisy? I have the code but I don't know how to apply the math on paper...
from skimage import filters
import numpy as np
grad_x = filters.sobel_h(input_image)
grad_y = filters.sobel_v(input_image)
edge_magnitude = np.sqrt(grad_x**2+grad_y**2)


text:
Q: Menu slide toggle. Function not executed on screen width I'm trying to make a menu for a responsive site. The click function already works but I want the menu to slide up when the screen size is smaller than 850 pixels but I can't seem to get the function to execute.
Here's my code:
$(document).ready(function () {
      $( "#mobile" ).click(function() {
      $( "#fripple" ).slideToggle();
      $( "#site-navigation" ).slideToggle();
      $( "#secondary" ).slideToggle();

        if (screen.width >= 850) {
      $( "#fripple" ).show();
      $( "#site-navigation" ).show();
      $( "#secondary" ).show();
    }

    else if (screen.width < 850){

      $( "#fripple" ).slideUp();
      $( "#site-navigation" ).slideUp();
      $( "#secondary" ).slideUp();
    }

    });
});

A: I think .show() is not needed anymore since you already slideToggle() the display has been changed to block. With window.screen.width your trying to get the device native screen resolution so use $(window).width() instead.
$(document).ready(function(){
    $('#mobile').click(function(){
        $( "#fripple" ).slideToggle();
        $( "#site-navigation" ).slideToggle();
        $( "#secondary" ).slideToggle();

        if($(window).width() < 850){
            $( "#fripple" ).slideUp();
            $( "#site-navigation" ).slideUp();
            $( "#secondary" ).slideUp();
        }
   });
});