text:
Q: Faster way to get the numerical difference between 2 byte[] arrays? I'm working on a program where I have 2 byte arrays and need to calculate the difference between them. For example, if the first array was {1, 2, 3}, and the second array {2, 3, 4}, the difference would be 3.
My current method to do this looks like this:
public long calculateDifference(byte[] a, byte[] b) {
  long difference = 0;
  for(int i = 0; i < a.length; i++) {
    difference += Math.abs(a[i] - b[i]);
  }
  return difference;
}

However, the program will need to be able to process byte arrays that have up to around 5,000,000 elements, so using the current method would be too slow.
Because I have 16 threads, I've seen parallel streams as an option. But because there's no ByteStream, using the reduce and collect operations wouldn't be possible without unboxing and boxing.
Another option would be to use IntStream.range(0, byteArrayLength) to create a parallel stream and the access the index using the int. However, to do this a LongAdder or AtomicLong would be necessary, both of which are much slower in my benchmarks. (LongAdder seems to use an array internally then sum it up at the end)
Is there a more efficient way to achieve this? I don't mind adding external dependencies. Thanks!

A: One thing you can try is divide the data into two or more regions that are each processed in separate threads. It may make enough of a difference for arrays of a billion items to make it worth it, but for as few as 5 million, probably not.
What follows is a very crude proof-of-concept you can use to evaluate if the idea has any merit at all.
Make a method that does the computation for a region:
public long calculateDifference(byte[] a, byte[] b, int start, int end) {
    long difference = 0;
    for(int i = start; i < end; i++) {
        difference += Math.abs(a[i] - b[i]);
    }
    return difference;
}

And call this method from several threads, and combine the results:
ExecutorService threadPool = Executors.newFixedThreadPool(2);

public long calculateDifference(byte[] a, byte[] b) throws Exception {
    Future<Long> diff1 = threadPool.submit(() -> calculateDifference2(a, b, 0, a.length / 2));
    Future<Long> diff2 = threadPool.submit(() -> calculateDifference2(a, b, a.length / 2, a.length));
    return diff1.get() + diff2.get();
}


text:
Q: How to create a circular bar plot using ggplot I am trying to create a circular bar plot using my data, but I could not even organize the data frame in order to do it. I have 121 seed analizes from 3 different years (column named campana), and from 4 regions of a province (column named zona). I would like to make a graph like the one in the image, using the different areas (zonas) instead of the letters A-B-C-D, and using the stacked bars to show the incidence (frequency) of fungi on each year. Each fungus frequency is in a column with the fungus name, such as A.padwickii, Microdochium, Bipolaris, etc. I don't expect you to do all the work, just the first step of helping me organize the data in the correct way.
tibble::tribble(
     ~muestra_n, ~campana, ~zona, ~inc_pan, ~percent_gran_m_pan, ~peso_pan, ~percent_perdida_peso, ~severidad, ~phoma, ~microdochium, ~a_padwickii, ~bipolaris, ~curvularia, ~fusarium, ~exserohilum,
             16,        2,     2,       98,                14.6,      2.85,      9.90007401924501,        0.1,      0,            11,            0,          0,           0,         0,            0,
             18,        2,     2,     97.1,                 7.8,      1.34,      29.9991559044484,       0.44,     13,             0,            0,          0,           0,         0,            0,
             19,        2,     2,      100,                14.3,      1.35,    0.0288073746879383,       0.66,      0,            16,            0,          0,          18,         0,            0,
             20,        2,     1,      100,                 9.6,      1.49,      1.64930877284015,       0.09,      0,            12,            1,          2,          44,         0,            0,
             21,        2,     1,      100,                17.9,      3.04,      1.46085792877853,       0.56,      0,             9,            0,          0,           1,         0,            0,
             22,        2,     1,      100,                37.4,       2.1,      5.60829881602581,        0.6,     41,             8,            0,          0,           1,         0,            1
     )

A: Not enough info to know for sure, but hopefully this moves you in the right direction with a few tips. In my experience, polar plots tend to require a lot of customization for labeling based on where it fits, rather than any particular standard. This makes for a lot more complication when you make them.
library(tidyverse)
YOUR_DATA %>%

  # this step reshapes your data to a format more suited for ggplot2; each
  # fungi appearance is given its own row
  pivot_longer(phoma:last_col()) %>%

  # this sets up the main plot
  ggplot(aes(name, value)) +
  geom_col() +

  # these add the lines and text for zonas. If you have many of them, it
  # might make sense to figure these out as a separate data frame and feed
  # these into lines like `geom_segment(data = SUMMARY) + geom_text(data =
  # SUMMARY)`
  annotate("segment", x = c(0.5,2.5,4.5), xend = c(2.4,4.4,7), y = -10, yend = -10) +
  annotate("text", x = c(1.5,3.5,5.5), y = -20, label = LETTERS[1:3]) +

  # This adds space in the middle, changing it from a pie chart to a donut
  scale_y_continuous(limits = c(-100, NA)) +
  coord_polar() +   # converts into polar coordinates
  theme_void()      # gets rid of grid lines and axis labels

A: As Jon Spring said, polar plots can be very difficult to customize in the way you've described. They are also often difficult to read and interpret, but that's another matter. For these reasons, most plotting systems don't make it easy to create heavily customized polar plots.
To achieve what you want, we'll need to do a lot manual work, including:

*

*Reshape the data into "long" format to work with ggplot.

*Custom calculations to correctly rotate each fungus text label.

*Custom calculations for the "zone" secondary x-axis.

*An obscure use of ggplot's summary functions to ensure that text labels are placed correctly at the top of each bar stack.

The following code implements all of this. Here I've duplicated the data under a second value of "campana" to verify that things plotted correctly when the bars stack. Comments presented alongside:
# reshape the data to "long" format
df.long <- df %>% # YOUR DATA
  select(zona, campana, phoma:exserohilum) %>%
  pivot_longer(-c(zona, campana), names_to = 'fungus', values_to = 'freq') %>%
  filter(freq > 0)

# duplicate the data and change campana so that we have some stacks to work with
df.long <- df.long %>%
  bind_rows(mutate(df.long, campana = 3))

df.long.summary <- df.long %>%
  group_by(combined_label = paste(zona, fungus, sep = '_'), fungus, campana, zona) %>% # a label that combines zona and fungus for the x-axis
  summarize(freq = sum(freq)) %>% # totals
  ungroup %>%
  mutate(
    x = as.numeric(factor(combined_label)), # the numerical position of each x-axis label
    campana = factor(campana), # optional, but ggplot produces better colors this way
    angle = (max(x) + 0.45 - x) / max(x) * 2*pi * 180/pi + 90, # calculate an angle for each text label
    angle = angle %% 360, # constrain to [0-360]
    flip = angle > 90 & angle < 270, # angles that fall in this range will need to be flipped for easier reading
    angle = ifelse(flip, angle + 180, angle), # flip the angle
    hjust = ifelse(flip, 1.1, -0.1) # flip the hjust parameter to match
  )

# create secondary x-axis parameters for "zona"
df.zona <- df.long.summary %>%
  group_by(zona) %>%
  summarize(
    zona_x = min(x) - 0.4,
    zona_xend = max(x) + 0.4,
    label_x = mean(x),
    angle = 90 - (max(x) - zona_x) / max(x) * 2*pi * 180/pi + 90
  )

plot.fungi <- df.long.summary %>%
  ggplot(data = ., aes(x = x, y = freq)) +
  geom_col(position = 'stack', aes(fill = campana)) +
  geom_text(aes(label = fungus, x = x, y = freq, angle = angle, hjust = hjust), stat = 'summary', fun = sum) +
  geom_segment(data = df.zona, aes(x = zona_x, xend = zona_xend), y = -10, yend = -10) +
  geom_text(data = df.zona, aes(label = zona, x = label_x, y = -12, angle = 0, vjust = sign(angle) * 2)) +
  coord_polar(clip = 'off') +
  scale_y_continuous(limits = c(-100, NA)) +
  theme_void()
print(plot.fungi)

It would be much simpler to create a cartesian (non-polar) plot of the same data (in my opinion, this is also easier to read):
# reshape the data to "long" format
df.long <- df %>%
  select(zona, campana, phoma:exserohilum) %>%
  pivot_longer(-c(zona, campana), names_to = 'fungus', values_to = 'freq') %>%
  filter(freq > 0)

df.bar <- df.long %>%
  mutate(
    campana = factor(campana),
    zona = paste0('Zona ', zona)
  ) %>%
  ggplot(data = ., aes(x = fungus, y = freq, fill = campana)) +
  geom_col(position = 'stack') +
  facet_grid(facets = ~zona, scales = 'free_x', space = 'free_x') +
  theme_minimal() +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1),
    strip.background.x = element_rect(fill = '#cccccc', color = NA)
  )
print(df.bar)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to find limit $\lim_{h\rightarrow0^-}\frac{e^{-1/|h|}}{h^2}$ How can I find limit $$\lim_{h\rightarrow0^-}\frac{e^{-1/|h|}}{h^2}$$
I solve subproblem: $$\lim_{h\rightarrow0^-}\frac{e^{-1/|h|}}{h} = \lim_{h\rightarrow0^-}\frac{1}{e^{1/|h|}\cdot h} =\lim_{y\rightarrow -\infty}\frac{y}{e^{|y|}}=0$$
but I have no idea how to apply that for main target

A: It suffices to prove $$\lim_{y \to +\infty} \frac{y^2}{e^y} = 0$$ using the limit you provided.
Notice that you may write:
$$\frac{y^2}{e^y} = \frac{y}{e^{y/2}}\cdot \frac{y}{e^{y/2}} = 4 \cdot \frac{y/2}{e^{y/2}} \cdot \frac{y/2}{e^{y/2}}$$
Now you just have to substitute $z = y/2$ and take the limit $\frac{z}{e^z} \to 0$.

A: To use your result, substitute $h\mapsto2h$ and square:
$$
\lim_{h\to0^-}\frac{e^{-1/|h|}}{(2h)^2}=\left(\lim_{h\to0^-}\frac{e^{-1/|2h|}}{2h}\right)^2=0
$$

A: Note that, since you have the limit for $h\to0^-$, the substitution $y=1/h=-1/|h|$ brings the limit into the form
$$
\lim_{y\to\infty}\frac{y^2}{e^y}
$$
Now any limit of the form
$$
\lim_{y\to\infty}\frac{y^k}{e^y}
$$
with $k>0$ can be dealt with the substitution $y=kz$, so you get
$$
\lim_{z\to\infty}\frac{k^kz^k}{e^{kz}}=k^k\lim_{z\to\infty}\left(\frac{z}{e^z}\right)^{\!k}
$$
Thus you just need to know that $\lim_{z\to\infty}z/e^z=0$.


text:
Q: I need help plotting different permutations of an if/else command in different colors on the same plot Basically I have a code where it produces a plot of all possible permutations between Cost and Reliability. There's a total of 864 data points split up between 8 rows. Five of the rows have 2 options and three of them 3 options.
Given here is a copy of my code. I'm trying to have the permutations of 'Other Cameras' and 'Depth & Structure Testing' have a different color with the other six possibilities. I tried using the 'gscatter' command but didn't have much luck with it.
I believe I need to have the scatter command in the if/else statements themselves, although I'm not too sure what to plot in the 'X' and 'Y' for the 'scatter' command. Currently my code is set up for plotting all the data in one color. I deleted my code with the 'gscatter' because I got many errors and when I tried to fix them the plot ultimately didn't work as planned.
% Pareto_Eval
baseline_cost = 45;
nrows = 8;
%Initialize Variables
for aa = 1:nrows
   cost_delta(aa) = 0;
   reliability(aa) = 1;
end
icount = 1;

   %Propulsion
for row1 = 1:2
    if row1 == 1
        cost_delta(1)= -7;
        reliability(1) = 0.995;
    elseif row1==2
        cost_delta(1)=0;
        reliability(1)=.99;
    end

    %Entry Mode
for row2 = 1:2
    if row2 == 1
        cost_delta(2) = -3;
        reliability(2) = .99;
    else
        cost_delta(2) = 0;
        reliability(2) = .98;
    end

    %Landing Method
for row3 = 1:3
    if row3 == 1                %if needs declaration
        cost_delta(3)= 0;
        reliability(3) = .99;
    elseif row3 == 2            %elseif needs declaration
        cost_delta(3) = 4;
        reliability(3) = .995;
    else                        %else does not need declaration
        cost_delta(3) = -2;
        reliability(3) = .95;
    end

    %Lander Type
for row4 = 1:3
    if row4 == 1
        cost_delta(4)= 10;
        reliability(4) = .99;
    elseif row4 == 2
        cost_delta(4) = 0;
        reliability(4) = .99;
    else
        cost_delta(4) = 15;
        reliability(4) = .95;
    end

    %Rover Type
 for row5 = 1:2
    if row5 == 1
        cost_delta(5)= -2;
        reliability(5) = .98;
    else
        cost_delta(5) = 0;
        reliability(5) = .975;
    end

    %Power Source
for row6 = 1:2
    if row6 == 1
        cost_delta(6) = -3;
        reliability(6) = .95;
    else
        cost_delta(6) = 0;
        reliability(6) = .995;
    end

    %Depth & Structure Testing
for row7 = 1:2
    if row7 == 1
        cost_delta(7) = 0;
        reliability(7) = .99;
    else
        cost_delta(7) = 2;
        reliability(7) = .85;
    end

      %Other Cameras
for row8 = 1:3
    if row8 == 1
        cost_delta(8)= -1;
        reliability(8) = .99;
    elseif row8 == 2
        cost_delta(8) = -1;
        reliability(8) = .99;
    else
        cost_delta(8) = 0;
        reliability(8) = .9801;
    end

    cost_delta_total = 0;
    reliability_product = 1;

    for bb=1:nrows
        cost_delta_total = cost_delta_total + cost_delta(bb);
        reliability_product = reliability_product*reliability(bb);
    end

    total_cost(icount) = baseline_cost + cost_delta_total;
    total_reliability(icount) = reliability_product;
    icount = icount + 1;

end; end; end;      %Rows 1,2,3
end; end; end;      %Rows 4,5,6
end; end;           %Rows 7,8

%Plot the Pareto Evaluation
fignum=1;
figure(fignum)
sz = 5;
scatter(total_reliability, total_cost, sz, 'blue')
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')

Any help is appreciated. I don't have a lot of experience with Matlab and I've tried looking around for help but nothing really worked.
Here is a sample code to make questions easier I created:
% Pareto_Eval
baseline_cost = 55;
nrows = 3;

%Initialize Variables
for aa = 1:nrows
   cost_delta(aa) = 0;
   reliability(aa) = 1;
end
icount = 1;

%Group 1
for row1 = 1:2
    if row1 == 1
        cost_delta(1)= 5;
        reliability(1) = 0.999;
    elseif row1==2
        cost_delta(1) = 0;
        reliability(1) = .995;
    end

    %Group 2
    for row2 = 1:2
      if row2 == 1
        cost_delta(2) = 0;
        reliability(2) = .98;
      else
        cost_delta(2) = -2;
        reliability(2) = .95;
      end

      %Group 3
      for row3 = 1:2
        if row3 == 1
          cost_delta(3) = 3;
          reliability(3) = .997;
         else
          cost_delta(3) = 0;
          reliability(3) = .96;
        end

       %initializing each row
       cost_delta_total = 0;
       reliability_product = 1;

        for bb = 1:nrows
          cost_delta_total = cost_delta_total + cost_delta(bb);
          reliability_product = reliability_product*reliability(bb);
        end

       total_cost(icount) = baseline_cost + cost_delta_total;
       total_reliability(icount) = reliability_product;
       icount = icount + 1;
      end
    end
end

fignum=1;
figure(fignum)
sz = 25;
scatter(total_reliability, total_cost, sz)
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')

Basically I need to make a plot in each if-loop, but I'm not sure how to do it and have them all on the same plot

A: sounds like an interesting project! Not sure if I understood your intended plots correctly, but hopefully the code below gets you a bit closer to what you are looking for.
I've started off with a rather deep mess of nested for loops (as you did) but kept it more concise bybuilding a permutations matrix.
counter = 0;
for propulsion_options = 1:2
    for entry_mode = 1:2
        for landing_method = 1:3
            for lander_type = 1:3
                for rover_type = 1:2
                    for power_source = 1:2
                        for depth_testing = 1:2
                            for other_cameras = 1:3
                                counter = counter +1
                                permutations(counter,:) = [...
                                    propulsion_options,...
                                    entry_mode,...
                                    landing_method,...
                                    lander_type,...
                                    rover_type,...
                                    power_source,...
                                    depth_testing,...
                                    other_cameras];
                            end
                        end
                    end
                end
            end
        end
    end
end

This way I kept the actual scoring out of the loops, and perhaps easier to tweak the values. I initialised the cost and reliabiltiy arrays to be the same size as the permutations array:
cost_delta = zeros(size(permutations));
reliability = zeros(size(permutations));

Then for each metric, I searched the permutations array for all occurances of each possible value and assigned the appropriate score:
%propulsion
propertyNo = 1;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -7;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.995;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.99;

%entry_mode (2)
propertyNo = 2;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -3;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.98;

%landing_method (3)
propertyNo = 3;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = 0;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 4;
cost_delta(find(permutations(:,propertyNo)==3),propertyNo) = -2;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.995;
reliability(find(permutations(:,propertyNo)==3),propertyNo) = 0.95;

%lander_type (3)
propertyNo = 4;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = 10;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
cost_delta(find(permutations(:,propertyNo)==3),propertyNo) = 15;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==3),propertyNo) = 0.95;

%rover_type (2)
propertyNo = 5;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -2;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.98;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.975;

%power_source (2)
propertyNo = 6;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -3;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.95;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.995;

%depth_testing (2)
propertyNo = 7;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = 0;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = 2;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.85;

%other_cameras (3)
propertyNo = 8;
cost_delta(find(permutations(:,propertyNo)==1),propertyNo) = -1;
cost_delta(find(permutations(:,propertyNo)==2),propertyNo) = -1;
cost_delta(find(permutations(:,propertyNo)==3),propertyNo) = 0;
reliability(find(permutations(:,propertyNo)==1),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==2),propertyNo) = 0.99;
reliability(find(permutations(:,propertyNo)==3),propertyNo) = 0.9801;

Then each permutation can have a total cost / reliabiltiy score by summing and takign the product along the second dimension:
cost_delta_total = sum(cost_delta,2);
reliability_product = prod(reliability,2);

Finally, you can plot all points (as per your original):
%Plot the Pareto Evaluation
fignum=1;
figure(fignum)
sz = 5;
scatter(reliability_product, cost_delta_total, sz, 'b')
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')

or you can create an index into the permutations by searching for specific property values and plot these different colours (actually this bit answers your most specific question of how to plot two things on the same axes - you just need the hold on; command):
propertyNo = 7;
indexDepth1 = find(permutations(:,propertyNo)==1);
indexDepth2 = find(permutations(:,propertyNo)==2);
fignum=2;
figure(fignum)
sz = 5;
scatter(reliability_product(indexDepth1), cost_delta_total(indexDepth1), sz, 'k');
hold on;
scatter(reliability_product(indexDepth2), cost_delta_total(indexDepth2), sz, 'b');
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
legend('Depth & Structure Test 1','Depth & Structure Test 2')

propertyNo = 8;
indexCam1 = find(permutations(:,propertyNo)==1);
indexCam2 = find(permutations(:,propertyNo)==2);
indexCam3 = find(permutations(:,propertyNo)==3);
fignum=3;
figure(fignum)
sz = 5;
scatter(reliability_product(indexCam1), cost_delta_total(indexCam1), sz, 'k');
hold on;
scatter(reliability_product(indexCam2), cost_delta_total(indexCam2), sz, 'b');
scatter(reliability_product(indexCam3), cost_delta_total(indexCam3), sz, 'g');
xlabel('Reliability')
ylabel('Cost')
title('Pareto Plot')
legend('Other Camera 1','Other Camera 2','Other Camera 3')

Good luck with the mission! When is launch day?


text:
Q: Prxmatch in SAS - using $ to limit results doesn't work I'm trying to use prxmatch to verify if postcode format (UK) is correct. The ('/^[A-Z]{1,2}\d{2,3}[A-Z]{2}|[A-Z]{1,2}\d[A-Z]\d[A-Z]{2}$/') bit covers (I think) all the possible post code formats used in UK, however I only want exact and not partial matches and no additional chars before or after match.
data pc_flag ; set abc ;

format  pc_correct_flag $1. compressed_postcode $100.;
compressed_postcode = compress(postcode);

pc_regex = prxparse('/^[A-Z]{1,2}\d{2,3}[A-Z]{2}|[A-Z]{1,2}\d[A-Z]\d[A-Z]{2}$/');

if prxmatch(pc_regex,compressed_postcode)>0

    then pc_correct_flag='Y';
    else pc_correct_flag='N';run;

I was expecting 'Y' only on exact matches on full string, i.e. with no additional characters before and after regex. However, I'm also getting false positives, where a part of 'compressed_postcode' matches regex, but there are additional characters after the match, which I thought using $ would prevent.
I.e. I'd expect only something like AA11AA to match, but not AA11AAAA. I suspect this has to do with $ positioning but can't figure out exactly what's wrong. Any idea what I've missed?

A: SAS character variables contain trailing spaces out to the length of the variable.  Either trim the value to be examined, or add \s*$ as the pattern termination.
if prxmatch(pc_regex,TRIM(compressed_postcode))>0 then …

A: Your regex is quite permissive - it allows every letter of the alphabet in every valid character position, so it matches quite a lot of strings that look like valid postcodes but do not exist as such, e.g. ZZ1 1ZZ.
I provided a more specific SAS-compatible postcode regex as an answer to another question - here's link in case this proves useful to you:
https://stackoverflow.com/a/43793562/667489
That one still matches some non-postcode strings, but it filters out any with characters on Royal Mail's blacklists for each position within the postcode.
As per Richard's answer, you need to trim the string being matched before applying the regex, or amend the regex to match extra trailing blanks.


text:
Q: How I prevent the bottom Order By from effecting everything in @Result? I need to prevent the Order By SettingID at the bottom of this SQL from re-ordering everything. I want to Order my first select by UserID and my second select by OrderID. How do put a bound on the bottom Order By? I tried parentheses but I'm a T-SQL beginner so couldn't get that figured out. I tried using @ResultA and @ResultB and then Select them into @Result but the end result is the same the bottom Order By applies to the entire @Result. Would temp tables be the way to go and if so how?
  DECLARE @Result TABLE (SettingID INT, GroupID INT, UserID INT)

  INSERT INTO @Result
  SELECT
       SettingID,
       GroupID,
       UserID
  FROM Table1
  WHERE (GroupID = @GroupID AND UserID = @UserID)
  ORDER BY UserID

  INSERT INTO @Result
  SELECT
       SettingID,
       GroupID,
       UserID
   FROM Tabel1
   WHERE (GroupID IS NULL)
   ORDER BY SettingID DESC -- This Order By is reordering everything in @Result.

   SELECT * FROM @Result

A: Use commas to add ORDER BY layers:
SELECT * FROM @Result ORDER BY UserID, OrderID

You can and should remove the order by in the queries that populate your table variable.

A: You should not depend on the ordering of rows in a table, even table variables.  In SQL, tables represent unordered sets.  You can do what with a single query:
SELECT SettingID, GroupID, UserID
FROM Table1
ORDER BY (CASE WHEN (GroupID = @GroupID AND UserID = @UserID) THEN 1 ELSE 0 END) DESC,
         GroupID

You can put this into a table variable:
INSERT INTO @Result
    SELECT SettingID, GroupID, UserID
    FROM Table1
    ORDER BY (CASE WHEN (GroupID = @GroupID AND UserID = @UserID) THEN 1 ELSE 0 END) DESC,
             GroupID;

However, you cannot assume that:
SELECT *
FROM @Result

will be in any particular order, such as insert order.
There is a trick if you want to do that.  Create an identity column in the temporary table and order by that:
DECLARE @Result TABLE (
    ResultId INT IDENTITY(1, 1) PRIMARY KEY,
    SettingID INT,
    GroupID INT,
    UserID INT
);

INSERT INTO @Result(SettingID, GroupID, UserID)
    SELECT SettingID, GroupID, UserID
    FROM Table1
    ORDER BY (CASE WHEN (GroupID = @GroupID AND UserID = @UserID) THEN 1 ELSE 0 END) DESC,
             GroupID;

SELECT *
FROM @Result
ORDER BY ResultId;

A: Tables don't have a concept of record order as you perceive it. It just doesn't exist.
If you need to guarantee that results are returned in a specific order, you must use an ORDER BY on the select query that produces those results. With that in mind, you should probably just omit the ORDER BY clause on your INSERT statements, and only include it on the final select.
More than that, if controlling the order is the whole reason for the temp table, you should really just do this:
SELECT
   SettingID,
   GroupID,
   UserID
FROM Table1
WHERE (GroupID = @GroupID AND UserID = @UserID) OR @GroupID IS NULL
ORDER BY CASE WHEN GroupID IS NOT NULL THEN 0 ELSE 1 END
       , CASE WHEN GroupID IS NOT NULL THEN UserID ELSE SettingID END

A: ORDER BY
CASE WHEN (SettingID between x and y)
THEN UserID
else OrderID END


text:
Q: Poiseuille flow: can I avoid the simplification that $u=u(y)$? Let's consider a viscous, incompressible and irrotational fluid that flows in a canal in two dimensions. It is reasonable to assume that the velocity of the fluid has the form $\vec v = u(x,y,t) \hat x $, or in other words, we are assuming that the velocity has just the horizontal component $u(x,y,t)$.
Under these hypotheses, the incompressibility condition $\vec \nabla \cdot \vec v = 0$ gives us that $\partial_x u = 0$, i.e. $u$ depends only on $t$ and $y$.
The Navier-Stokes equations then become
$$ (1) \qquad \begin{cases}
\partial_tu = -\partial_xp + \nu \partial_{yy}u \\
-\partial_y p = 0
\end{cases}$$
At this point one usually says "suppose that the velocity does not depend on time": the first equation of the system $(1)$ simplifies to $\nu \partial_{yy}u = \partial_x p $ and one obtain a closed form of the pressure $p$ and the velocity $u$.
My question is: while the assumptions made at the beginning seem resonable with the usual context of fluid dynamics, the last hypothesis seems to be made just to derive in few steps a solution of the problem. Although it is said "a physical theory will always be wrong" because of the assumptions made to translate the real world into some mathematical equations, I ask:

Can the system $(1)$ have solutions without the simplification that $u = u(y)$?

A: You have reduced the Navier-Stokes equations to a simple form by making a number of assumptions that may or may not be realistic or commensurate with a physical configuration.  To begin with, restricting to two-dimensional flow where there is no dependence on the spanwise coordinate $z$ nor a non-zero velocity component $w$ in that direction can only be true assuming infinite extent of the domain in the $z-$direction.  Furthermore, by assuming there is no dependence on the streamwise coordinate $x$, you are making the assumption of fully developed flow far from an entrance to the channel where the velocity field must assume a more complicated form. Nevertheless, if the physical dimensions are such that the the spanwise extent is very large and we are examining the flow far from an entrance, this can be a good approximation.
Of more immediate concern is that you have not mentioned boundary conditions.  If the channel is confined between solid stationary boundaries at $y = 0,L$, then we must impose the boundary conditions $u(0) = u(L) =0$.  A further assumption is needed about the pressure gradient.  The simplest would be that it is constant, $\frac{\partial p}{\partial x} = -G < 0$. In this case, (1) admits a steady solution obtained by first integrating twice with respect to $y$ to get
$$u(y) = C_1 +C_2y - \frac{Gy^2}{2\nu},$$
and, after applying boundary conditions, we obtain the velocity profile for steady plane Poiseuille flow:
$$u(y) = \frac{GL}{2\nu}\left( y - \frac{y^2}{L}\right)$$
Again, this is an idealization for the flow between infinite parallel plane boundaries with a constant pressure gradient.
Changing the configuration or boundary conditions by introducing time-dependency will lead to solutions of (1) with the full functional form $u(y,t)$.  An example would be when the pressure gradient is itself time-dependent, for example oscillating sinusoidallly in time.
A classic variation with a time-dependent solution is the Stokes problem. In this case the domain is of semi-infinite extent $0 \leqslant y < \infty$ and the flow is driven not by pressure but, instead, by the sinusoidal oscillation of a plate at $y=0$ requiring the boundary condition $u(0,t) = U\cos \omega t$.  In this case, the pressure gradient is taken to be zero and the closed form solution to (1) is
$$u(y,t) = Ue^{-\sqrt{\frac{\omega}{2\nu}}y}\cos \left(\omega t - \sqrt{\frac{\omega}{2\nu}}y \right)$$
A closed-form time dependent solution can even be obtained when $0 \leqslant y \leqslant L$ and there is a stationary wall at $L$ where $u(L,t) =0$ for all $t$.
Even in simple configurations like flow between infinite parallel plates,  the full Navier-Stokes equations admit extremely complex  time-dependent solutions that reflect the instability of unidirectional, laminar flow and the transition to fully developed turbulence.


text:
Q: SWT setForeground in Windows 7 vs. Windows XP We have SWT apps which use the setForeground method on windows XP, and they work fine.  However, running the most recent stable SWT jars and dlls on Win7 seems to show the setForeground method being ignored.  I know that the javadoc says it's a hint, but I wanted to know if this is because something changed between XP and 7, or if it's possible it's a system setting on my new Win7 install.
I had found this post: How to set SWT button foreground color?, but the main answer definitively says that setForeground is ignored on Windows, which isn't true in XP. Also, our problem doesn't seem to be limited to Buttons. Same issues happen with Groups as well.

Apparently, a hacky work-around exists by adding a paint listener that manipulates the GC directly to redraw the text with the appropriate color, besides being hacky, this is not practical, because it would mean we had to add this listener to the thousands places where we use Buttons.
Thanks for any help.

A: This doesn't have anything to do with your system settings. It's just that, as you have guessed, something has changed between XP and 7. Actually, it changed between XP and Vista. Unfortunately there is not much you can do about this, except for the hack that you have mentioned.
For more information, see this bug report.

A: Further investigation reveals that this is not a difference between XP and Windows 7, but rather the Classic theme vs the Aero or XP theme. If we use the XP theme in XP, Button foreground also cannot be set.


text:
Q: how to testfor a player that selected an item? How to use the scoreboard command to testfor for a player that selected a snowball, namely "Blast" in Minecraft 1.9?

A: The SelectedItem compound holds a copy of the player's currently-held item (minus the Slot tag). All item data that is not the root id, Damage, Count, or Slot, must be placed within a single tag compound.
/scoreboard players set @a OBJ 0
/scoreboard players set @a OBJ 1 {SelectedItem:{id:"minecraft:snowball",tag:{display:{Name:"Blast"}}}}

/say Players holding the item: @a[score_OBJ_min=1]

As of 1.9 you will want to use "tags" instead of scores when labeling the player, which is more efficient and does not require an objective:
/scoreboard players tag @a[tag=holding] remove holding
/scoreboard players tag @a add holding {SelectedItem:{id:"minecraft:snowball",tag:{display:{Name:"Blast"}}}}

/say Players holding the item: @a[tag=holding]


text:
Q: Make image caption cover the entire image on hover Currently I am using css in squarespace to try and make image captions cover the entire image on hover, but because of some of squarespace's code I can make it cover the bottom portion of the image.
Here is the website page I am editing:
https://baikart.com/3rdall
And here is the code I have so far to change the caption:
.sqs-block-image .image-block-outer-wrapper.layout-caption-overlay-hover .image-caption-wrapper {
    position: absolute;
    color:#fff;
    top: 0%;
    bottom: 10%;
    left: 0%;
    right: 0%;
    opacity: 0;
    transition: all .5s ease;
    transform: translate(-0%,-0%);
    -webkit-transform: translate(-0%,-0%);
    -ms-transform: translate(-0%,-0%);
    -moz-transform: translate(-0%,-0%);
}

Thank you in advance!

A: Remove max-height from here
.sqs-block-image .image-block-outer-wrapper.layout-caption-overlay-hover:hover .image-caption-wrapper {
    max-height: 75%;
}

and set height: 100%.

A: When you look using element inspector in chrome dev tools or something you can see that there is a max-height: 75% being applied to the caption class. You would need to change this to 100% in your css.
This is what is in element inspector
.sqs-block-image .image-block-outer-wrapper.layout-caption-overlay-hover:hover .image-caption-wrapper {
    max-height: 75%;
    opacity: 1;
    visibility: visible;
}


text:
Q: TextBlock justify is broken, how to justify a text? I have a text which I want it to be justified.
in a TextBlock like this:
<TextBlock Width="Auto" TextAlignment="Justify"/>

it says it is not supported.
How can I justify a text, in a TextBlock or another control?

A: You can workaround it using RichTextBox control:
<RichTextBox TextAlignment="Justify" IsReadOnly="True">
    <Paragraph>
        Put your text here
    </Paragraph>
</RichTextBox>


text:
Q: composed mysql query working but if parametrized in mysqli don't working I have a search page with 3 terms (seach parameter, postal code, and type of activity)
I have done a function to compose the sql: (this is not the real function, just a simplified one). You can use it with the parameter(s) that you want to filter or without parameter to get all.
function get_items($search="",$postal_code="",$activity=""){
global $db; //this is the $db=new mysqli(...) in other include file
$where="";
if ($s!=""){
    $s="%".$search."%";
    $where=" AND ((item.name like '".$s."') OR (item.description like '".$s."'))";
}
if($postal_code!=""){
    if (strlen($postal_code)==5){
         $where=" AND (item.postal_code like '".$postal_code."')";
    }
}

if($activity!=""){
    if (m_is_integer($postal_code)){ //m_is_integer returns true if is an integer
         $where=" AND (item.activity =".$activity.")";
    }
}
$sql="select ....... from -..... where .....".$where." order by ......"
//yes, I know I don't need to prepare the query
$stmt=$db->prepare($sql);
$result=$stmt->execute();
$stmt->store_result();
$item_array=Array();
if (($result!=false) && ($stmt->num_rows>0)){
     //do things and populate the array $item_array
}
$stmt->close();
return $item_array;
}

This functions works, The sql is right composed, you put any parameter or none and return an array of items.
I want to make the parametrized query, and this is my approach:
function get_items_parametrized($search="",$postal_code="",$activity=""){
global $db; //this is the $db=new mysqli(...) in other include file
$where="";
$bind_array=Array();
if ($s!=""){
    $s="%".$search."%";
    $where=" AND ((item.name like ?) OR (item.description like ?))";
    $bii=Array("s",$s);
    $bind_array[]=$bii;
    $bii=Array("s",$s);
    $bind_array[]=$bii;
}
if($postal_code!=""){
    if (strlen($postal_code)==5){
         $where=" AND (item.postal_code like ?)";
         $bii=Array("s",$postal_code); //yes, is a string in the database
         $bind_array[]=$bii;
    }
}

if($activity!=""){
    if (m_is_integer($postal_code)){ //m_is_integer returns true if is an integer
         $where=" AND (item.activity = ?)";
         $bii=Array("i",$activity);
         $bind_array[]=$bii;
    }
}
$sql="select ....... from -..... where .....".$where." order by ......"
$stmt=$db->prepare($sql);
//go to bind data to search
$bind_type="";
$bind_params=Array();

foreach($bind_array as $b){
    $bind_type.=$b[0];
    $bind_params[]=$b[1];
    /* Approach 1: */
    $stmt->bind_param($b[0],$b[1]);
}
/* Approach 2: */
$stmt->bind_param($bind_type,$bind_params);
$result=$stmt->execute();
$stmt->store_result();
$item_array=Array();
if (($result!=false) && ($stmt->num_rows>0)){
     //do things and populate the array $item_array
}
$stmt->close();
return $item_array;
}

This function is always returning an empty $item_array Array () not an Array(Array(),Array()) that will be possible if I don't bind the results ok, the execute is not returning any results.
I also tried to do:
/* attempt 3 */
$data=Array();
$data[0]="";
foreach($bind_array as $b){
    $data[]=$b1;
    $bind_type.=$b[0];
}
$data[0]=$bind_type;

To compose an array like ('ssi',$s,$postal_code,$activity) to call to call_user_func_array():
call_user_func_array(array(&$stmt, 'bind_param'), $data);

I also try:
call_user_func_array(array($stmt, 'bind_param'), $data);

And this approach is still returning no data.
What can I try now to make it work with parametrized querys?
Any help will be welcome :D

A: The answer is simple: don't use mysqli with prepared statements.
It's unusable with prepared statements.
Use PDO instead.
This is the answer. Mysqli is your problem and you have to solve it.
With PDO your code will be 3 times shorter and working.
If you want to stick with mysqli, another way would be to get rid of prepared statements and implement your own placeholders, but some knowledge required. However, it will let you build conditional queries easier:
$w = array();
$where = '';
if ($one) $w[] = $db->parse("one = ?s",$one);
if ($two) $w[] = $db->parse("two IN (?a)",$two);
if ($tre) $w[] = $db->parse("tre <= ?i",$tre);
if (count($w)) $where = "WHERE ".implode(' AND ',$w);
$data = $db->getArr("SELECT * FROM table ?p LIMIT ?i,?i",$where, $start,$per_page);


text:
Q: Equation for the normal derivative of the solution of Poisson's equation The solution of Poisson's equation
\begin{align*}
\Delta u  &= 0 ~~~\text{in } B_r \\
u &= g~~~\text{in } \partial B_r,
\end{align*}
is well known. For some $a\in\Bbb R\setminus \{0\}$ we have
$$
u(x) = \frac{r^2-|x|^2}{a} \int_{\partial B_r} \frac{g(y)}{|x-y|^n}dS(y).
$$
Does there exist a constant $c\in\mathbb{R}^+$  such that
$$\partial_\nu u = c\, u~~~\text{in }\partial B_r\,?$$


text:
Q: Draw Line from Session Open in an Opening Range I am new to pine and managed to Frankenstein the code below based on other open source data I found. It's an opening range indicator and as of now, seems to work quite well. One thing I would like to add but can't figure it out: how to plot a line with a label ('Session Open', for example) on the open of the session, and limit its extension to the duration of the session. Would this be possible?
Thanks in advance!
//@version=5
indicator('Open Range Study', shorttitle='Open Range', overlay=true)

london = input.session(title='London Session', defval='0300-1300')
LD = time('D', london)

////////////////// London

showLON = input(true, title='Show London Session?')
showHistoricalORB = input(true, title='Show historical ORB')

orbTimeFrame = input.timeframe('60', title='Opening Range Length')

// Get High & Low
getSeries(_e, _timeFrame) =>
    request.security(syminfo.tickerid, _timeFrame, _e, lookahead=barmerge.lookahead_on)

is_newbar(res, sess) =>
    t = time(res, sess)
    na(t[1]) and not na(t) or t[1] < t

newbar = is_newbar('D', london)

var float orbH = na
var float orbL = na
if newbar
    orbH := getSeries(high[1], orbTimeFrame)
    orbL := getSeries(low[1], orbTimeFrame)
    orbL

orbA = (orbH + orbL) / 2
orbPrevDayHigh = getSeries(high[1], 'D')
orbPrevDayLow = getSeries(low[1], 'D')
orbPrevDayOpen = getSeries(open[1], 'D')
orbPrevDayClose = getSeries(close[1], 'D')

// Today's Session Start timestamp
y = year(timenow)
m = month(timenow)
d = dayofmonth(timenow)

// Start & End time for Today
start = timestamp(y, m, d, 09, 15)
end = start + 86400000
london_session = na(LD) ? na : color.green
isToday = timenow > start
P1 = plot(showHistoricalORB and showLON and LD ? orbH : na, title='London Open High', color=color.new(color.lime, 100))
P2 = plot(showHistoricalORB and showLON and LD ? orbL : na, title='London Open Low', color=color.new(color.lime, 100))

orbcolor1 = color.green
fill(P1, P2, color = orbcolor1, title="London Opening Range")


text:
Q: Unable to login in EC2 instance from github repo via gitaction I have an EC2 instance with a downloaded repository that runs some commands via githubaction.
I get the following error and can't seem to understand what I need to do.
Here is my github action
name: Deploy to x-web

on:
  push:
    branches: [ master ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout
      uses: actions/checkout@v2

    - name: Register Private Key
      uses: webfactory/ssh-agent@v0.5.4
      with:
          ssh-private-key: ${{ secrets.PRIVATE_KEY }}

    - name: Deploy to EC2
      env:
        HOSTNAME : XX.XX.X.XX
        USER_NAME : ec2-user
      run: |
          ssh -o StrictHostKeyChecking=no ${USER_NAME}@${HOSTNAME} '
          cd ./x-web
          eval $(ssh-agent -s)
          ssh-add /home/ec2-user/.ssh/github
          git checkout -b foo
          git branch -D master
          git checkout -b master origin/master-f
          git fetch --all -f &&
          git pull origin master -f &&
          git branch -D foo
          npm i --force && npm run build &&
          pm2 restart Frontend
          '

The error that I get is the following ....
Agent pid 16351
Identity added: /home/ec2-user/.ssh/github (/home/ec2-user/.ssh/github)
fatal: a branch named 'foo' already exists
error: Cannot delete branch 'master' checked out at '/home/ec2-user/x-web'
fatal: a branch named 'master' already exists
fatal: could not read Username for 'https://github.com': No such device or address
npm WARN using --force Recommended protections disabled.
...

A: I don't quite follow what you are try to achieve, but to help you with a few of the errors:
fatal: a branch named 'foo' already exists is caused by your use of the -b flag which will attempt to create a new branch, but it looks like your repo has one already. Use git checkout foo instead to switch to it.
error: Cannot delete branch 'master' checked out at '/home/ec2-user/x-web' since your checkout failed you didn't switch off of master and you cant delete the branch you are on.
fatal: could not read Username for 'https://github.com': No such device or address I'm not 100% sure of but I suspect that in your manipulation of ssh or setting of env HOSTNAME or USER_NAME has caused this I would also recommend updating your first step to actions/checkout@v3

A: If git version on your ECS is recent enough (2.23 or more), use git switch instead of git checkout.
That way you can replace
git checkout -b foo
git branch -D master
git checkout -b master origin/master-f

with:
git switch -C foo
git switch -f -C master origin/master

Also check your git remote -v on that instance. If it starts with https://, your SSH key would not be used at all.
A git config --global url.git@github.com:.insteadOf https://github.com/ would help ensuring you are using SSH.
(Or, if you know the full URL, git remote set-url origin git@github.com:<user>/<repo>)


text:
Q: C# Mocking a function I need to mock a method from the google calendar api. But it gives an error everytime. I have the following code.
        DateTime dateTimeNow = new DateTime(2018, 10, 10, 10, 10, 10);
        Event events = new Event
        {
            Id = "EventA",
            Summary = "Summary",
            Description = "Desc",
            Start = new EventDateTime { Date = "2018-10-10", DateTime = dateTimeNow},
            End = new EventDateTime { Date = "2018-10-10", DateTime = dateTimeNow.AddHours(1) },
        };

        Mock<CalendarService> fakeCalendarService = new Mock<CalendarService>();
        fakeCalendarService
            .Setup(x => x.Events.Insert(It.IsAny<Event>(), It.IsAny<string>()).Execute())
            .Returns(events);

I get the following error message:
Message: System.NotSupportedException : Invalid setup on a non-virtual (overridable in VB) member: x => x.Events.Insert(It.IsAny<Event>(), It.IsAny<String>()).Execute()

I was able to mock other functions but this function:
_service.Events.Insert(newEvent, _calendarId).Execute();

has .Execute() behind it. Because of this statement I don't know how to mock it.


text:
Q: Qt Multimedia API and video decode I'm looking to Qt Multimedia API becouse I want to show the same video on 2 different widget. After hacking a little bit the boundled "videographicsitem" example it works using 2 GraphicsView. But this example use QMovie to decode gif, I want to decode avi, mp4, etc.
What can I use to replace QMovie?
Is the multimedia API supported on every platform?

A: The Qt 4.6 videographicsitem example uses QMovie to decode video, though it only supports animated gifs. More extensive support for video codecs is available in the Qt Phonon multimedia framework, which uses directshow on Windows, gstreamer on Linux, and quicktime on Mac OS X.
It is not obvious to me how to use Phonon as a replacement for QMovie in the videographicsitem, but you can use Phonon alone to build a video player.
QMultimedia seems to be a work in progress. Given what it is doing, it seems likely that it will gain the functionality you are looking for. This could be helped by submitting feature requests or implementing some of the missing pieces.


text:
Q: Keeping javascript from endlessly appending dom I have a javascript that adjusts the dom depending on the JSON response it receives for each field. an example is:
    if (data.errors.firstName) {
        document.getElementById("firstName-group").classList.add("has-error");
        let helpBlock = document.createElement('div');
        helpBlock.classList.add('help-block');
        helpBlock.innerHTML = data.errors.firstName;
        document.getElementById("firstName-group").append(helpBlock);
    }

The problem here is that this will result in the dom being repeatedly appending like so:
image
so how do I avoid this issue when appending the dom? should this clear out any appended messages already? or how to accomplish this?

A: You can can check if the #firstName-group element has already the .help-block div under it, and only append if it doesn't.
Here is an example:
if (data.errors.firstName && !document.querySelector('#firstName-group .help-block')) {
    document.getElementById("firstName-group").classList.add("has-error");
    let helpBlock = document.createElement('div');
    helpBlock.classList.add('help-block');
    helpBlock.innerHTML = data.errors.firstName;
    document.getElementById("firstName-group").append(helpBlock);
}


text:
Q: mongoDB Regex Scan Optimization - Suffix based? Okay, so I have a collection full of folks' emails. I want to efficiently look up the domain of the email without altering the existing data.
Currently I can look up the username SUPER fast since it's a regex scan that is prefix based, my collection is about 1GB+ in size and my server isn't super powerful. I do have an index on "Email".
The fast query is something like:
db.emails.find({"Email": {'$regex':'^johnsmith'}})
My index is simple and looks like this:
db.emails.createIndex({ Email: 1 })
However, if I try to find the domain, I have to use a non-prefixed regex scan like this, but this results in a query that still uses the index, but takes about 10-20x more time:
db.emails.find({"Email": {'$regex':'sampledomain.com'}})
I've tried using a suffix instead of a prefix like this, but still just as slow:
db.emails.find({"Email": {'$regex':'sampledomain.com&'}})
I'm not sure if there's some sort of index I can make just on the domain portion of the email, but I'm pretty new to mongoDB so any advice would be appreciated.

A: If you are searching from the beginning of domain, you can extract the domain and store it in another field, at which point you'd be able to use prefix regexp match on that field.


text:
Q: Push notification is not working with iOS9 and above I have tried these bellow ways:

*

*I noticed was the Device Token gets changed for every fresh install which is kind of weird as we have to update the server for every new instance. Now i have fixed with save UUID in keychains.

*I have created development provision and check. But not getting any luck.

*I have created Adhoc provision and check. But still not getting PN.

A: Depending on how you distribute your app you may either be on the sandbox or the production server. Your token will only work for the server that the app is provisioned for.
Additionally, the machine that you're sending push notifications from will need to have the correct certificate and key to interaction with the APNS servers.
One thing to watch out for is using the same Certificate Signing Request for both the development and production APNS certs, some services won't properly send if they detect the wrong certificates in a .p12 file and keychain access will export more than two items if you used the same CSR.


text:
Q: How to match the first part of string with the two same substring? I have text as below,
<meta name="description" content="28日からは「天地始粛(てんちはじめてさむし)」。 「粛」にはおさまる、弱まる等の意味があり、夏の暑さもようやく落ち着いてくる頃とされています。">
<meta name="Keywords" content="天気,天気予報,気象,情報,台風,地震,津波,週間,ウェザー,ウェザーニュース,ウェザーニューズ,今日の天気,明日の天気"><meta property="og:type" content="article">
<meta property="og:title" content="【天地始粛】音や景色から感じる秋の気配"><meta property="og:description" content="28日からは「天地始粛(てんちはじめてさむし)」。 「粛」にはおさまる、弱まる等の意味があり、夏の暑さもようやく落ち着いてくる頃とされています。"><meta property="og:url" content="https://weathernews.jp/s/topics/201807/300285/">
<meta property="og:image" content="https://smtgvs.weathernews.jp/s/topics/img/201807/201807300285_sns_img_A.jpg?1532940869">
<meta name="twitter:title" content="【天地始粛】音や景色から感じる秋の気配">
<meta name="twitter:description" content="28日からは「天地始粛(てんちはじめてさむし)」。 「粛」にはおさまる、弱まる等の意味があり、夏の暑さもようやく落ち着いてくる頃とされています。"><meta name="twitter:image" content="https://smtgvs.weathernews.jp/s/topics/img/201807/201807300285_sns_img_A.jpg?1532940869">
<link rel="canonical" href="https://weathernews.jp/s/topics/201807/300285/">
<link rel="amphtml" href="https://weathernews.jp/s/topics/201807/300285/amp.html">
<script async="async" src="https://www.googletagservices.com/tag/js/gpt.js">

I used pattern = re.compile(r'(https://smtgvs.weathernews.jp/s/topics/img/[0-9]+/.+)\?[0-9]+') to match it, and I want to get https://smtgvs.weathernews.jp/s/topics/img/201807/201807300285_sns_img_A.jpg, but I got
https://smtgvs.weathernews.jp/s/topics/img/201807/201807300285_sns_img_A.jpg?1532940869"><meta name="twitter:title" content="【天地始粛】音や景色から感じる秋の気配"><meta name="twitter:description content="28日からは「天地始粛(てんちはじめてさむし)」。 「粛」にはおさまる、弱まる等の意味があり、夏の暑さもようやく落ち着いてくる頃とされています。"><meta name="twitter:image" content="https://smtgs.weathernews.jp/s/topics/img/201807/201807300285_sns_img_A.jpg

how can I modify my Regex pattern?

A: You may try this:
this captures the url until it reaches file extensions[inclusive],
(https:\/\/smtgvs\.weathernews\.jp\/s\/topics\/img\/\d+\/\w+\.[jpng]{3})

demo


text:
Q: How to change inactive tab colour background on click I'm not well-versed in HTML and CSS but basically, I have a page with tabs. When I click a button I want the colour scheme to change, including the original background colour of the button container.

        <button class="buttonnorm tablinks" onclick="openTab(event, 'Tab 1')"
        id="defaultOpen">

            usagi tsukino

            sailor moon

        </button>

        <button class="button2 tablinks" onclick="openTab(event, 'Tab 2')">

            ami mizuno

            sailor moon

        </button>

If I try to create a separate div thing [meaning a btncontainer2] with a different colour background, how can I implement this to change upon opening the tab?
If you need to see what I've got so far, I'm only worried about the tab group on the left. Let me know if any more info is needed.
https://glaceontea.tumblr.com/mediatest
https://pastebin.com/8wsEjavY

A: Are you using JavaScript as well on your website? This would be the easiest to add onClick() listener for that button, find your button with getElementsByClassName (Maybe consider adding ID to buttons if you want to target them easier with getElementByID) and then change the css attributes through JavaScript.
Let me know if this will work or you need help on the implementation

A: If you add a common class to all the tabcontent type div elements you can simplify the javascript considerably and make it applicable to any number of tabs/buttons with no headaches when registered as an external event listener.
Here I used .tab as the common className so that I could easily identify these tabs ( it is just one of several ways of identifying these elements btw ) and assign an event listener to each button identified using querySelectorAll

document.querySelectorAll('#btncontainer button').forEach( (bttn,index)=>bttn.addEventListener('click',function(e){

  let i=index+1;
  let expr='Tab '+i;

  // hide all elements of class `tab`
  let col=document.querySelectorAll('.tab');
  col.forEach( n=>n.style.display='none' );

  // set current tab as visible block
  document.getElementById(expr).style.display='block';

  // find and remove active class from all relevant nodes
  col=document.querySelectorAll('.tablinks');
  col.forEach( n=>n.classList.remove('active') );

  // apply background colour to button parent and assign current button as `active`
  e.currentTarget.parentNode.className='CUSTOM_BACKGROUND_'+i;

  e.currentTarget.classList.add('active');
}));
.CUSTOM_BACKGROUND_1{
  background:#8494A9!important;
}
.CUSTOM_BACKGROUND_2{
  background:#B1F0F9!important;
}
.CUSTOM_BACKGROUND_3{
  background:#BAE6C3!important;
}
.CUSTOM_BACKGROUND_4{
  background:#ECB1F5!important;
}

.tmblr-iframe {
    filter: invert(100%);
    -o-filter: invert(100%);
    -moz-filter: invert(100%);
    -ms-filter: invert(100%);
    -webkit-filter: invert(100%);
    opacity: 0.2;
    position: fixed;
    right: 5px;
    top: 5px;
    transform: scale(0.7,0.7);
    transform-origin: 100% 0%;
    -ms-transform-origin: 100% 0%;
    -webkit-transform-origin: 100% 0%;
    transition: 0.4s;
    -o-transition: 0.4s;
    -moz-transition: 0.4s;
    -ms-transition: 0.4s;
    -webkit-transition: 0.4s;
    white-space: nowrap;
}

.tmblr-iframe:hover {
    opacity: 1;
}

/* ----------------------------------------------------------------------- */
/* --------------------------- custom tooltips --------------------------- */

.tippy-tooltip.custom-theme {
    background-color: #ee959e;
    border-radius: 0;
    color: #ffffff;
    font-family: inherit;
    font-size: inherit;
    text-align: center;
}

/* ----------------------------------------------------------------------- */
/* -------------------- custom selection & scrollbar --------------------- */

::-moz-selection {background: #ee959e; color: #ffffff;}
::selection {background: #ee959e; color: #ffffff;}

::-webkit-scrollbar-thumb
{background: #fab1b9; border: 5px solid #ffffff; border-radius: 10px;}
::-webkit-scrollbar-track
{background: #141414; border: 7px solid #ffffff;}
::-webkit-scrollbar
{width: 15px;}

/* ----------------------------------------------------------------------- */
/* ----------------------------- page layout ----------------------------- */

body {
    background: #ffffff;                /* background color */
    color: #141414;                     /* text color */
    font-family: Poppins;               /* font */
    font-size: 15px;                    /* font size */
    letter-spacing: 0.025em;            /* text letter spacing */
    line-height: 160%;                  /* text line height */
    text-align: justify;                /* text align */
}

#container {                            /* content container */
    height: 620px;
    margin: 50px auto;
    max-width: 1000px;
    width: 90%;
}

/* ----------------------------------------------------------------------- */
/* --------------------------------- tabs -------------------------------- */

#btncontainer {                         /* button container */
    background-color: #fab1b9;
    float: left;
    height: 100%;
    overflow: auto;
    width: 200px;
    -moz-overflow-style: none;
    -ms-overflow-style: none;
    -o-overflow-style: none;
}

#btncontainer4 {                         /* button container 4 */
    background-color: #4d8f5f;
    float: left;
    height: 100%;
    overflow: auto;
    width: 200px;
    -moz-overflow-style: none;
    -ms-overflow-style: none;
    -o-overflow-style: none;
}

.tabcontent {                           /* tab container */
    background-color: #f6f2fc;
    display: none;
    float: right;
    height: calc(100% - 40px);
    height: -moz-calc(100% - 40px);
    height: -webkit-calc(100% - 40px);
    overflow: none;
    padding: 20px;
    width: calc(100% - 200px - 40px);
    width: -moz-calc(100% - 200px - 40px);
    width: -webkit-calc(100% - 200px - 40px);
}

.tabcontent2 {                           /* tab container 2 */
    background-color: #adcdf0;
    display: none;
    float: right;
    height: calc(100% - 40px);
    height: -moz-calc(100% - 40px);
    height: -webkit-calc(100% - 40px);
    overflow: none;
    padding: 20px;
    width: calc(100% - 200px - 40px);
    width: -moz-calc(100% - 200px - 40px);
    width: -webkit-calc(100% - 200px - 40px);
}

.tabcontent3 {                           /* tab container 3 */
    background-color: #caadf0;
    display: none;
    float: right;
    height: calc(100% - 40px);
    height: -moz-calc(100% - 40px);
    height: -webkit-calc(100% - 40px);
    overflow: none;
    padding: 20px;
    width: calc(100% - 200px - 40px);
    width: -moz-calc(100% - 200px - 40px);
    width: -webkit-calc(100% - 200px - 40px);
}

.tabcontent4 {                           /* tab container 4*/
    background-color: #dcf7e3;
    display: none;
    float: right;
    height: calc(100% - 40px);
    height: -moz-calc(100% - 40px);
    height: -webkit-calc(100% - 40px);
    overflow: none;
    padding: 20px;
    width: calc(100% - 200px - 40px);
    width: -moz-calc(100% - 200px - 40px);
    width: -webkit-calc(100% - 200px - 40px);
}

.buttonnorm {                  /* buttons */
    background-color: inherit;
    border: none;
    color: #ffffff;
    cursor: pointer;
    display: block;
    font-family: inherit;
    font-size: inherit;
    margin: 0;
    outline: none;
    padding: 10px 15px;
    text-align: justify;
    width: 100%;
}

.button2 {                  /* button 2 */
    background-color: inherit;
    border: none;
    color: #ffffff;
    cursor: pointer;
    display: block;
    font-family: inherit;
    font-size: inherit;
    margin: 0;
    outline: none;
    padding: 10px 15px;
    text-align: justify;
    width: 100%;
}

.button3 {                  /* button 3 */
    background-color: inherit;
    border: none;
    color: #ffffff;
    cursor: pointer;
    display: block;
    font-family: inherit;
    font-size: inherit;
    margin: 0;
    outline: none;
    padding: 10px 15px;
    text-align: justify;
    width: 100%;
}

.button4 {                  /* buttons */
    background-color: inherit;
    border: none;
    color: #ffffff;
    cursor: pointer;
    display: block;
    font-family: inherit;
    font-size: inherit;
    margin: 0;
    outline: none;
    padding: 10px 15px;
    text-align: justify;
    width: 100%;
}

/* active button and hover */

.buttonnorm:hover, .buttonnorm.active{
    background-color: #ee959e;
}

.button2:hover, .button2.active{
    background-color: #6185ab;
}
.button3:hover, .button3.active{
    background-color: #8161ab;
}
.button4:hover, .button4.active{
    background-color: #7fc993;
}

.buttonnorm::-webkit-scrollbar {display: none;}
.chaname {font-size: 1.2em; text-transform: uppercase;}
.chasubtitle {font-size: 0.9em; font-style: italic; padding-left: 20px;}

/* ----------------------------------------------------------------------- */
/* ------------------------------- content ------------------------------- */

#leftcontent {                          /* left content in tab */
    float: left;
    height: calc(100% - 40px);
    height: -moz-calc(100% - 40px);
    height: -webkit-calc(100% - 40px);
    padding: 20px;
    width: calc(100% - 250px - 40px - 20px);
    width: -moz-calc(100% - 250px - 40px - 20px);
    width: -webkit-calc(100% - 250px - 40px - 20px);
}

#linkbox {                              /* top left link and quote box */
    border-bottom: none;
    border-radius: 20px;
    height: 180px;
    margin-left: -20px;
    margin-top: 20px;
    width: calc(100% + 40px);
    width: -moz-calc(100% + 40px);
    width: -webkit-calc(100% + 40px);
}

#quote {                                /* quote box */
    background-color: #ffffff;
    border-radius: 20px 20px 0px 0px;
    height: 65px;
    padding: 30px;
    text-align: center;
}

#quote i {                              /* quote icons */
    color: #fab1b9;
    font-size: 25px;
    margin: 0px 10px;
}

#quote2 i {                              /* quote icons */
    color: #3d76b3;
    font-size: 25px;
    margin: 0px 10px;
}
#links {                                /* link bar */
    background-image: linear-gradient(to bottom right, #fab1b9, #ee959e);
    border-radius: 0px 0px 20px 20px;
    display: flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-box;
    display: -webkit-flex;
    height: 25px;
    justify-content: space-between;
    padding: 15px;
}
#links2 {                                /* link bar 2*/
    background-image: linear-gradient(to bottom right, #3d76b3, #09407a);
    border-radius: 0px 0px 20px 20px;
    display: flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-box;
    display: -webkit-flex;
    height: 25px;
    justify-content: space-between;
    padding: 15px;
}

#links a {                              /* links */
    color: #ded9da;
    font-size: 19px;
}
#links2 a {                              /* links2 */
    color: #ded9da;
    font-size: 19px;
}

#links a:hover {                        /* links hover */
    color: #ff7a95;
    transform: scale(1.4);
    -moz-transform: scale(1.4);
    -ms-transform: scale(1.4);
    -o-transform: scale(1.4);
    -webkit-transform: scale(1.4);
}

#links2 a:hover {                        /* links2 hover */
    color: #23384f;
    transform: scale(1.4);
    -moz-transform: scale(1.4);
    -ms-transform: scale(1.4);
    -o-transform: scale(1.4);
    -webkit-transform: scale(1.4);
}

#bio {                                  /* bio section */
    margin-left: -20px;
    margin-top: 20px;
    height: calc(100% - 220px);
    height: -moz-calc(100% - 220px);
    height: -webkit-calc(100% - 220px);
    overflow: auto;
    width: calc(100% + 40px);
    width: -moz-calc(100% + 40px);
    width: -webkit-calc(100% + 40px);
    -moz-overflow-style: none;
    -ms-overflow-style: none;
    -o-overflow-style: none;
}

/* gives links in bio section a bottom border */

#bio a {border-bottom: 3px solid #fab1b9;}
#bio a:hover {border-bottom: 3px solid #ee959e;}

#facts {                                /* right bottom info */
    height: calc(100% - 270px);
    height: -moz-calc(100% - 270px);
    height: -webkit-calc(100% - 270px);
    line-height: 139%;
    margin-top: 20px;
    overflow: none;
}

img:hover {cursor: cell;}
img {border-radius: 20px; width: 250px;}
#bio::-webkit-scrollbar {display: none;}
.answer {float: right; margin-left: 7px;}
#rightcontent {float: right; height: 100%; width: 250px;}
.prompt {background-color: #ee959e; border-radius: 10px; padding: 5px 8px;}

/* ----------------------------------------------------------------------- */
/* -------------------------------- text --------------------------------- */

h1 {                                    /* character name */
    font-size: 2.2em;
    font-weight: normal;
    overflow-x: scroll;
    text-align: center;
    text-transform: uppercase;
    white-space: nowrap;
    -moz-overflow-style: none;
    -ms-overflow-style: none;
    -o-overflow-style: none;
}

a {
    color: #fab1b9;                     /* link color */
    text-decoration: none;
}

a2 {
    color: #3d76b3;                     /* link2 color */
    text-decoration: none;
}
a:hover {
    color: #ee959e;                     /* link hover color */
}
a2:hover {
    color: #09107a;                     /* link2 hover color */
}

.firstword {color: #ee959e;}
h1::-webkit-scrollbar {display: none;}

/* ----------------------------------------------------------------------- */
/* ---------------------------- transitions ------------------------------ */

a, a:hover, a2, a2:hover #credit, #credit:hover, button, button:hover, button4, button4:hover{
    transition: 0.4s;
    -moz-transition: 0.4s;
    -ms-transition: 0.4s;
    -o-transition: 0.4s;
    -webkit-transition: 0.4s;
}

/* ----------------------------------------------------------------------- */
/* ----------------------------- responsive ------------------------------ */

@media only screen and (max-width: 900px){
    #quote {height: 95px;}
    #linkbox {height: 210px;}

    #bio {
        height: calc(100% - 270px);
        height: -moz-calc(100% - 270px);
        height: -webkit-calc(100% - 270px);
    }
}

@media only screen and (max-width: 800px){
    #quote {height: 65px;}
    #linkbox {height: 180px;}
    #rightcontent {margin-top: 20px;}
    .tabcontent::-webkit-scrollbar {display: none;}
    #leftcontent, #rightcontent {float: none; width: calc(100% - 40px);}

    .tabcontent {
        overflow: auto;
        -moz-overflow-style: none;
        -ms-overflow-style: none;
        -o-overflow-style: none;
    }
    .tabcontent2 {
        overflow: auto;
        -moz-overflow-style: none;
        -ms-overflow-style: none;
        -o-overflow-style: none;
    }
    .tabcontent3 {
        overflow: auto;
        -moz-overflow-style: none;
        -ms-overflow-style: none;
        -o-overflow-style: none;
    }
    .tabcontent4 {
        overflow: auto;
        -moz-overflow-style: none;
        -ms-overflow-style: none;
        -o-overflow-style: none;
    }

    #bio {
        height: calc(100% - 220px);
        height: -moz-calc(100% - 220px);
        height: -webkit-calc(100% - 220px);
    }

    img {
        width: calc(100% + 40px);
        width: -moz-calc(100% + 40px);
        width: -webkit-calc(100% + 40px);
    }
}

/* ----------------------------------------------------------------------- */
/* ------------------------------- credits ------------------------------- */

#credit {
    background-color: #ffffff;
    color: #fab1b9;
    bottom: 0;
    font-size: 20px;
    font-style: italic;
    margin: 10px;
    padding: 10px 0px;
    position: fixed;
    right: 0;
    text-align: center;
    width: 40px;
}

#credit:hover {
    background-color: #fab1b9;
    color: #ffffff;
}

  <button class="buttonnorm tablinks active" id="defaultOpen">
    usagi tsukino

    sailor moon
  </button>
  <button class="button2 tablinks">
    ami mizuno

    sailor moon
  </button>
  <button class="button3 tablinks">
    rei hino

    sailor moon
  </button>
  <button class="button4 tablinks">
    makoto kino

    sailor moon
  </button>

usagi tsukino

            girls have to be strong to protect the men they love

senshi namesailor moon

age14

genderfemale

sexualitybisexual

alignmentchaotic good

zodiaccancer

birthdayjune 30

height1.5 m

ami mizuno

            be pure, be honest, be beautiful

senshi namesailor mercury

age14

genderfemale

sexualityasexual

alignmentlawful neutral

zodiacvirgo

birthdayseptember 10

height1.57 m

rei hino

            i shall punish those who steal pure hearts to destroy innocent lives with the fire of mars

senshi namesailor mars

age14

genderfemale

sexualityheterosexual

alignmenttrue neutral

zodiacaries

birthdayapril 17

height1.6 m

makoto kino

            how dare you destroy my precious lunch box! | I'll make you feel regret, it'll leave you numb!

senshi namesailor jupiter

age14

genderfemale

sexualitypansexual

alignmentlawful good

zodiacsagittarius

birthdaydecember 5

height1.67 m


text:
Q: Dwarf Fortress military and bedroom issues? I had a working single squad military, I added another squad and a burrow to defend and I put the squads into a rotation of training one month and defending the next.  The training group just hangs around the barraks and has the not solid smiley face icon.  And the groups seem to have the wrong activity setting (it doesnt match the scedule).  Is there anything obvious that I am doing wrong?
edit: Both squads are using the same barraks, is this an issue?
When I make a bedroom I press f for free.  Only 2 of my 50 bedrooms have owners.  Am I doing something wrong?  When I make a bedroom then go back to the bed I still have the option of making a bedroom, did I make it wrong?

A: "Freeing" the bed, or any furniture, means making it free of the room. That is, it removes the room you just made. You just have to choose a room size with r. After that, a dwarf will take the room for himself (and eventually his spouse) as soon as he gets sleepy.
The reason two of your bedrooms have owners is probably that you forgot to press f.
I suppose you set the schedule for their "Active/Training" alert. You can check that in the military-schedule screen; the alert that you're editing is in the title and can be changed with /*. Make sure that they're actually in that alert: go to the squads screen, mark each squad (a or b) and press t until the right alert is chosen.


text:
Q: NER types for 'en' model? Is there a way to get all the built-in and added custom NER types in spaCy? The method suggested here doesn't seem to work anymore. On trying
nlp.entity.cfg

I get back,
{u'hist_size': 0, u'pretrained_dims': 0L, u'hist_width': 0, u'beam_density':
0.0, u'cnn_maxout_pieces': 3, u'maxout_pieces': 2, u'hidden_depth': 1,
u'token_vector_width': 128, u'nr_class': 73, u'beam_width': 1,
u'hidden_width': 200}

There are no 'actions' and 'extra_labels' keys in this dictionary.

A: I've found another way. Works for spacy v. 3.0.5:
ner = nlp.get_pipe('ner')
print(ner.labels)

it gives the result:
('CARDINAL', 'DATE', 'EVENT', 'FAC', 'GPE', 'LANGUAGE', 'LAW', 'LOC', 'MONEY', 'NORP', 'ORDINAL', 'ORG', 'PERCENT', 'PERSON', 'PRODUCT', 'QUANTITY', 'TIME', 'WORK_OF_ART')

A: Not quite sure if this is the way it's to be done. I figured out on calling
nlp.entity.move_names

returns,
[u'B-PERSON', u'B-CARDINAL', u'B-ORG', u'B-GPE', u'B-FAC', u'B-MONEY', u'B-NORP', u'B-DATE', u'B-TIME', u'B-ORDINAL', u'B-PERCENT', u'B-PRODUCT', u'B-LANGUAGE', u'B-LOC', u'B-QUANTITY', u'B-WORK_OF_ART', u'B-EVENT', u'B-LAW', u'I-PERSON', u'I-CARDINAL', u'I-ORG', u'I-GPE', u'I-FAC', u'I-MONEY', u'I-NORP', u'I-DATE', u'I-TIME', u'I-ORDINAL', u'I-PERCENT', u'I-PRODUCT', u'I-LANGUAGE', u'I-LOC', u'I-QUANTITY', u'I-WORK_OF_ART', u'I-EVENT', u'I-LAW', u'L-PERSON', u'L-CARDINAL', u'L-ORG', u'L-GPE', u'L-FAC', u'L-MONEY', u'L-NORP', u'L-DATE', u'L-TIME', u'L-ORDINAL', u'L-PERCENT', u'L-PRODUCT', u'L-LANGUAGE', u'L-LOC', u'L-QUANTITY', u'L-WORK_OF_ART', u'L-EVENT', u'L-LAW', u'U-PERSON', u'U-CARDINAL', u'U-ORG', u'U-GPE', u'U-FAC', u'U-MONEY', u'U-NORP', u'U-DATE', u'U-TIME', u'U-ORDINAL', u'U-PERCENT', u'U-PRODUCT', u'U-LANGUAGE', u'U-LOC', u'U-QUANTITY', u'U-WORK_OF_ART', u'U-EVENT', u'U-LAW', u'O']

This also shows any additional custom entities added to the model, like u'EMAIL' in my case:
[u'B-PERSON', u'B-CARDINAL', u'B-ORG', u'B-GPE', u'B-FAC', u'B-MONEY', u'B-NORP', u'B-DATE', u'B-TIME', u'B-ORDINAL', u'B-PERCENT', u'B-PRODUCT', u'B-LANGUAGE', u'B-LOC', u'B-QUANTITY', u'B-WORK_OF_ART', u'B-EVENT', u'B-LAW', u'I-PERSON', u'I-CARDINAL', u'I-ORG', u'I-GPE', u'I-FAC', u'I-MONEY', u'I-NORP', u'I-DATE', u'I-TIME', u'I-ORDINAL', u'I-PERCENT', u'I-PRODUCT', u'I-LANGUAGE', u'I-LOC', u'I-QUANTITY', u'I-WORK_OF_ART', u'I-EVENT', u'I-LAW', u'L-PERSON', u'L-CARDINAL', u'L-ORG', u'L-GPE', u'L-FAC', u'L-MONEY', u'L-NORP', u'L-DATE', u'L-TIME', u'L-ORDINAL', u'L-PERCENT', u'L-PRODUCT', u'L-LANGUAGE', u'L-LOC', u'L-QUANTITY', u'L-WORK_OF_ART', u'L-EVENT', u'L-LAW', u'U-PERSON', u'U-CARDINAL', u'U-ORG', u'U-GPE', u'U-FAC', u'U-MONEY', u'U-NORP', u'U-DATE', u'U-TIME', u'U-ORDINAL', u'U-PERCENT', u'U-PRODUCT', u'U-LANGUAGE', u'U-LOC', u'U-QUANTITY', u'U-WORK_OF_ART', u'U-EVENT', u'U-LAW', u'O', u'B-EMAIL', u'I-EMAIL', u'L-EMAIL', u'U-EMAIL']


text:
Q: Assigning jQuery ajax response text to variable constanty returns null hopefully one of you on this great site can help. I'm having issues with assigning a variable to a jQuery ajax call response text.
I have a form which when submited runs my "checkemail" function to varify the email address can be found in a database. If it's found, the responseText == "true", else "false". This works fine, and can be seen ok using Firebug....but the actual variable the response text should be assigned to is constantly showing "", and therefore causing the function to return false all the time.
        function checkemail(){

            var EmailFromForm = $("#lostemail").val();

            var EmailCheckRes = $.ajax({

            type        : "POST",
            cache       : false,
            url         : "./scripts/passreset/emailcheck.php",
            data        : "Email="+EmailFromForm,
            dataType        : "text",

      }).responseText;

            if (EmailCheckRes == "true")
            {
                alert("Should say true:  " + EmailCheckRes);
                return true;
            }
            else
            {
                $("#ErrorMsg").html("Your email address is either invalid or not found.");
                alert("Should say false:  " + EmailCheckRes);
                return false;
            }

        }

If anyone has any pointers as to what i'm doing wrong it'd be greatly appreciated.

A: The problem is that the $.ajax method is getting executed async so the checkemail function is returning before your ajax request is completed.
The flow of your application is not linear and therefore your return value from checkmail will not reflect the response returned from your ajax request.
You'll need to restructure your code to take a callback and execute it when your ajax request is complete.

A: your ajax url needs to be the web url of emailcheck.php not a relative system path using ./
var EmailCheckRes = $.ajax({

    type        : "POST",
    cache       : false,
    async       : false,
    url         : "scripts/passreset/emailcheck.php",
    data        : "Email="+EmailFromForm,
    dataType    : "text",

    }).responseText;

EDIT : While it is not the optimal solution to switch to a synchronous server request, you might just set the ajax option async: false which will make the browser wait for the response to continue, which should eliminate your issue.  Also I would recommend switching to an absolute path, and/or removing the ./ from the front of your relative path. I have reflected this option addition to my example code.

A: You need to restructure your code. Most of the AJAX calls are async, meaning the flow of the code goes without waiting for the call to be completed.
Meaningfully, you need to change:
function checkmail() {
    var checkThis = Ajax();

    if (checkThis) {
        DoSomething();
    }
    else {
        DontDoSomething();
    }
}

for:
function checkmail() {
    Ajax.success = function(checkThis){
        if (checkThis) {
            DoSomething();
        }
        else {
            DontDoSomething();
        }
    };

    Ajax.error= function(){
        ReportSomeError();
    };

    Ajax();
}

Applied to your code, it may go something like this:
function checkemail () {
    var EmailFromForm = $("#lostemail").val(),

    $.ajax({
        type:"POST",
        cache:false,
        url:"./scripts/passreset/emailcheck.php",
        data:"Email="+EmailFromForm,
        dataType:"text",
        success:function(EmailCheckRes){
            if (EmailCheckRes == "true") {
                alert("Should say true:  " + EmailCheckRes);

                /* You cannot longer "return" this value, add code to do
                 * what you need done
                 */
                return true;
            }
            else {
                $("#ErrorMsg").html("Your email address is either invalid or not found.");
                alert("Should say false:  " + EmailCheckRes);

                /* You cannot longer "return" this value, add code to do
                 * what you need done
                 */
                return false;
            }
        },
        error:function(){
            $("#ErrorMsg").html("There was an AJAX communication error.");
        }
    });
}

A: I really struggled with getting the results of jQuery ajax into my variables at the "document.ready" stage of events.
jQuery's ajax would load into my variables when a user triggered an "onchange" event of a select box after the page had already loaded, but the data would not feed the variables when the page first loaded.
I tried many, many, many different methods, but in the end, the answer I needed was at this stackoverflow page: JQuery - Storing ajax response into global variable
Thanks to contributor Charles Guilbert, I am able to get data into my variables, even when my page first loads.
Here's an example of the working script:
jQuery.extend
(
    {
        getValues: function(url)
        {
            var result = null;
            $.ajax(
                {
                    url: url,
                    type: 'get',
                    dataType: 'html',
                    async: false,
                    cache: false,
                    success: function(data)
                    {
                        result = data;
                    }
                }
            );
           return result;
        }
    }
);

// Option List 1, when "Cats" is selected elsewhere
optList1_Cats += $.getValues("/MyData.aspx?iListNum=1&sVal=cats");

// Option List 1, when "Dogs" is selected elsewhere
optList1_Dogs += $.getValues("/MyData.aspx?iListNum=1&sVal=dogs");

// Option List 2, when "Cats" is selected elsewhere
optList2_Cats += $.getValues("/MyData.aspx?iListNum=2&sVal=cats");

// Option List 2, when "Dogs" is selected elsewhere
optList2_Dogs += $.getValues("/MyData.aspx?iListNum=2&sVal=dogs");


text:
Q: Get all inputs with type text in console? Page in iFrame How do you get all of the inputs of form on a page into an array while matching by input type(text|checkbox|radio)?

JavaScript:
Just plain js like this will give me ALL of the inputs
var inputs = document.getElementsByTagName( 'input' );

Now with jQuery:
I have jQuery loaded and I tried: as per docs (http://api.jquery.com/text-selector/)
$( "<input>" ).is( ":text" );
$( "<input>" ).is( "[type=text]" );

Console Error message:
TypeError: undefined is not a function
message: "undefined is not a function"
stack: (...)
get stack: function () { [native code] }
set stack: function () { [native code] }
__proto__: Error

Additional information:
The page I am trying to get text inputs on is in an iFrame and this whole interaction is running within a webkit.

*

*My main page has jQuery loaded.

*The iFrame page does not.

Need to get inputs on iFrame page with jQuery from my main page.

A: To select an input with jQuery you would do this
$("input")

No brackets needed.
To select all text inputs
$("input[type='text']")

With the change in the question caused by the edit, you can find the answer here: Selecting an element in iFrame jQuery

A: So the given answer is accurate but you can also do
$(':text")

that will give you the all the text input items, just a little more readable in my opinion.
again the answer from @Robbert is accurate

A: You select all inputs of type="text" using:
$(':text')

Inputs of type="checkbox" using:
$(':checkbox')

Inputs of type="radio" using:
$(':radio')

EDIT To cater for new iframe information
Which would, for inputs in an iframe, translate to, respectively:
$('iframe').contents().find( ':text' );
$('iframe').contents().find( ':checkbox' );
$('iframe').contents().find( ':radio' );


text:
Q: Change local repo from master to main to push files to master repo at github I am trying to push files to GitHub main repo as the master branch name is changed to main, but after
git init >
and git remote add >
as git initialized a master branch on my local,
how to push change and push to main check the error below.
$ git push origin/main main
error: src refspec main does not match any.
error: failed to push some refs to 'origin/main'

A: Several solution
Change default branch name
git config --global init.defaultBranch main

Create a main branch
git checkout -b main

Push your master branch to the origin main
git push origin/main master

A: I would suggest you change the upstream branch for your local master to origin/main with the --set-upstream-to option:
git switch master
git branch --unset-upstream
git branch --set-upstream-to origin/main

From that point on, you can just use the regular git pull/git push from your master branch and Git will interact with the main branch on the origin remote.
If you like to keep things in sync, you can also rename your local master branch to main with the --move option:
git branch --move master main


text:
Q: How to move partition in a usb to the first position I've Recalbox installed in the USB with 16 gb 3.0. It's partitionated in 4 because Recalbox needs at least 3 partitions, and it has a fourth partition of 5 gb that is called Documents. The problem comes when I try to access that partition on Windows. On Windows 10 Pro and Home it's not detected, only on Enterprise it is detected. It's a primary partition, but it's in the end of the drive, I read Windows only detects the first and primary partition in the drive, so I want to move Documents to there, but I don't know if it's possible or if it can damage Recalbox.

A: I did that with fdisk / parted (needs some keystrokes, though) for eactly the same reason: Have MS-Win recognize the second partition on a stick:
Device     Boot    Start      End Sectors  Size Id Type
/dev/sdd1            361  4096360 4096000    2G  c W95 FAT32 (LBA)
/dev/sdd2       12288361 15633407 3345047  1,6G  c W95 FAT32 (LBA)
/dev/sdd3              1      360     360  180K  1 FAT12
/dev/sdd4        4096361 12288360 8192000  3,9G 83 Linux


text:
Q: Get specific value from a Nested JSON using Node.js I am totally new to Node.JS. I have written the Node.JS code and getting the response in JSON file. The JSON is in Nested Format. I want to get, store in a variable and print only one value inside the Nested JSON.
Code:
var https = require('https');
var optionget = {
 host : 'api-dev.dataoverflow.com',
 port : 443,
 path : '/test1/test2/MR0000091/benifits?latency=RTIME',
 method : 'GET',
 HEADERS: {
  'Authorization' : 'Basic Qjrfrfhurhfurhjfr2839gbfwj==',
  'X-PruAppID : 'PlainCardPortal'
  }
 };

console.info(optionsget)

var reqGet = htttps.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
res.on('data', function(d) {
process.stdout.write(d);
});
});

reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});

var optionsgetmsg = {
 host : 'api-dev.dataoverflow.com',
 port : 443,
 method : 'GET'
};

console.info(optionsgetmsg);

var reqGet = https.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
res.setEncoding('utf-8')

    res.on('data', function(data) {
        process.stdout.write(data);
    });
});

reqGet.end();
reqGet.on('error', function(e) {
 console.error(e);
});

Getting the whole JSON:
{
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "image":
        {
            "url": "images/0001.jpg",
            "width": 200,
            "height": 200
        },
    "thumbnail":
        {
            "url": "images/thumbnails/0001.jpg",
            "width": 32,
            "height": 32
        }
}

I want to get the width=32 only which is under thumbnail. I want to store it in a variable and want to print in console.

A: You can use JSON.parse() in order to convert your JSON string into an object, and then you can retrieve your value as you would a regular JS object like this:
let parsedData = JSON.parse(data)
process.stdout.write(console.log(parsedData.image.url)

A: You can do something like
res.on('data', (d) => {
  var jsonObj = JSON.parse(d);
  console.log('width = ', jsonObj.thumbnail.width);
});

JSON.parse() will transform the received string in d to a JavaScript object. You then can access the object via standard dot notation.

A: Parse the string using JSON.parse(...). The object is then a standard JavaScript object.  You can access it using either dot notation (e.g. object.property) or via index notation (e.g. object['property'])
You can also nest those, such as in your example, data.thumbnail.width
res.on('data', (d) => {
    let data = JSON.parse(d);
    let width = data.thumbnail.width;
    console.log(width);
});

However, if thumbnail could possibly be undefined, you should check for that.
res.on('data', (d) => {
    let data = JSON.parse(d);
    let width = undefined;
    if (data.thumbnail) width = data.thumbnail.width;
    console.log(width);
});

A: Use npm request
var request = require('request');

var options = {
    url: 'api-dev.dataoverflow.com:443/test1/test2/MR0000091/benifits?latency=RTIME',
    headers: {
        'Authorization': 'Basic Qjrfrfhurhfurhjfr2839gbfwj==',
        'X-PruAppID': 'PlainCardPortal'
    }
};

function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
    }
}

request(options, callback);


text:
Q: Can't program ESP32-MINI-1 over serial despite "Waiting for Download" While I've been able to program both the ESP32-WROOM-32D (mounted on a custom PCB) as well as the ESP32-DevKitV1 using the Espressif idf and a TTL-234X-3V3-WE FTDI cable through the RXD/TXD lines, I am not able to connect to the ESP32-DevKitM-1 in the same way.
I can't find very much information online specifically about the esp32-mini-1, so I've been working off the assumption that it functions and can be programmed identically to the esp32-wroom-32d I'm more familiar with.
I can see the "waiting for download" message when starting the ESP32-DevKitM-1 with the boot button held down, so the TXD line is clearly working, however I just receive a "Failed to connect to ESP32" error when attempting to flash code. At this point I have tried with two separate ESP32-DevKitM-1's to check that the issue wasn't caused by a faulty chip, and retested flashing a program onto an ESP32-DevKitV1 to check that the FTDI cable was working correctly.
Since there is no connection established at all, I assume the issue is not related to the code itself, but either with the hardware, or my environment - which is set up by following the espressif idf guide for linux. (I'm using Windows 11, but performing the flashing and what not using the Ubuntu WSL shell)
My connection to the ESP32-DevKitM-1 from the FTDI cable is cable TXD to devkit RXD, and cable RXD to devkit TXD. The power and ground are also supplied to the devkit over the FTDI cable (into the devkit's 5V pin) and the 3V3 pin is showing 3.293V. I have also tested powering the devkit's 3V3 pin directly from a benchtop power supply (with the FTDI's 5V line disconnected, but both FTDI and power supply grounds connected) to ensure the issue isn't caused by a power issue.
In all cases I have been able to program the ESP32 devkit with no issues, and see a 'waiting for download' response from the ESP32-mini devkit, but fail to connect to the ESP32-mini devkit when flashing code or attempting to erase flash. Are there any secrets to programming the ESP32-MINI-1 which don't apply to the ESP32-WROOM-32D?


text:
Q: How to add svg to pug via mixin? I have a mixin
mixin icon(url)
  svg()
    use(xlink:href=url)

And the code to output
 -
   var features = [
      {
        icon: +icon(img/time.svg)
      }
   ]
  each item in features
    +feature(item.icon)

What am I doing wrong?

A: Are you wanting something like this? I've fixed the indentation, mixin references, and stored the path to the icon as a string.
mixin icon(url)
  svg
    use(xlink:href=url)

-
  var features = [
    {
      icon: 'img/time.svg'
    }
  ]

each item in features
  +icon(item.icon)


text:
Q: Why is Google Cloud Task queue so slow? I have a google cloud tasks queue that processes 1000's of HTTP requested (cloud functions). I've set up the task queue with the default settings except updated "Max attempts" = 2

Each task is dispatched using python using "from google.cloud import tasks_v2" package.
the issue I'm facing is that it just takes too long to finish processing all the tasks within the queue, I would have expected with a setting of "max concurrent" = 1000 I would see more tasks running in one go? When refreshing all observing the "running tasks" indicator I've only seen it at a maximum of 15.

Have I missed something or are there other settings I can play with to get these tasks process quicker?

A: It turns out that the issues had to do with my cloud function. I have try-catch statements that would return a status of 500 when an error occurred.
It seems that cloud tasks will back off when it sees an increase in error responses. I ended up changing my catch statements to return a 200 and my task queue is finishing substantially quicker now.
Hope this helps someone else in the future.


text:
Q: getsockopt doesn't return error when trying to connect to a closed port I try to use connect() & O_NONBLOCK to connect to a port in localhost asynchronously. In order to get the connect result, I use getsockopt to check the socket error status. I can sure no one listen to this port, so ECONNREFUSED should be returned. But in my test, this error may not be returned in some cases.
My test program:
int main() {
  uint64_t p = 0;
  while (1) {
    int fd = ::socket(PF_INET, SOCK_STREAM, 0);
    assert(fd > 0);
    int flags = ::fcntl(fd, F_GETFL, 0);
    flags |= O_NONBLOCK;
    int ret = ::fcntl(fd, F_SETFL, flags);
    assert(ret != -1);
    sockaddr_in addr;
    bzero(&addr, sizeof(sockaddr_in));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(25400);
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    ret = ::connect(fd, (sockaddr *)&addr, sizeof(sockaddr));
    assert(ret != 0);
    switch (errno) {
      case EINPROGRESS:
      case EINTR:
      case EISCONN:
        break;
      default:
        assert(false);
    }
    int epfd = epoll_create1(0);
    assert(epfd > 0);
    epoll_event ev;
    ev.events = EPOLLOUT;
    ev.data.fd = fd;
    ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev);
    assert(ret == 0);
    epoll_event events;
    auto nfds = epoll_wait(epfd, &events, 1, -1);
    assert(nfds == 1);
    assert(events.data.fd == fd);
    int err;
    socklen_t optlen = static_cast<socklen_t>(sizeof err);
    ret = ::getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &optlen);
    assert(ret == 0);
    assert(err != 0);
    ::close(fd);
    ::close(epfd);
    if (p++ % 10000 == 0) {
      std::cout << p << std::endl;
    }
  }
}

assert(err != 0); will be triggered.

A: In this test code, I use connect() without bind(), in this case,  the source port is choosen by kernel. So the source port may be the same as destination port 25400. Due to the destination ip address is localhost, this TCP connection can be established in this case.


text:
Q: argonaut - separating failures and successes when extracting List[A] I have an instance of DecodeJson[A] for a particular type, A, and I have an instance of Json, call it j. I'd like to do something like j.as[List[A]]. However, this JSON is coming to me from a 3rd party, and if some of the items in the array are missing fields, I'd like to just log errors for those items and collect only the items that can be properly parsed (instead of failing the entire decoding).
It seems to me like what I want to end up with is something like (List[(String, CursorHistory)], List[A]). That is, any successfully decoded elements will end up in the list on the right, and errors for any items that could not be successfully parsed will be accumulated on the left. This looks a lot like the MonadPlus.separate method in scalaz.
I can think of a couple ways of getting there. One way is to do something like:
j.as[List[Json]].map(_.map(_.as[A].result).separate)

This should give me a DecodeResult[List[(String, CursorHistory)], List[A]] as desired. However, that will throw away cursor information about where in the JSON array the items that failed were located. I could use something like zipWithIndex, but that starts to get pretty messy.
To me what seems like a better solution is to do something like this:
implicit def DecodeResultDecodeJson[A: DecodeJson]: DecodeJson[DecodeResult[A]] =
  decodeArr(_.as[A]) // outer DecodeResult is always a success

j.as[List[DecodeResult[A]]].map(_.map(_.result)).separate)

This will give me the same output type, but the CursorHistory should be populated to include the information about stepping into the elements of the array.
Here is an example:
val j = Json.array(List("1", "2", "foo").map(Json.jString): _*)
val r = j.as[List[DecodeResult[Int]]].map(_.map(_.result).separate)
// r is DecodeResult[(List[(String, CursorHistory)], List[Int])] =
// DecodeResult(\/-((List((Int,CursorHistory([->,->,\\]))),List(1, 2))))

This seems to behave reasonably (ignoring some terrible List concatenation that is probably happening). However, it seems like this sort of thing would be a fairly common use-case, so I'm wondering if there is a simpler or built-in way to do something like this. If not, I might submit a PR to argonaut for the DecodeJson[DecodeJson[A]] instance and see if anyone is interested.

A: You can use the HCursor decoder, rather than the Json decoder, which preserves the history:
j.as[List[HCursor]].map(_.map(_.as[Int].result).separate)


text:
Q: Convert all 0 value image pixels to 255 in tensorflow I am new to tensorflow,
I need to convert all 0 value pixels to 255 on a 3d image tensor
I can do it in cv like this
img[np.where((img == [0, 0, 0]).all(axis=2))] = [255, 255, 255]
But, I need help to find out how to do this in tensorflow. As i need to do this in a tensorflow graph

A: You can do:
img = tf.cast(tf.equal(img, tf.zeros_like(img)), tf.int32)*255 + img