text:
Q: tc match IPv4 fragment offset What is the correct Syntax for matching Fragments that have and Offset > 0 in tc?
I have tried:
... u32 match u8 255 ff at 7 flowid 2:1

But to no avail

A: According to the IPv4 Header Format (don't be fooled by the numbering when pondering bits later), you must compare the 13 lower bits of the combined two bytes at offset 6 and 7.
    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |Version|  IHL  |Type of Service|          Total Length         |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |         Identification        |Flags|      Fragment Offset    |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |  Time to Live |    Protocol   |         Header Checksum       |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                       Source Address                          |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                    Destination Address                        |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                    Options                    |    Padding    |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

So it can't be matched with u8 but requires for example u16. Also, tc u32 appears to lack a not logical operator, thus it can only reliably match packets without fragment offset (or packets with no offset but the MF set etc.) in one rule. There's even abbreviations for this, if you also want to also include the MF flag in the check:
... u32 match ip nofrag flowid 2:1 # would match the opposite of what's wanted

without MF flag:
... protocol ip u32 match u16 0 0x1fff flowid 2:1

So you can either use two filters to invert the logic, the first filter to bypass the second (you can complement the action with an other flowid if needed):
... prio 1 protocol ip u32 match u16 0 0x1fff action pass
... prio 2 protocol ip matchall flowid 2:1

or you can completely change the filter module and use tc basic's ematch features which include logical operators like not, thus achieving goal in one filter:
... protocol ip basic match 'not cmp(u16 at 6 layer network mask 0x1fff eq 0)' flowid 2:1


text:
Q: Child orders (target and stop loss) in bracket order does not get sent to IB TWS using python code I have the code below - python code using ib_insync to connect and place a bracket order for a ticker. However, only the first order, the parent order, gets submitted. The child orders (target and stop loss) don't get submitted.  I am a bit stumped and not sure where/what the error is?
from ib_insync import*

#create connection
ib = IB()
ib.connect(host='xxx.x.x.x', port=xxxx, clientId=1)

ticker_symbol = "CAN"
ticker_contract = Stock(ticker_symbol,'SMART','USD')
ib.qualifyContracts(ticker_contract)
ticker_bracket_order = ib.bracketOrder('BUY',100,8.51,8.68,4.26)
    #place bracket order
for ord in ticker_bracket_order:
    ib.placeOrder(ticker_contract, ord)

A: I have managed to get a resolution to the problem from some kind individual on another forum/group. In case, some other person encounters this same problem in future, what resolved it was inserting " ib.sleep(1)" right after "ib.placeOrder(ticker_contract,ord)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spectral series' formula of a given atom (other than hydrogen-like)? The hydrogen spectral series is given by the Rydberg formula:

The energy differences between levels in the Bohr model, and hence the
  wavelengths of emitted/absorbed photons, is given by the Rydberg
  formula:
$${1 \over \lambda} = R \left( {1 \over (n^\prime)^2} - {1 \over n^2}
 \right) \qquad \left( R = 1.097373 \times 10^7 \ \mathrm{m}^{-1}
 \right)$$ where $n$ is the upper energy level, $n'$ is the lower
  energy level, and $R$ is the Rydberg constant.

There is a similar formula for every hydrogen-like atom.
Question:  Is there a theoretic formula for the spectral series of a given atom (other than hydrogen-like)?   Else, why, what are the difficulties?

A: There are, in general, no closed form solutions (aka formulas) for the spectra of multi-electron atoms. There are reasonably precise formulas for special cases, like approximate values of x-ray transitions from inner shell electrons, though. Unlike in case of hydrogen and Rydberg atoms, which can be treated as a non-relativistic one-body problems (i.e. for which the Schroedinger equation is a good approximation), no such simplification exists for atoms with Z>2 and more than one electron. Precise calculation of spectral properties of heavy atoms requires a fully relativistic treatment of a quantum mechanical many-body problem. The correct theoretical framework for that is quantum electrodynamics (QED), which is very complex and can only produce numerical results.


text:
Q: can anyone help me with the html pattern validation for a string of 6 chracters? can anyone help me with the html pattern for validating a string which has its first letter as "C" ,second letter as either "A" or "S" followed by four numbers.(Eg: cs4567,ca1589)

A: The pattern is supposed to be a regex, and your question indicated case insensitivity, so the following will work:
^[Cc][AaSs][0-9]{4}$

A: Maybe you mean RegExp? And perhaps instead of "letters" you mean "numbers".
/^c[as]?\d{4}$/i


text:
Q: Как сделать, чтобы виртуальная клавиатура не поднимала activity? Подскажите пожалуйста, как сделать, чтобы выезжающая снизу виртуальная клавиатура(по клику на EditText) не поднимала activity до верха своей границы, а просто поверх выезжала? У меня MapsActivity, но это наверно роли не играет..

A: Вам нужно в манифесте для активити указать атрибут android:windowSoftInputMode. Вам нужны
значения adjustResize и/или adjustPan. Подробнее вот тут можно почитать

A: Можно в onCreate добавить строку
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

И клавиатура будет открываться в режиме "Наложения"


text:
Q: How to make .ics file as downloadable c# For Exporting of .ics file i wrote the following code.
 Collapse | Copy Code
iCalendar iCal = new iCalendar();
            foreach (DataRow row in dt.Rows)
            {
                // Create the event, and add it to the iCalendar
                Event evt = iCal.Create<event>();

            // Set information about the event
            evt.Start = (DDay.iCal.iCalDateTime)Convert.ToDateTime(row["StartDate"]);
            evt.End = (DDay.iCal.iCalDateTime)Convert.ToDateTime(row["EndDate"]);// This also sets the duration
            evt.Description = (string)row["Description"];
        }

     // Serialize (save) the iCalendar
 iCalendarSerializer serializer = new iCalendarSerializer();
        serializer.Serialize(iCal, @"C:\iCalendar.ics");

It is working fine for me but it writes file into C drive or as per the path we have given. but i need it to be downloadable.
i tried some code but it is not the exact format i needed.
Thanks in advance.

A: The documentation supports using a stream. You could write the contents of the calendar to the response. Make sure you set the mime type as well.
iCalendarSerializer serializer = new iCalendarSerializer(iCal);
serializer.Serialize(Response.OutputStream, Encoding.ASCII);

http://www.ddaysoftware.com/Pages/Projects/DDay.iCal/Documentation/


text:
Q: Strange positioning after using MKAnnotationView centerOffset in iOS 5.0, I first place annotations on the map and also set the centre offset to CGPointMake(0,-annotationView.frame.size.height/2); right after setting the custom image for the annotation in the mapView:viewForAnnotation: method... after this the pins still appear at the original position which would be the case when the centre offset was not applied.
However, when I pinch or zoom the map, the annotation jumps to the correct position as would be the case with the centerOffset being set and then behaves correctly..
What could be the reason and solution for this?
Any help would be much appreciated.
Baffled!!

A: I was finally able to solve it by subclassing the MKAnnotationView and in the initWithAnnotation:reuseIdentifier: constructor method, synchronously get the annotationView image and then set the centerOffset to CGPointMake(0.0, -img.size.height/2);
If there are too many annotations, this will slow down the display of annotations, so would need to handle that differently.


text:
Q: debug python in vscode failed I'm unable to debug my python code in vscode. I've attempted to redownload python and add it to PATH, but I'm still getting the same errors as before.
When I press F5, the terminal shows the image 1, and later, image 2 shows automatically.
Any ideas?

A: It's not the problem of python but the 'Python' extension. You can try to reinstall it. If it does not work, you can try to install other versions of 'Python' extension(Hit the "manage" button on the extension -> Install Another Version).


text:
Q: При увеличении изображения на canvas оно размывается. Как с этим бороться? Слева размытое изображение на канвасе, справа исходное изображение, надо что бы было с пикселями, а оно размывает, не знаю как бороться.

        c=skinImage.width/64;
        var canvas = document.createElement('canvas');
        canvas.width = 256;// * scale;
        canvas.height = 256;// * scale;
        //we assign the same classname the image has, for CSS purposes
        canvas.setAttribute('class', skinImage.getAttribute('class'));
        var context = canvas.getContext("2d");
        var s = scale;
        //draw the head
        context.drawImage(skinImage, 8*c,  8*c,  8*c, 8*c,  4*s,  0*s,  8*s, 8*s);
        //draw the mask
        context.drawImage(skinImage, 40*c,  8*c,  8*c, 8*c,  4*s,  0*s,  8*s, 8*s);
        //draw the body
        context.drawImage(skinImage, 20*c, 20*c, 8*c, 12*c, 4*s,  8*s,  8*s, 12*s);
        //draw the left leg
        context.drawImage(skinImage, 4*c,  20*c, 4*c, 12*c, 4*s,  20*s, 4*s, 12*s);
        //draw the right leg
        context.drawImage(skinImage, 4*c,  20*c, 4*c, 12*c, 8*s,  20*s, 4*s, 12*s);
        //draw the left arm
        context.drawImage(skinImage, 44*c, 20*c, 4*c, 12*c, 0*s,  8*s,  4*s, 12*s);
        //draw the right arm
        context.drawImage(skinImage, 44*c, 20*c, 4*c, 12*c, 12*s, 8*s,  4*s, 12*s);
        //draw down leftleg
        context.drawImage(skinImage, 20*c,  52*c,  4*c, 12*c,  4*s,  20*s, 4*s, 12*s);
        //draw down lefthand
        context.drawImage(skinImage, 36*c,  52*c,  4*c, 12*c,  0*s,  8*s,  4*s, 12*s);

        //we replace the image with the canvas
        skinImage.parentNode.replaceChild(canvas, skinImage);

Использую такой код, s-это во сколько раз должно увеличиться, оно увеличивается, но в результате оно размывается вместо того что бы нормально отобразиться, я не знаю что делать подскажите.

A: При помощи установки свойства context.imageSmoothingEnabled в false. Кроссбраузерная установка:
ctx.mozImageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.msImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;

Рабочий пример на Plunker
Страница на MDN


text:
Q: R Creating boundary boxes with tmaptools for every row in an sf object I'm trying to work out how to create boundary boxes from sf point geometry data on every row in an sf object. I'm trying to use the 'bb' function from the tmaptools package, along with dplyr and rowwise(). However, the output I get is just the same bounday box values copied onto every row, rather than a specific boundary box calculated from the point data on each row.
Here is a snip of the data frame sf object:
df1<-structure(list(Altitude = c(65.658, 65.606, 65.562, 65.51, 65.479,
65.408, 65.342, 65.31, 65.242, 65.17, 65.122), Bearing = c(201.3042,
201.3042, 201.3042, 201.3042, 201.3042, 201.3042, 201.3042, 201.3042,
201.3042, 201.3042, 201.3042), TAI = c(0.7535967, 0.7225685,
0.7142722, 0.7686105, 0.760403, 0.7515627, 0.7905218, 0.6231222,
0.7246232, 0.6290409, 0.635797), lat_corrd = c(51.28648265, 51.28647067,
51.28646118, 51.28645183, 51.28644244, 51.28643067, 51.28642109,
51.28641164, 51.28639984, 51.2863905, 51.28638087), lon_corrd = c(0.866623929,
0.866616631, 0.866610968, 0.86660517, 0.866598889, 0.866591258,
0.866585183, 0.866579259, 0.866571906, 0.86656599, 0.866560288
), geometry = structure(list(structure(c(0.866623929, 51.28648265
), class = c("XY", "POINT", "sfg")), structure(c(0.866616631,
51.28647067), class = c("XY", "POINT", "sfg")), structure(c(0.866610968,
51.28646118), class = c("XY", "POINT", "sfg")), structure(c(0.86660517,
51.28645183), class = c("XY", "POINT", "sfg")), structure(c(0.866598889,
51.28644244), class = c("XY", "POINT", "sfg")), structure(c(0.866591258,
51.28643067), class = c("XY", "POINT", "sfg")), structure(c(0.866585183,
51.28642109), class = c("XY", "POINT", "sfg")), structure(c(0.866579259,
51.28641164), class = c("XY", "POINT", "sfg")), structure(c(0.866571906,
51.28639984), class = c("XY", "POINT", "sfg")), structure(c(0.86656599,
51.2863905), class = c("XY", "POINT", "sfg")), structure(c(0.866560288,
51.28638087), class = c("XY", "POINT", "sfg"))), class = c("sfc_POINT",
"sfc"), precision = 0, bbox = structure(c(xmin = 0.866560288,
ymin = 51.28638087, xmax = 0.866623929, ymax = 51.28648265), class = "bbox"), crs = structure(list(
    input = "EPSG:4326", wkt = "GEOGCRS[\"WGS 84\",\n    DATUM[\"World Geodetic System 1984\",\n        ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n            LENGTHUNIT[\"metre\",1]]],\n    PRIMEM[\"Greenwich\",0,\n        ANGLEUNIT[\"degree\",0.0174532925199433]],\n    CS[ellipsoidal,2],\n        AXIS[\"geodetic latitude (Lat)\",north,\n            ORDER[1],\n            ANGLEUNIT[\"degree\",0.0174532925199433]],\n        AXIS[\"geodetic longitude (Lon)\",east,\n            ORDER[2],\n            ANGLEUNIT[\"degree\",0.0174532925199433]],\n    USAGE[\n        SCOPE[\"Horizontal component of 3D system.\"],\n        AREA[\"World.\"],\n        BBOX[-90,-180,90,180]],\n    ID[\"EPSG\",4326]]"), class = "crs"), n_empty = 0L)), row.names = 5000:5010, class = c("sf",
"data.frame"), sf_column = "geometry", agr = structure(c(Altitude = NA_integer_,
Bearing = NA_integer_, TAI = NA_integer_, lat_corrd = NA_integer_,
lon_corrd = NA_integer_), .Label = c("constant", "aggregate",
"identity"), class = "factor"))

str(df1)
#Classes 'sf' and 'data.frame': 11 obs. of  6 variables:

What I want to do is create a new boundary box from the sfc_point values in the 'geometry' column, for example:
require(tmaptools)
bb(df1, cx = st_coordinates(df1)[,1], cy = st_coordinates(df1)[,2], width = 0.000012, height = 0.000012, relative = FALSE)
#      xmin       ymin       xmax       ymax
# 0.8666179 51.2864767  0.8666299 51.2864887

Or more specifically, something that is like this:
bb(df1[i,], cx = st_coordinates(df1)[i,1], cy = st_coordinates(df1)[i,2], width = 0.000012, height = 0.000012, relative = FALSE)

I want the resulting xmin,ymin, xmax, ymax values calculated for each row as a new geometry called something like boundary_boxes added to the existing data frame.
I tried to do it using 'apply' but it didn't work at all, and seemed like the way that 'apply' passes the 'geometry' sf list-type values along wasn't correct for 'bb'.
I then tried to use 'dplyr' and this worked better, but still not quite right:
df1 %>% rowwise() %>% mutate(boundary_boxes = list(bb(cx = st_coordinates(.)[,1], cy = st_coordinates(.)[,2], width = 0.000012, height = 0.000012, relative = FALSE)))

This almost works but just repeats the same values for each row in the new 'boundary_box' column rather than give a specific boundary box.
How do i get this to work, or is there a better way to do it?
Many thanks
Once I have a bbox for each row of data, I then need to convert the bounding box to a spatial object. I've used 'bb_poly' to do this:
bb_poly('some boundary box data', steps = 1)

A: You made it unnecessarily complicated by storing vectors in a data frame.
It's better to store this data in tibble with  x and y  columns.
See below.
I'm using tribble and bind_cols here to make it more visible.
library(tidyverse)
library(tmaptools)

geom = tribble(
  ~x, ~y,
  0.866623929, 51.28648265,
  0.866616631, 51.28647067,
  0.866610968, 51.28646118,
  0.86660517, 51.28645183,
  0.866598889, 51.28644244,
  0.866591258, 51.28643067,
  0.866585183, 51.28642109,
  0.866579259, 51.28641164,
  0.866571906, 51.28639984,
  0.86656599, 51.2863905,
  0.866560288, 51.28638087)

df = tibble(
  Altitude = c(65.658, 65.606, 65.562, 65.51, 65.479,65.408, 65.342, 65.31, 65.242, 65.17, 65.122),
  Bearing = c(201.3042, 201.3042, 201.3042, 201.3042, 201.3042, 201.3042, 201.3042, 201.3042,201.3042, 201.3042, 201.3042),
  TAI = c(0.7535967, 0.7225685, 0.7142722, 0.7686105, 0.760403, 0.7515627, 0.7905218, 0.6231222, 0.7246232, 0.6290409, 0.635797),
  lat_corrd = c(51.28648265, 51.28647067, 51.28646118, 51.28645183, 51.28644244, 51.28643067, 51.28642109, 51.28641164, 51.28639984, 51.2863905, 51.28638087),
  lon_corrd = c(0.866623929, 0.866616631, 0.866610968, 0.86660517, 0.866598889, 0.866591258, 0.866585183, 0.866579259, 0.866571906, 0.86656599, 0.866560288),
) %>% bind_cols(geom)
df

output
# A tibble: 11 x 7
   Altitude Bearing   TAI lat_corrd lon_corrd     x     y
      <dbl>   <dbl> <dbl>     <dbl>     <dbl> <dbl> <dbl>
 1     65.7    201. 0.754      51.3     0.867 0.867  51.3
 2     65.6    201. 0.723      51.3     0.867 0.867  51.3
 3     65.6    201. 0.714      51.3     0.867 0.867  51.3
 4     65.5    201. 0.769      51.3     0.867 0.867  51.3
 5     65.5    201. 0.760      51.3     0.867 0.867  51.3
 6     65.4    201. 0.752      51.3     0.867 0.867  51.3
 7     65.3    201. 0.791      51.3     0.867 0.867  51.3
 8     65.3    201. 0.623      51.3     0.867 0.867  51.3
 9     65.2    201. 0.725      51.3     0.867 0.867  51.3
10     65.2    201. 0.629      51.3     0.867 0.867  51.3
11     65.1    201. 0.636      51.3     0.867 0.867  51.3

Now you only need one simple function that returns you the results of the function bb in the form of tibble. For example, such as below.
fbb = function(data){
  bbout = bb(cx=data$x, cy=data$y, width= 0.000012, height= 0.000012, relative= FALSE)
  tibble(
    xmin = bbout["xmin"],
    ymin = bbout["ymin"],
    xmax = bbout["xmax"],
    ymax = bbout["ymax"]
  )
}

The next one couldn't be easier.
df %>%
  nest(data=x:y) %>%
  mutate(bbout = map(data, fbb)) %>%
  unnest(c(data, bbout))

output
# A tibble: 11 x 11
   Altitude Bearing   TAI lat_corrd lon_corrd     x     y  xmin  ymin  xmax  ymax
      <dbl>   <dbl> <dbl>     <dbl>     <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1     65.7    201. 0.754      51.3     0.867 0.867  51.3 0.867  51.3 0.867  51.3
 2     65.6    201. 0.723      51.3     0.867 0.867  51.3 0.867  51.3 0.867  51.3
 3     65.6    201. 0.714      51.3     0.867 0.867  51.3 0.867  51.3 0.867  51.3
 4     65.5    201. 0.769      51.3     0.867 0.867  51.3 0.867  51.3 0.867  51.3
 5     65.5    201. 0.760      51.3     0.867 0.867  51.3 0.867  51.3 0.867  51.3
 6     65.4    201. 0.752      51.3     0.867 0.867  51.3 0.867  51.3 0.867  51.3
 7     65.3    201. 0.791      51.3     0.867 0.867  51.3 0.867  51.3 0.867  51.3
 8     65.3    201. 0.623      51.3     0.867 0.867  51.3 0.867  51.3 0.867  51.3
 9     65.2    201. 0.725      51.3     0.867 0.867  51.3 0.867  51.3 0.867  51.3
10     65.2    201. 0.629      51.3     0.867 0.867  51.3 0.867  51.3 0.867  51.3
11     65.1    201. 0.636      51.3     0.867 0.867  51.3 0.867  51.3 0.867  51.3

Or maybe you say that the data is the same in every row? Of course they are not. Look
df %>%
  nest(data=x:y) %>%
  mutate(bbout = map(data, fbb)) %>%
  unnest(c(data, bbout)) %>%
  ggplot(aes(x, y)) +
  geom_ribbon(aes(ymin=ymin, ymax=ymax), alpha=0.2)+
  geom_line(aes(x, y))

Add one more function fbb_poly and you will have boxes!!
fbb_poly = function(data)
  bb_poly(bb(cx=data$x, cy=data$y, width= 0.000012,
             height= 0.000012, relative= FALSE), steps = 1)

df %>%
  nest(data=x:y) %>%
  mutate(bbout = map(data, fbb),
         bb_poly = map(data, fbb_poly)) %>%
  unnest(c(data, bb_poly))

output
# A tibble: 11 x 9
   Altitude Bearing   TAI lat_corrd lon_corrd     x     y bbout                                                                                bb_poly
      <dbl>   <dbl> <dbl>     <dbl>     <dbl> <dbl> <dbl> <list>                                                                                <POLYGON [arc_degree]>
 1     65.7    201. 0.754      51.3     0.867 0.867  51.3 <tibble [1 x 4]> ((0.8666179 51.28648, 0.8666179 51.28649, 0.8666299 51.28649, 0.8666299 51.28648, 0.86661...
 2     65.6    201. 0.723      51.3     0.867 0.867  51.3 <tibble [1 x 4]> ((0.8666106 51.28646, 0.8666106 51.28648, 0.8666226 51.28648, 0.8666226 51.28646, 0.86661...
 3     65.6    201. 0.714      51.3     0.867 0.867  51.3 <tibble [1 x 4]> ((0.866605 51.28646, 0.866605 51.28647, 0.866617 51.28647, 0.866617 51.28646, 0.866605 51...
 4     65.5    201. 0.769      51.3     0.867 0.867  51.3 <tibble [1 x 4]> ((0.8665992 51.28645, 0.8665992 51.28646, 0.8666112 51.28646, 0.8666112 51.28645, 0.86659...
 5     65.5    201. 0.760      51.3     0.867 0.867  51.3 <tibble [1 x 4]> ((0.8665929 51.28644, 0.8665929 51.28645, 0.8666049 51.28645, 0.8666049 51.28644, 0.86659...
 6     65.4    201. 0.752      51.3     0.867 0.867  51.3 <tibble [1 x 4]> ((0.8665853 51.28642, 0.8665853 51.28644, 0.8665973 51.28644, 0.8665973 51.28642, 0.86658...
 7     65.3    201. 0.791      51.3     0.867 0.867  51.3 <tibble [1 x 4]> ((0.8665792 51.28642, 0.8665792 51.28643, 0.8665912 51.28643, 0.8665912 51.28642, 0.86657...
 8     65.3    201. 0.623      51.3     0.867 0.867  51.3 <tibble [1 x 4]> ((0.8665733 51.28641, 0.8665733 51.28642, 0.8665853 51.28642, 0.8665853 51.28641, 0.86657...
 9     65.2    201. 0.725      51.3     0.867 0.867  51.3 <tibble [1 x 4]> ((0.8665659 51.28639, 0.8665659 51.28641, 0.8665779 51.28641, 0.8665779 51.28639, 0.86656...
10     65.2    201. 0.629      51.3     0.867 0.867  51.3 <tibble [1 x 4]> ((0.86656 51.28638, 0.86656 51.2864, 0.866572 51.2864, 0.866572 51.28638, 0.86656 51.28638))
11     65.1    201. 0.636      51.3     0.867 0.867  51.3 <tibble [1 x 4]> ((0.8665543 51.28637, 0.8665543 51.28639, 0.8665663 51.28639, 0.8665663 51.28637, 0.86655...


text:
Q: Difference when executing a piece of code in main versus calling it as a function in golang I am trying to do a CPU-intensive operation in GO. The code is pretty straight forward and I am trying to measure it as well. The measurement code looks like this
However, when I try to execute the same code as a function (invoked from main) it seems to work much faster. Any idea as to why this is happening?
package main
import (
       "fmt";
       "time"
    )

func addlist1 (from uint64, to uint64) {
var i uint64;
var l uint64;
var j uint64;
var sum1 uint64;
var  count uint64;

   count = 0;
   for i=1;i<1001;i++ {
      for l=from;l<(from+to);l++ {
           j = l*l;
           count = count + 1;
           sum1 = sum1 + (j*j*j*j*j*j*j*j*j*j);
      }
   }
}

func main () {
   var sum1 uint64;
   var j uint64;
   var i uint64;
   var l uint64;
   var num uint64;
   var count  uint64;

   sum1 = 0;
   num = 100000000;
   start88 := time.Now ();
   addlist1(1,num);
   elapsed88 := time.Since(start88);
   fmt.Println("The time taken is ", elapsed88,sum1,num);
   time.Sleep(1*time.Second);

   sum1 = 0;
   count  = 0;
   start := time.Now();
   for i=1;i<1001;i++ {
      for l=1;l<num;l++ {
         j = l*l;
         sum1 = sum1 + (j*j*j*j*j*j*j*j*j*j);
         count = count+1;
      }
   }
   elapsed := time.Since(start);
   fmt.Println("The total time without function is", elapsed,sum1,num,count);
   time.Sleep(1*time.Second);

}

The first println gives an output of 29 seconds whereas the second one gives an output of 4m 57seconds. The difference is huge. It is consistent as well.
I am running this in a Debian distribution that has 4 cores.
Any ideas why this is so?
Sincerely,
Sudarsan.D

A: The code inside main and addlist1 is not the same.
In the function addlist1, no values are returned. The compiler can completely optimize it away into nothing, because the function does nothing (it does not modify memory or return a value).
This is not true of the code in main(), which prints the value of sum1.
To make the code the same, return sum1 and count from your function and print it from main:
func addlist1(from uint64, to uint64) (uint64, uint64) {
    ...
    return sum1, count
}

func main() {
    ...
    start := time.Now()
    sum, count := addlist1(1, num)
    elapsed := time.Since(start)
    fmt.Println("The time taken is ", elapsed, sum1, num);
    ...
}


text:
Q: Flask Streaming Server I have a problem with a debug streaming server that I want to use to get better insights into my project in Python.
I set up the following flask server, but I do not want to just stream a video directly from the camera to the browser but edit the image on the main thread and after that update the web server to display the new image.
I am trying to achieve that by calling the update method in the main loop. But the image in my browser does not change. Maybe because the methods are running in different threads?
from flask import Response
from flask import Flask
from flask import render_template
from flask import request
from multiprocessing import Process
import datetime
import time
import cv2
import queue

global outputFrame

class Webstream():

def __init__(self):
    self.t1 = None
    # initialize a flask object
    self.app = Flask(__name__)
    self.app.add_url_rule('/', 'index', self.index)
    self.app.add_url_rule('/videofeed', 'videofeed', self.videofeed)

def shutdown_server(self):
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

def startInternally(self):
    self.app.run(host='0.0.0.0', port='5000', debug=False)

def start(self):
    self.t1 = Process(target=self.startInternally)
    self.t1.start()

def stop(self):
    self.t1.terminate()
    self.t1.join()

@staticmethod
def update(image):
    global outputFrame
    outputFrame = image

@staticmethod
def getFrame():
    global outputFrame
    return outputFrame

def gen(self):
    while True:
        time.sleep(0.01)
        frame = Webstream.getFrame()                #This never changes, even when #the update method is called
        if(frame.any()):
            ret, buffer = cv2.imencode('.jpg', frame)
            yield (b'--frame\r\n'
                b'Content-Type: image/jpeg\r\n\r\n' + bytearray(buffer) + b'\r\n\r\n')
        else:
            yield (b'--frame\r\n'
                b'Content-Type: image/jpeg\r\n\r\n\r\n\r\n')

def index(self):
    # return the rendered template
    return render_template('index.html')

def videofeed(self):
    # return the response generated along with the specific media
    # type (mime type)
    return Response(self.gen(), mimetype='multipart/x-mixed-replace; boundary=frame')

I cannot find any relevant answers on google but only the standard tutorials on using this setup with a regular generator. Please help me.


text:
Q: Apache reverse proxy "RequestHeader set" based on "Require ldap-group" I have a application which has only local authentication and I want to put Apache reverse proxy Infront of it to achieve LDAP authentication. But also I need to have different roles inside application so I have created 3 local users with different permissions.
What I need somehow set Authorization header based on LDAP groups if user successfully logs-in.
I thought that SetEnvIf could help as per example below, but it does not work.
How can I achieve such behaviour?
<VirtualHost 1.2.3.4: 443>
SSLEngine on
SSLProtocol all -SSLv2
SSLProxyEngine on

<Location />
    AuthType Basic
    AuthBasicProvider ldap
    AuthName "Active Directory authentication"
    AuthLDAPURL "ldap://myldap.net/DC=mydc,DC=net?sAMAccountName?sub"
    AuthLDAPInitialBindPattern (.+) "$1@myldap.net"
    AuthLDAPInitialBindAsUser on
    AuthLDAPSearchAsUser on
    AuthLDAPCompareAsUser on
    AuthLDAPMaxSubGroupDepth 1
    AuthLDAPGroupAttribute member
    AuthLDAPSubgroupAttribute member
    AuthLDAPSubGroupClass group

    SetEnvIf Require ldap-group CN=aaaa-00-00,OU=My Groups,OU=Admin,DC=myldap,DC=net env=admin_user
    SetEnvIf Require ldap-group CN=bbbb-00-02,OU=My Groups,OU=Admin,DC=myldap,DC=net env=admin_user

    SetEnvIf Require ldap-group CN=cccc-00-00,OU=My Groups,OU=Admin,DC=myldap,DC=net env=read_user
    SetEnvIf Require ldap-group CN=dddd-00-02,OU=My Groups,OU=Admin,DC=myldap,DC=net env=read_user

    SetEnvIf Require ldap-group CN=cccc-00-00,OU=My Groups,OU=Admin,DC=myldap,DC=net env=write_user
    SetEnvIf Require ldap-group CN=dddd-00-02,OU=My Groups,OU=Admin,DC=myldap,DC=net env=write_user

    RequestHeader set Authorization "Basic RDAwOTdfdfdfdfdfdffdy9hTGtA" env=admin_user
    RequestHeader set Authorization "Basic RDAwOTdfrrrererfdffdy9hTGtA" env=read_user
    RequestHeader set Authorization "Basic RDAwOTdfkkkkkkkkkffdy9hTGtA" env=write_user

    Require all denied

    ProxyPass "http://localhost:1234/"
    ProxyPassReverse "http://localhost:1234/"

</Location>


text:
Q: Conjugate heat transfer modelling of reciprocating flow crashes for long flow times The following transient problem is essentially the reciprocating (i.e., fully reversing) flow of a fluid over a thick heated block until the system reaches a cyclic steady-state (i.e., the system temperature oscillates around a mean when this point is reached). The following code simulates the system for a fluid velocity boundary condition $u=3*\sin(2*\pi*0.5*t)$, i.e., a frequency of $0.5Hz$ and a heat flux input of $1000 W/m^2$. tflow refers to the total time till which the flow oscillation occurs and t0 is the time-step. The code uses the flow solver developed by Alex Trounev and described in this page.
Needs["NDSolve`FEM`"]

{f = 0.5; L = 0.040, d = 0.003, e = 0.005, kf = 0.026499, ks = 16,
 rho = 1.1492, rhos = 7860, mu = 18.923*10^-6, cp = 1.0069*10^3,
 cps = 502.4}; u0 = 3; nu = mu/rho; om = 2 Pi f;
tflow = 400;
t0 = .3;
NV = 2 f tflow;
nn = Round[NV \[Pi]/(om t0)]
Ti = 307; q = 1000/Ti;

reg1 = ImplicitRegion[0 <= x <= L && 0 <= y <= d, {x, y}]; reg2 =
 ImplicitRegion[0 <= x <= L && -e <= y <= d, {x, y}];
UX[0][x_, y_] := 0;
VY[0][x_, y_] := 0;
P[0][x_, y_] := 0;
Tfs[0][x_, y_] := 307/Ti; appro =
 With[{k = 2. 10^6}, ArcTan[k #]/Pi + 1/2 &];
ade[y_] := (ks + (kf - ks) appro[y])
rde[y_] := (cps rhos + (cp rho - cps rhos) appro[y]);

Monitor[Do[{UX[i], VY[i], P[i]} =
    NDSolveValue[{{Inactive[
            Div][({{-\[Mu], 0}, {0, -\[Mu]}}.Inactive[Grad][
              u[x, y], {x, y}]), {x, y}] + D[p[x, y], x] +
          UX[i - 1][x, y]*D[u[x, y], x] +
          VY[i - 1][x, y]*D[u[x, y], y] + (u[x, y] - UX[i - 1][x, y])/
           t0, Inactive[

            Div][({{-\[Mu], 0}, {0, -\[Mu]}}.Inactive[Grad][
              v[x, y], {x, y}]), {x, y}] + D[p[x, y], y] +
          UX[i - 1][x, y]*D[v[x, y], x] +
          VY[i - 1][x, y]*D[v[x, y], y] + (v[x, y] - VY[i - 1][x, y])/
           t0, D[u[x, y], x] + D[v[x, y], y]} == {0, 0, 0} /. \[Mu] ->
         nu, {DirichletCondition[{u[x, y] == u0*Sin[om*i*t0],
         v[x, y] == 0},
        x == L (1 - Sign[Sin[om*i*t0]])/2 && 0 < y < d],
       DirichletCondition[{u[x, y] == 0, v[x, y] == 0},
        y == 0 || y == d]},
      DirichletCondition[p[x, y] == 0,
       x == L (1 + Sign[Sin[om*i*t0]])/2 && 0 < y < d]}, {u, v,
      p}, {x, y} \[Element] reg1,
     Method -> {"FiniteElement",
       "InterpolationOrder" -> {u -> 2, v -> 2, p -> 1},
       "MeshOptions" -> {"MaxCellMeasure" -> 0.0000005}}];
   ux = If[y <= 0, 0, UX[i][x, y]]; vy = If[y <= 0, 0, VY[i][x, y]];
   Tfs[i] =
    NDSolveValue[{rde[
           y] ((ux*D[T[x, y], x] +
              vy*D[T[x, y], y]) + (T[x, y] - Tfs[i - 1][x, y])/t0) -
         Inactive[Div][
          ade[y]*Inactive[Grad][T[x, y], {x, y}], {x, y}] ==
        NeumannValue[q, y == -e],
       DirichletCondition[{T[x, y] == 1},
        x == L (1 - Sign[Sin[om*i*t0]])/2 && 0 <= y <= d]},
      T, {x, y} \[Element] reg2,
      Method -> {"FiniteElement", "InterpolationOrder" -> {T -> 2},
        "MeshOptions" -> {"MaxCellMeasure" -> 0.0000001}}] //
     Quiet;, {i, 1, nn}],ProgressIndicator[i,{1,nn}]]; // AbsoluteTiming

ListLinePlot[
 Table[{i t0, Tfs[i][0.5*L, -e/2]*Ti - 273.16}, {i, 0, nn}],
 AxesLabel -> {"t(s)", "T(in deg. C)"}, PlotRange -> Full]

If one plots the temperature profile at a point $(0.5L,-e/2)$ in the solid with time, it turns out to be:

As can be seen, the temperature of the system initially increases fast to gradually slow down and reach a cyclic steady-state (marked with red), where it oscillates around a mean.
However, keeping all other parameters same, if I increase the frequency to say f=2 Hz, I need to give a smaller time-step which should be at-least $<\frac{1}{2*2}=0.25s$, to resolve the flow reversal in each half-period correctly. In this scenario, the tflow required to reach a cyclic steady-state increases.
When I run the above code with f=2, t0=0.1,tflow=800, it crashes each and every time with the error Wolfram Kernel has stopped working. My question is:

*

*Can this code be improved so that it does not crash for high f, which require small t0? For example: f=2, t0=0.1

A: To answer first question we can improve code by separating fluid part and using mesh with QuadElement only as follows
Needs["NDSolve`FEM`"]
{f = 2;
 L = 0.040, d = 0.003, e = 0.005, kf = 0.026499, ks = 16,
 rho = 1.1492, rhos = 7860, mu = 18.923*10^-6, cp = 1.0069*10^3,
 cps = 502.4}; u0 = 3; nu = mu/rho; om = 2 Pi f;
tflow = 800;
t0 = .1;
NV = 2 f tflow;
nn = Round[NV \[Pi]/(om t0)]
Ti = 307; q = 1000/Ti;

reg1 = ImplicitRegion[0 <= x <= L && 0 <= y <= d, {x, y}]; reg2 =
 ImplicitRegion[0 <= x <= L && -e <= y <= d, {x, y}];

mesh = ToElementMesh[FullRegion[2], {{0, L}, {0, d}}];
mesh1 = ToElementMesh[FullRegion[2], {{0, L}, {-e, d}}];
UX[0][x_, y_] := 0;
VY[0][x_, y_] := 0;
P[0][x_, y_] := 0;
Tfs[0][x_, y_] := 307/Ti; appro =
 With[{k = 2. 10^6}, ArcTan[k #]/Pi + 1/2 &];
ade[y_] := (ks + (kf - ks) appro[y])
rde[y_] := (cps rhos + (cp rho - cps rhos) appro[y]);
eqs = {Inactive[
     Div][({{-\[Mu], 0}, {0, -\[Mu]}} .
      Inactive[Grad][u[x, y], {x, y}]), {x, y}] + D[p[x, y], x] +
   UX[i - 1][x, y]*D[u[x, y], x] +
   VY[i - 1][x, y]*D[u[x, y], y] + (u[x, y] - UX[i - 1][x, y])/t0,
  Inactive[
     Div][({{-\[Mu], 0}, {0, -\[Mu]}} .
      Inactive[Grad][v[x, y], {x, y}]), {x, y}] + D[p[x, y], y] +
   UX[i - 1][x, y]*D[v[x, y], x] +
   VY[i - 1][x, y]*D[v[x, y], y] + (v[x, y] - VY[i - 1][x, y])/t0,
  D[u[x, y], x] + D[v[x, y], y]};
bc[i_] := {DirichletCondition[{u[x, y] == u0*Sin[om*i*t0],
    v[x, y] == 0}, x == L (1 - Sign[Sin[om*i*t0]])/2 && 0 < y < d],
  DirichletCondition[{u[x, y] == 0, v[x, y] == 0}, y == 0 || y == d],
  DirichletCondition[p[x, y] == 0,
   x == L (1 + Sign[Sin[om*i*t0]])/2 && 0 < y < d]};

Monitor[Do[{UX[i], VY[i], P[i]} =
      NDSolveValue[{eqs == {0, 0, 0} /. \[Mu] -> nu, bc[i]}, {u, v,
        p}, {x, y} \[Element] mesh,
       Method -> {"FiniteElement",
         "InterpolationOrder" -> {u -> 2, v -> 2, p -> 1}}];, {i, 1,
     nn}], ProgressIndicator[i, {1, nn}]]; // AbsoluteTiming

It takes about 1871s on my laptop. Visualization last 20 frames
Table[DensityPlot[UX[i][x, y], {x, y} \[Element] mesh,
  ColorFunction -> "Rainbow", PlotRange -> All,
  AspectRatio -> Automatic, Frame -> False], {i, nn - 19, nn}]

With this velocity field we can compute temperature as follows
Monitor[Do[ux = If[y <= 0, 0, UX[i][x, y]];
    vy = If[y <= 0, 0, VY[i][x, y]];
    Tfs[i] =
     NDSolveValue[{rde[
            y] ((ux*D[T[x, y], x] +
               vy*D[T[x, y], y]) + (T[x, y] - Tfs[i - 1][x, y])/t0) -
          Inactive[Div][
           ade[y]*Inactive[Grad][T[x, y], {x, y}], {x, y}] ==
         NeumannValue[q, y == -e],
        DirichletCondition[{T[x, y] == 1},
         x == L (1 - Sign[Sin[om*i*t0]])/2 && 0 <= y <= d]},
       T, {x, y} \[Element] mesh1,
       Method -> {"FiniteElement",
         "InterpolationOrder" -> {T -> 2}}] // Quiet;, {i, 1, nn}],
   ProgressIndicator[i, {1, nn}]]; // AbsoluteTiming

It takes about 1086s. Visualization
{ListLinePlot[
  Table[{i t0, Tfs[i][0.5*L, -e/2]*Ti - 273.16}, {i, 0, nn}],
  AxesLabel -> {"t(s)", "T(in deg. C)"}, PlotRange -> Full],
 ListLinePlot[
  Table[{i t0, Tfs[i][0.5*L, -e/2]*Ti - 273.16}, {i, nn - 40, nn}],
  AxesLabel -> {"t(s)", "T(in deg. C)"}, PlotRange -> Full]}


text:
Q: jQuery and TinyMCE 3.5.2: attr() not working There's a problem in how jQuery and TinyMCE interact when using the jQuery version of TinyMCE that's been reported and solved several times. It involves, as I understand it, a redefinition of the jQuery attr() function by TinyMCE.
The result is that the while the following returns the attribute value when TinyMCE is not being used on a page:
var junk = $(this).attr('someAttribute');

an object gets returned instead when TinyMCE is in use.
I'm running into this problem with jQuery 1.7.2 and TinyMCE 3.5.2.
Is anyone else encountering this? If so, is there a workaround?

A: TinyMCE jquery's plugin would break jQuery's attr method (jQuery>=1.7.2.). This is fixed in TinyMCE 3.5b3.
For your references, here is a reported TinyMCE Bug #5136 and a fix.

A: I'm posting an answer to this question, but if anyone has a different solution I'd still love to hear it.
Basically, I took Thariama's advice and stopped using the jQuery build of tinyMCE. Instead, I did the following:
    tinyMCE.init({
        mode: "specific_textareas",
        editor_selector: "tinymce",
        script_url: '@Url.Content("~/Scripts/tinymce/tiny_mce.js")',
        theme: "advanced",
        plugins: "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
        theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
        theme_advanced_buttons4: "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_resizing: true,
        template_external_list_url: "lists/template_list.js",
        external_link_list_url: "lists/link_list.js",
        external_image_list_url: "lists/image_list.js",
        media_external_list_url: "lists/media_list.js",
        convert_urls: 0, // default 1
        content_css: '@Url.Content("~/Content/tinymce.css")'
    });

This was based on a suggested solution I found elsewhere on StackOverflow.
FYI for others converting from the jQuery version of tinyMCE: you need to remember to add the mode: and editor_selector: parameters to the parameter list you were using previously. If you don't you'll get the default behavior of turning every textarea control into a tinyMCE editor.
You'll also need to include the tinyMCE library in your page's header. In my application that looks like the following:
<script src="@Url.Content("~/Scripts/tinymce/tiny_mce.js")" type="text/javascript"></script>

Enjoy!


text:
Q: Confusion in reading file using FolderBrowserDialog which i used earlier (FileuploadControl tool used)
inside button click method
if (FileUploadControl.HasFile)
{
    filename = Path.GetFileName(FileUploadControl.FileName);
    FileUploadControl.SaveAs(Server.MapPath("~/") + filename);

    string lines;
    string root = Server.MapPath("~/");
    string Template = root + filename;
    using (StreamReader reader = new StreamReader(Template))
    {
        while ((lines = reader.ReadLine()) != null)
            list.Add(lines); // Add to list.
    }
    //file is now in list
    //MORE IMPORTANT CODE
}

But now I am just using FolderDialog
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.ShowNewFolderButton = true;
DialogResult result = folderDialog.ShowDialog();
if (result == DialogResult.OK) {
    textBox8.Text = folderDialog.SelectedPath;
    Environment.SpecialFolder root = folderDialog.RootFolder
    //...
}

How can i read the file so that i can only use the FolderBrowserDialog to read an entire file and extract data?

A: I guess you are working in Windows Forms now if you are using FolderDialog.
You should use better OpenFileDialog if you want the user to check a FILE, not a Folder.
You can read the file using System.IO classes once you have the path.
If the file is text for example you can do:
string FinalPath = OpenFileDialog.FileName;

string Text= System.IO.File.ReadAllText(FinalPath);

you can also read the file into byte()
byte[] file = System.IO.File.ReadAllBytes(FinalPath);


text:
Q: Unable to open feature class - Failed to execute (Raster to Polyline) I'm working in ArcGIS 10.4.1 in the ModelBuilder with the iterate feature selection iterator. Everything works out just fine. But in the end I would like to convert my raster-output via "Raster to Polyline" to a shapefile.
This leads to the following error:
Executing (Raster to Polyline): RasterToPolyline "P:\path\Scratch.gdb\CostPat_Ziel_1" "P:\path\Scratch.gdb\RasterT_CostPat_1.shp" NODATA 0 SIMPLIFY Value

Start Time: Thu Apr 05 07:59:41 2018
ERROR 999999: Error executing function.
The table was not found. [RasterT_CostPat_1.shp]
ERROR 010157: Unable to open feature class P:\path\Scratch.gdb\RasterT_CostPat_1.shp.
Failed to execute (Raster to Polyline).
Failed at Thu Apr 05 07:59:41 2018 (Elapsed Time: 0,38 seconds)
Does anyone have an idea what could cause the error and how to solve it?
I checked the other questions about this issue but couldn't really understand what lead to it's success in the end, since I'm not working in arcpy but in the ModelBuilder and my understanding of python isn't that good.

A: You are trying to write a feature class into a file geodatabase with an invalid name P:\path\Scratch.gdb\RasterT_CostPat_1.shp. Feature classes cannot contain dots (.) and some other non-alphanumeric characters.
You either need to create a shapefile (plain file data structure) as P:\path\ScratchFolder\RasterT_CostPat_1.shp or a file geodatabase feature class with legal name as P:\path\Scratch.gdb\RasterT_CostPat_1.


text:
Q: Can't do a websocket handshake using an APIM on azure I have some issues doing a handshake to a websocket endpoint through an Azure APIM. This error doesn't happen if I use the app service endpoint, it is only when the request is sent through the APIM.
The main problem, and as far I can see, is that the APIM is not sending the header Connection: Update, it overrides the header and sets it to keep-alive. I have tried to create a policy to set that header to Upgrade but the APIM returns the following error.

Error in element 'set-header' Header name is invalid or restricted
from modification

The policy I tried to use is
<policies>
    <inbound>
        <base />
        <set-header name="Connection" exists-action="override">
            <value>Upgrade</value>
        </set-header>
    </inbound>
...
</policies>

I opened an issue on the MS documentation github (https://github.com/MicrosoftDocs/azure-docs/issues/96878) asking this and they told me to try using some extra headers
Connection: Upgrade
Upgrade: Websocket
Sec-WebSocket-Version: 13
And the response is the same in any case...
{
    "statusCode": 400,
    "message": "Invalid websocket upgrade request"
}

Postman request and response
Also, there is another parameter negotiateVersion that is set to 1 that can't be seen on the picture.
Any way to solve this? Thanks in advance.


text:
Q: In JavaScript, removeChild node error when removing an element from its parent I have a method to remove an item from a list when its checkbox is checked. The 1st item is removed fine, but when I want to remove the subsequent items I get this error:
Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
But according to my code it look like I'm doing the right thing. Can you tell me what is missing, please?
HTML:

          <input type="checkbox" name="product_item_1" id="product_item_1">
          Product Item

          <input type="checkbox" name="product_item_2" id="product_item_2">
          Product Item

          <input type="checkbox" name="product_item_3" id="product_item_3">
          Product Item

          <input type="checkbox" name="product_item_4" id="product_item_4">
          Product Item

JS:
import utils from 'utils';

class CategoryList {

  constructor() {
    this._categoryLists;
  }

  init(component) {
    this._categoryLists = document.querySelector(component);
  }

  _deleteItem() {
    let categoryList;
    let productItems;
    let productItem;
    let productItemInnerWrapper;
    let checkboxes;
    let checkbox;

    for (categoryList of this._categoryLists) {
      checkboxes = categoryList.querySelectorAll('.product-item__checkbox');

      for (checkbox of checkboxes) {
        if (checkbox.checked) {
          productItem = utils.findParent(
            checkbox,
            'product-item'
          );

          productItemInnerWrapper =
            productItem.querySelector('.product-item__wrapper');

          productItemInnerWrapper.classList.add('product-item__wrapper--animate');

          productItem.classList.add('product-item__item--animate');

          setTimeout(() => {
            categoryList.removeChild(productItem); // --> This produces an error. I don't know why
          }, 500);
        }
      }
    }
  }
}

export default CategoryList;

A: A simple solution which should work everytime is getting the parentNode directly from the element you want to remove:
productItem.parentNode.removeChild(productItem);


text:
Q: Storing PBKDF2 Settings Alongside Password I'm experimenting with PBKDF2 for my passwords right now, and it dawned on me that if I were to ever upgrade to a faster machine in the future, I would want to increase the number of PBKDF2 iterations. However, this would invalidate all the current passwords that I have stored. One idea I've seen was to store the PBKDF2 settings along with the password (similar to how you store the salt) such as the iteration count and the PRF used (SHA-256, SHA-512) at the time of the hash creation. It sounds like a good idea in terms of backwards compatibility, but I wanted to know if there are any drawbacks to doing this. Any insight into this would be appreciated.

A: You are definitely taking the right direction here. Many systems store just the salt but where is the rest of the parameters required to perform PBKDF2? Hardcoded! And hardcoding parameters of cryptographic functions is almost never a good idea.
Only drawback I see is that when you store all the parameters your database will probably take a little more space but your future upgrades will be much easier and straightforward.
BTW RFC 2898 defines structure called PBKDF2-params which was designed as a data holder for all the public parameters of PBKDF2 algorithm. Use it at least as an inspiration so you won't forget any important parameter.


text:
Q: Grammatically correct way to restart a thought in a single sentence There exists an oratory technique where a sentence or thought that might be highly complex, too complex even to risk maintaining the listeners' understanding throughout it, where such a complex thought can be restarted or succinctly restated mid sentence, and the listener implicitly understands that all that has come before is now summarized and can be used to complete the thought, of which this sentence is an example.
My training tells me this is grammatically incorrect.  My thinking is that restarting a new sentence with effectively a new subject and predicate when the previous one has not been completed is invalid grammar, and I have no guess how to punctuate it correctly.  If I just end the previous sentence and start a new one, one of the two resulting sentences becomes a fragment, but keeping them together as one sentence doesn't fall into any sort of correct sentence structure that I can recognize.  Is there a way to do this in written word, or does this fall under, "as long as the reader understands what you mean, all is forgiven?"


text:
Q: JavaFX Как узнать координаты курсора, который находится в TextField? Нашел только getCaretPosition(), но это немного не то.

A: Если посмотреть на класс TextFieldSkin он наследует от TextInputControlSkin. В нем содержится экземпляр класса Path, который показывает курсор, caretPath. Но он объявлен с модификатором protected.
protected final Path caretPath = new Path();

Чтобы получить к нему доступ, надо создать наследника. В нем мы и получим доступ к нашему курсору. И при каждом изменении курсора мы будет отлавливать его и обрабатывать.
import com.sun.javafx.scene.control.skin.TextFieldSkin;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class TextFieldCaretControlSkin extends TextFieldSkin {
    public TextFieldCaretControlSkin(TextField textField, Stage stage) {
        super(textField);
        // следим за изменениями layoutBoundProperty нашего экземпляра Path
        caretPath.layoutBoundsProperty().addListener(new ChangeListener<Bounds>() {
            @Override
            public void changed(ObservableValue<? extends Bounds> observable,
                            Bounds oldValue, Bounds newValue) {
                // координаты курсора относительно TextField-а
                double x = newValue.getMaxX();
                double y = newValue.getMaxY();

                // искомая координата
                Point2D p = caretPath.localToScene(x, y);

                System.out.println(p.toString());
            }
        });
    }
}

Этим же способом можно получить координаты курсора от всех наследователей TextInputControlSkin.


text:
Q: nifi routeText processor usage issue I am facing issue in configuring RouteText Processor correctly. I have to filter out those lines which have say a particular string values at a particular index. Let's say I want all the lines which have 'BT'  or 'PV7' and 'PV30'  values at index 19. My file is csv.
I tried using below configuration but all of my lines are moved to unmatched relation. However, data is containing other lines too.

A: You need to change the Matching Strategy to "Satisfies Expression" since you are not using regular expressions here.
The docs for Satisfies Expression says:
"Match lines based on whether or not the the text satisfies the given Expression Language expression. I.e., the line will match if the property value, evaluated as an Expression, returns true. The expression is able to reference FlowFile Attributes, as well as the variables 'line' (which is the text of the line to evaluate) and 'lineNo' (which is the line number being evaluated. This will be 1 for the first line, 2 for the second and so on)."


text:
Q: Run and manage android application on hundreds of identical devices I am trying to upload a single apk to each identical phones. I need to manage multiple settings in the phone and also need to re upload the new apk for upgrades again to the same hundreds of devices. I am spending lot of time for this work.
We are using Xamarin for android app development.
List of things to change in the settings.
1.Enabling the other sources to upload the apk.
2.Permissions to access wifii, bluetooth and cellular data.
3.Moving the app icon to main screen or home  screen.
Can anyone provide an easy way to manage this?

A: Easy solution do not exist, however exists MDM system. I used it 7 years ago for Win mobile and Palms. It worked like a charm. Or if you want do it all by yourself check here.
What is MDM? Source
MDM is an industry term associated with the management of mobile devices (most often it is applied to large-scale management) and involves a third-party solution that serves as the centralized management console for the devices. With these third-party solutions you are able to handle tasks that include:

*

*Distributing applications;

*Locking or wiping a single device;

*Sending software updates;

*Remotely troubleshooting a device;

*Pushing out settings and content;

*Enforcing policy compliance across platforms;

*Managing device lifecycles;

*Detecting jailbroken or rooted devices;

*Encrypting sensitive data;

*Monitoring usage;

*Containerization.


text: Q: Mac OSX Sierra, Out of the blue, User logs into the domain, and everything in the account is gone Never have seen this before, but just had a user log into his domain account, and it's like he is logging into his account for the first time? This user has been logging in for months now with no problem. Usually when this happens, it creates a separate folder in the Users directory, but this time nothing. It's a pretty standard setup with AD/mobile accts logging into the domain with OS X. Just wondering if anyone has seen this and maybe point me where to start to look? Is it a mobile account glitch? These clients are being synced with Munki/Deploy Studio as well, could they be the culprits?


text:
Q: Computer starts without pressing the power button When I open the switch of the power supply, the computer automatically starts up and then in three seconds automatically shuts down.
I have tried shutting down Windows properly, but this unusual behaviour is still there.
The vendor says this is normal! But how can that be?
Whenever I switch on the UPS/power supply the computer starts and shuts down which might some day cause any hardware to go bad!
How do I prevent this?
There is NO power loss.

A: What you have described is normal behavior when newer model power supplies are plugged into power or switched on using the switch on the power supply itself. This does not actually turn the computer on, it's more of a self test. It should not damage the computer.
You said you are using a UPS. When you turn it on, it has the same effect as plugging the computer into a power outlet.
In order to prevent this from happening, leave the UPS on. Desktop computers today are meant to be left plugged in.

A: If my understanding is correct, which I'm not certain it is, you may be able to fix this in the BIOS power settings. Set "on power loss" to "remain off".


text:
Q: Convert BYTE array into unsigned long long int I'm trying to convert a BYTE array into an equivalent unsigned long long int value but my coding is not working as expected. Please help with fixing it or suggest an alternative method for the same.
Extra Information: These 4 bytes are combined as a hexadecimal number and an equivalent decimal number is an output. Say for a Given byteArray= {0x00, 0xa8, 0x4f, 0x00}, Hexadecimal number is 00a84f00 and it's equivalent decimal number is 11030272.
#include <iostream>
#include <string>

typedef unsigned char BYTE;

int main(int argc, char *argv[])
{
  BYTE byteArray[4] = { 0x00, 0x08, 0x00, 0x00 };
  std::string str(reinterpret_cast<char*>(&byteArray[0]), 4);
  std::cout << str << std::endl;

  unsigned long long ull = std::strtoull(str.c_str(), NULL, 0);
  printf ("The decimal equivalents are: %llu", ull);

  return EXIT_SUCCESS;
}

I'm getting the following output:
The decimal equivalents are: 0

While the expected output was:
The decimal equivalents are: 2048

A: When you call std::strtoull(str.c_str(), NULL, 0);, its first argument supplied is equivalent to an empty string, as string is essentially a null-terminated sequence of characters.
Second, std::strtoull() does not convert with byte sequences, it converts with the literal meaning of strings. i.e. you'll get 2048 with std::strtoull("2048", NULL, 10).
Another thing to note is that unsigned long long is a 64-bit data type, whereas your byte array only provides 32 bits. You need to fill the other 32 bytes with zero to get the correct result. I use a direct assignment, but you could also use std::memset() here.
What you want to do is:
ull = 0ULL;
std::memcpy(&ull, byteArray, 4);

Given your platform has little-endian, the result should be 2048.

A: What you first must remember is that a string, is really a null-terminated string. Secondly, a string is a string of characters, which is not what you have. The third problem is that you have an array of four bytes, which corresponds to an unsigned 32-bit integer, and you want an (at least) 64-bit types which is 8 bytes.
You can solve all these problems with a temporary variable, a simple call to std::memcpy, and an assignment:
uint32_t temp;
std::memcpy(&temp, byteArray, 4);
ull = temp;

Of course, this assumes that the endianness is correct.

Note that I use std::memcpy instead of std::copy (or std::copy_n) because std::memcpy is explicitly mentioned to be able to bypass strict aliasing this way, while I don't think the std::copy functions are. Also the std::copy functions are more for copying elements and not anonymous bytes (even if they can do that too, but with a clunkier syntax).

A: Given the answers are using std::memcpy, I want to point out that there's a more idiomatic way of doing this operation:
char byteArray[] = { 0x00, 0x08, 0x00, 0x00 };
uint32_t cp;
std::copy(byteArray, byteArray + sizeof(cp), reinterpret_cast<char*>(&cp));

std::copy is similar to std::memcpy, but is the C++ way of doing it.
Note that you need to cast the address of the output variable cp to one of: char *, unsigned char *, signed char *, or std::byte *, because otherwise the operation wouldn't be byte oriented.


text:
Q: How to stack rails helper methods in controller? I'd like to
@cart = Cart.find_by(id: session[:cart], :limit => 1)

but that throws out an error SQLite3::SQLException: no such column: carts.limit: SELECT  "carts".* FROM "carts"  WHERE "carts"."id" = 1 AND "carts"."limit" = 1 LIMIT 1 so how can I use multiple methods on a single global variable? Version: rails 4.0.1

A: It appears you mean to specify a limit of one record to be returned from find_by.
However, find_by only returns one record anyway, so this is not needed. Your :limit gets interpreted as a table column, which of course doesn't exist.
You can omit it entirely.
@cart = Cart.find_by(id: session[:cart])

A: If you're going to be querying by id, you can simply do:
ruby @cart = Card.find(session[:cart])

as find will do a SELECT ... LIMIT 1 by the primary key.


text:
Q: Insert condition into a nested IIf Visual Basic is used to generate reports in SSRS.
I'm trying to alter a report that pulls client information. I want to check the record for a secondary address, if they do not want to display their primary address. The SQL query is working right and is pulling all the relevant data.
The information is displayed using Visual Basic which I know even less about than I do sql. I managed to get the relevant data to display correctly except for the "line 2" section of the address.
An image of the section.

"Address Line 2" is what I'm trying to fix.
The expression from the original version:
=IIf(IsNothing(Fields!AccountBillToLine1.Value), IIf(IsNothing(Fields!ContactBillToLine1.Value), IIf(IsNothing(Fields!AccountLine2.Value), IIf(IsNothing(Fields!ContactLine2.Value), "", chr(13)+chr(10)+Fields!ContactLine2.Value), chr(13)+chr(10)+Fields!AccountLine2.Value), IIf(IsNothing(Fields!ContactBillToLine2.Value), "", chr(13)+chr(10)+Fields!ContactBillToLine2.Value)), IIf(IsNothing(Fields!AccountBillToLine2.Value), "", chr(13)+chr(10)+Fields!AccountBillToLine2.Value))

I'm trying to insert into this cluster a condition to also check "SecondaryAddressLine2" and if it contains information to display it below "Address Line 1".

A: It helps with readability if you format it with indents so that the closing parentheses line up with the "IIf" statements.
=
IIf(IsNothing(Fields!AccountBillToLine1.Value),
 IIf(IsNothing(Fields!ContactBillToLine1.Value),
  IIf(IsNothing(Fields!AccountLine2.Value),
   IIf(IsNothing(Fields!ContactLine2.Value), "", chr(13)+chr(10)+Fields!ContactLine2.Value
   ), chr(13)+chr(10)+Fields!AccountLine2.Value
  ), IIf(IsNothing(Fields!ContactBillToLine2.Value), "", chr(13)+chr(10)+Fields!ContactBillToLine2.Value
     )
 ), IIf(IsNothing(Fields!AccountBillToLine2.Value), "", chr(13)+chr(10)+Fields!AccountBillToLine2.Value
    )
)

This is still difficult to understand. You may want to consider rewriting it using a Switch statement so that the conditions and results match up more nicely and there's no nesting. To answer you question though, you can wrap the whole thing in another IIf to add your condition like this:
=
IIF(IsNothing(Fields!SecondaryAddressLine2.Value),
 IIf(IsNothing(Fields!AccountBillToLine1.Value),
  IIf(IsNothing(Fields!ContactBillToLine1.Value),
   IIf(IsNothing(Fields!AccountLine2.Value),
    IIf(IsNothing(Fields!ContactLine2.Value), "", chr(13)+chr(10)+Fields!ContactLine2.Value
    ), chr(13)+chr(10)+Fields!AccountLine2.Value
   ), IIf(IsNothing(Fields!ContactBillToLine2.Value), "", chr(13)+chr(10)+Fields!ContactBillToLine2.Value
      )
  ), IIf(IsNothing(Fields!AccountBillToLine2.Value), "", chr(13)+chr(10)+Fields!AccountBillToLine2.Value
     )
 ) , chr(13)+chr(10)+Fields!SecondaryAddressLine2.Value)
)

The chr(13)+chr(10) there just inserts a new line, but you can also use VbCrLf which is more standard.


text:
Q: SharePoint APP with list and pre-defined list item, error in specifying image URL I am building a SharePoint hosted App which contains a list and pre-defined list items. When I try to deploy app, I get following error

@"Error 1
          CorrelationId: 39056be2-5dd1-4c51-ac43-9084a4791d02
          ErrorDetail: There was a problem with activating the app web definition.
          ErrorType: App
          ErrorTypeName: App Related
          ExceptionMessage: Invalid URL: IMG SRC="../Images/Explore.png">.
          Source: AppWeb
          SourceName: App Web Deployment
  Error occurred in deployment step 'Install app for SharePoint': Failed to install app for SharePoint. Please see the output window for details.

I have also tried following but not working:

<Field Name="BackgroundImageLocation">../Images/Explore.png</Field>
Problem is in the URL of the background image location field.
How can I specify the URL of an image here?

A: I tried this and worked.
<Field Name="Image">~site/Images/Explore.png</Field>


text:
Q: Validate jsonpath expression not working for a single attribute I have the following JSON document:
{
    "logVersion": 1,
    "id": "65eb093d-39ea-11e4-8481-0dcbed7e7494",
    "part": "e5818b35-39ea-11e4-9c1a-0ee3aaa24b07",
    "interaction": {
        "product": "IVR",
        "start": 1410463962299000,
        "finish": 0
    },
    "productData": {
        "timestamp": "2014-09-11T19:36:16.356Z",
        "name": "SessionEnded"
    }
}

I want to validate if the productData.name == 'SessionEnded'.  I tried the following:
$.productData[?(@.name == 'SessionEnded')] and $.productData?(@.name == 'SessionEnded')on this jsonpath expression tester.

A: I think your jsonpath is ok.
 $.productData[?(@.name=='SessionEnded')]

works for me on this tester:   [1]: http://jsonpath.herokuapp.com/


text:
Q: Get value of selected field in vb6 data grid I'm using data grid for my vb6 project .
How can I know which record is selected by user?

A: If the primary key is in the 3rd column, use
MyDataGrid.Columns(3).Value

That will show you the PK for the selected row.

A: The Text property of the DataGrid should be what is currently selected:
DataGrid1.Text

A: the .Col and .Row properties of the datagrid return the active row and column in the datagrid


text:
Q: ¿De que forma puedo obtener la diferencia en minutos de dos timepicker? en Java Por favor podrían decirme como puedo capturar la hora que me arroja una timepickerdialog y guardarla como un numero float para restarla con otro timerpickerdialog, he tratado de convertir ese formato de hora y no he podido, no se la forma como se hace. Cuando corro la app puedo poner la hora inicial y final que se muestran en EditText pero al hacer el calculo se cierra la app. Gracias.
public void horainicial(View view) {
HoraInicial = Calendar.getInstance();
hora = HoraInicial.get(Calendar.HOUR_OF_DAY);
minutos = HoraInicial.get(Calendar.MINUTE);

TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        thorainicial.setText(hourOfDay + ":" + minute);
       }

}
        , hora, minutos, false);
timePickerDialog.show();

}
    public void horafinal (View view){
    HoraFinal = Calendar.getInstance();
    hora = HoraFinal.get(Calendar.HOUR_OF_DAY);
    minutos = HoraFinal.get(Calendar.MINUTE);

    TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            thorafinal.setText(hourOfDay + ":" + minute);

        }
    }
            , hora, minutos, false);
    timePickerDialog.show();
}

A: Crea una valriable a nivel de clase para almacenar la hora inicial y final en formato Date
private Date horaInicial, horaFinal;

Ahora en cada TimePickerDialog obtiene los valores de hora inicial:
TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        thorainicial.setText(hourOfDay + ":" + minute);

        //*Obtiene valor de hora Inicial.
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm");
        horaInicial = simpleDateFormat.parse(hourOfDay + ":" + minute);

       }

}
        , hora, minutos, false);

y hora final:
TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        thorafinal.setText(hourOfDay + ":" + minute);

    //*Obtiene valor de hora Inicial.
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm");
    horaFinal = simpleDateFormat.parse(hourOfDay + ":" + minute);

    }
}
        , hora, minutos, false);

a partir de obtener estos valores puedes hacer uso del siguiente método el cual obtiene la diferencia entre ambos valores en formato String:
public String obtieneDiferencia(Date startDate, Date endDate) {
    //Diferencia en millisegundos
    long different = endDate.getTime() - startDate.getTime();

    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    different = different % daysInMilli;

    long elapsedHours = different / hoursInMilli;
    different = different % hoursInMilli;

    long elapsedMinutes = different / minutesInMilli;
    different = different % minutesInMilli;

    long elapsedSeconds = different / secondsInMilli;

    return "horas: " + elapsedHours + " minutos: " + elapsedMinutes + "segundos: " + elapsedSeconds;
}

Teniendo los valores de hora inicial y final puedes obtener el valor de la diferencia:
String diferencia = obtieneDiferencia(horaInicial, horaFinal);

A: Mauricio, quizas podrias trabajarlo de esta manera e implementar tu lógica aquí:
int minutosUno = timePicker1.getCurrentMinute();
int minutosDos = timePicker2.getCurrentMinute();

espero sea de ayuda


text:
Q: Return data from Async function React Native Redux I am having trouble with accessing the data after fetching it with SecureStore in Expo for react-native.
Here is the simple code:
const infoofuser = SecureStore.getItemAsync('userInfo').then(value =>
  console.log(`this is the vlaue from infouser: ${value}`),
);
console.log(`infoouser: ${JSON.stringify(infoofuser)}`);

the first infoofuser constant definition returns the object of the intended data.
console.log(`infoouser: ${JSON.stringify(infoofuser)}`);

however returns {"_U":0,"_V":0,"_W":null,"_X":null} which U understand is a promise. I would like to simply get the data that comes from the SecureStore call and use it to set my initialState in redux.
const infoofuser = SecureStore.getItemAsync('userInfo').then(value =>
  value
);

this does not work either to access the data

A: You can use async method using async/await. Try this:
const userInfo = useSelector(state => state.userInfo);

const getData = async () => {
  try {
    const infoofuser = await SecureStore.getItemAsync('userInfo');
    console.log('infoofuser:', infoofuser)
    /// strore on redux
  } catch (err) {
     // handle error
  }
}

useEffect(() => {
  getData()
}, [])

if (!userInfo) return null

//render something else

You can check the Expo Secure Store docs for reference.


text:
Q: How can I select if Date column is as same as current year This is my Student table
Id(int) | Name(varchar) | registerDate(Date)
1         John            2012-01-01

How can I write the appropriate query to check if the person's registerDate value is as same as current year (2012)?

A: SELECT *
FROM Student
WHERE YEAR(registerDate) = YEAR(getdate())

A: The most direct solution would be to use the YEAR or DATEPART function in whatever flavor of SQL you're using. This will probably meet your needs but keep in mind that this approach does not allow you to use an index if you're searching the table for matches. In this case, it would be more efficient to use the BETWEEN operator.
e.g.
SELECT id, name, registerDate
FROM Student
WHERE registerDate BETWEEN 2012-01-01 and 2012-12-31

How you would generate the first and last day of the current year will vary by SQL flavor.
Because you're using a range, and index can be utilized. If you were using a function to calculate the year for each row, it would need to be computed for each row in the table instead of seeking directly to the relevant rows.

A: If by chance your flavor of sql is Microsoft TSql then this works:
SELECT  * FROM Student Where datepart(yy,registerDate) = datepart(yy,GetDate())

A: This should work for SQL Query:
SELECT * FROM myTable
WHERE registerDate=YEAR(CURDATE())


text:
Q: Download wikipedia markup using Haskell Using http-conduit I want to download the raw wikimedia markup for any page, for example the Wikipedia page Stack Overflow.
Also, I'd like the solution to be applicable to wikimedia pages other than en.wikipedia.org, for example de.wikibooks.org.
Note: This question was immediately answered in Q&A form and therefore intentionally does not show research effort!

A: This question uses query parameters in http-conduits as described in this previous SO answer.
We will use the method described here on SO to download the markup content of a page.
Although this task could be possible using the mediawiki, it seems significantly simpler to use the ?action=raw method without explicitly using the API.
In order to support different pages (e.g. en.wikimedia.org), I wrote two functions getWikipediaPageMarkup and getEnwikiPageMarkup, the former one being more general and allowing to use custom domains (any domain should work, assuming Mediawiki is installed under /wiki).
{-# LANGUAGE OverloadedStrings #-}
import Network.HTTP.Conduit
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as LB
import Network.HTTP.Types (urlEncode)
import Data.Monoid ((<>))

-- | Get the Mediawiki marup
getWikipediaPageMarkup :: ByteString -- ^ The wikipedia domain, e.g. "en.wikipedia.org"
                       -> ByteString -- ^ The wikipedia page title to download
                       -> IO LB.ByteString -- ^ The wikipedia page markup
getWikipediaPageMarkup domain page = do
    let url = "https://" <> domain <> "/wiki/" <> urlEncode True page
    request <- parseUrl $ B.unpack url
    let request' = setQueryString [("action", Just "raw")] request
    fmap responseBody $ withManager $ httpLbs request'

-- | Like @getWikipediaPageMarkup@, but hardcoded to 'en.wikipedia.org'
getEnwikiPageMarkup :: ByteString -> IO LB.ByteString
getEnwikiPageMarkup = getWikipediaPageMarkup "en.wikipedia.org"

Note that a recent http-conduit version is required (minimum: 2.1, tested with 2.1.4) in order to compile the code.


text:
Q: How to regex between two square brackets with multiple lines? (grep|awk|python) I have this file with multiple json objects and am trying to grab the data in the array "ld" that continues to the next line. Is there a way to grab the first anchor '[' and the last anchor ']' as one set and then the next as another?
    {
        "test": 'asdfadfa',\n
        "happy": 'dq34werqedqe',\n
        "ld": [\n
            "creamer",\n
            "sugar",\n
            "honey"\n
        ]
    }
    {
        "test": 'asdfadfa',\n
        "happy": 'dq34werqedqe',\n
        "ld": [\n
            "coffee_creamer",\n
            "milk"
    ]\n
    }
.
.
.

Only want
"creamer", "sugar", "honey"
"coffee_creamer", "milk"

I have tried multiple was todo so even with [\r\n]+ but not able to match the first anchor is problem '[' to next anchor ']'.
I tried python but my file is to large to parse through and my memory keeps crashing it so figured to use regex with grep/awk.
Is it possible if not another way recommended would be amazing thanks.

A: This approach is fragile and I do not recommend using it. There are tools available such as jq which are designed to handle json data, and would be more appropriate for this task (see e.g. https://cameronnokes.com/blog/working-with-json-in-bash-using-jq/ for more details).
Having said that, here is one potential method using awk:
If the "\n" characters are 'real':
awk '/"ld":/{flag=1; next} /]/{flag=0} flag' test.json
"creamer",
"sugar",
"honey"
"coffee_creamer",
"milk"

# Tidy up the output
awk '/"ld":/{flag=1; next} /]/{flag=0} flag' test.json | tr -s "\n" " " | sed 's/" "/"\n"/g; s/ //g'
"creamer","sugar","honey"
"coffee_creamer","milk"

If the "\n" characters are actually present, in addition to 'real' newlines:
awk '/"ld":/{flag=1; next} /]/{flag=0} flag' test.json | tr -s "\n" " " | sed 's/\\n//g; s/" "/"\n"/g; s/ //g'
"creamer","sugar","honey"
"coffee_creamer","milk"


text:
Q: how to change Jenkins build schedule to different time? I am new to Jenkins. I have a job when I went in to configuration I see that it's scheduled to run at 12:25:03 AM EDT
Build Schedule : H H(0-3) * * *
I want to change that to run at 8:15 AM EDT, how can I do that ?
If I want to run more than once for example 8:15 AM EDT and 2:15 PM EDT how can I do that ?
What does that H H(0-3) * * * stands for ?

A: To launch your job at 8:15am and 2:15am, you can use the following expression:
15 2,8 * * *

You can use the following web site to test your cron expressions:
http://cron.schlitt.info/
H H(0,3) * * * means your job will be launch between midnight and 3am every day.
The Jenkins documentation is very detailed on this subject (accessible from your job with the help button).
Another useful link : How to schedule jobs in Jenkins?


text:
Q: Quickest way to turn multidimensional array into List? I have the following array:
Array
(
    [0] => stdClass Object
        (
            [categoryid] => 60
            [categoryName] => Parent Category A
            [categoryParent] =>
        )

    [1] => stdClass Object
        (
            [categoryid] => 65
            [categoryName] => Parent Category B
            [categoryParent] =>
        )

    [2] => stdClass Object
        (
            [categoryid] => 68
            [categoryName] => Child Category A
            [categoryParent] => 65
        )

    [3] => stdClass Object
        (
            [categoryid] => 69
            [categoryName] => Super Child Category A
            [categoryParent] => 68
        )
)

I need to end up with a list like this:

*

*Parent Category A

*Parent Category B

*

*Child Category A

*

*Super Child Category A

What would be the easiest way to do this?

A: Try this:
function htmlList($array, $parent = null){
    $str = '
';
    foreach($array as $object){
        if(!$parent){
            if(!$object->categoryParent){
                $str .= '
' . $object->categoryName;
                $str .= htmlList($array, $object->categoryid);
                $str .=  '
';
            }
        }
    }
    return $str .= '
';
}

echo htmlList($yourArray);

A: function mylist( $a, $parent='') {
   $r = '' ;
   foreach ( $a as $i ) {
       if ($i['categoryParent'] == $parent ) {
          $r = $r . "
" . $i['categoryName'] . mylist( $a, $i['categoryid'] ) . "
";
       }
   }
   return ($r==''?'':"
". $r . "
");
}

A: I will suggest to keep a array with parent items, and add the subitems in a own array of the element. (Similar to your tree)
You can read this element by following example:
<?php
BuildList($arrayParent, 0);

function BuildList($arrayElements, $depth)
{
    foreach($arrayElements as $element)
    {
        echo str_repeat("  ", $depth) . $element->categoryName;
        $depth++;
        if(count($element->subCategory) > 0)
            $depth = BuildList($element->subCategory, $depth);

        return $depth;
    }
}
?>


text:
Q: How to compute average slope and area-weighted average slope? I am learning GIS for use in hydrologic analysis.  Related to computation of overland flow there are two types of slope that I would like to be able to obtain from GIS.  The first is average slope for a given polygon area.  The second for the same polygon area is an AREA-Weighted average slope.  Presumably one would need to divide the polygon into subareas based on a slope-range (say 0-2%, 2%-4%, 4% -10%, etc) then compute a weighted average.
Is there a plugin that will provide this information, . . . or am I at the point where I need to learn how to write a python script?

A: The very first thing you need is a slope raster, which is created from a DEM - see 8.3.3 here.
To solve the first part of your problem, the average slope, you need a zonal statistics tool. This provides statistics of one raster's cell values based on areas defined by polygons or cells of constant value in another raster. There is a QGIS Zonal Statistics Plugin.
The area weighted average slope is a bit more of a challenge. For that you first need to classify your slope raster into the desired ranges. You could use broader ranges like your question, or more specific (rounded to nearest percent) if you wanted a more fine grained average slope. Then you need to calculate the area of each range within each zone. I don't know of an easy way to do this in QGIS (the methods or answers I know of already here apply specifically to Arc) and just off the top of my head it might be best as a separate question. I don't think that zonal stats plugin offers a case option (if it did you could get the sum area of each class per zone with it). Once you had the area of each class though, it'd be simple field calculations to determine class area percentage of zone and then multiply that percentage by class slope value, summing all those values, and dividing by the number of values to get the ultimate area-weighted slope.


text:
Q: token_exchange_failed when I try to login in react-native with IdentityServer4 I need to create Mobile client for my app. And I need to authenticate/authorize users.
I'm new in Mobile development, so I decided to use react-native because I have some experience with react.
I used the following stack:

*

*react-native (v0.66.4)

*react-native-app-auth (v6.4.0)

*IdentityServer4

I have the following Client configuration in IdentityServer4
new Client
{
    RequireConsent = false,

    ClientId = "28BDF82E-4443-4097-9430-C44471398728",
    ClientName = "Mobile Client",
    RequireClientSecret = false,

    AllowedGrantTypes = GrantTypes.Code,

    RedirectUris =
    {
        "io.identityserver.demo:/oauthredirect"
    },

    RequirePkce = true,
    AllowedScopes = {
        IdentityServerConstants.StandardScopes.OpenId,
        IdentityServerConstants.StandardScopes.Profile
    },

    AllowOfflineAccess = true
}

When user tries to authenticate from Mobile App
const configs = {
  clientId: '28BDF82E-4443-4097-9430-C44471398728',
  redirectUrl: 'io.identityserver.demo:/oauthredirect',
  scopes: ['openid', 'profile', 'offline_access'],
  serviceConfiguration: {
    authorizationEndpoint: 'https://localhost:5101/connect/authorize',
    tokenEndpoint: 'https://localhost:5101/connect/token',
    revocationEndpoint: 'https://localhost:5101/connect/revoke',
  },
};

const newAuthState = await authorize(configs);

He is redirected to the log-in page of Identity Server. After user enters credentials, he is redirected back to the mobile app, but then he gets this error:
{
    "nativeStackAndroid": [
        {
            "methodName": "doInBackground",
            "lineNumber": 636,
            "file": "AuthorizationService.java",
            "class": "net.openid.appauth.AuthorizationService$TokenRequestTask"
        },
        {
            "methodName": "doInBackground",
            "lineNumber": 564,
            "file": "AuthorizationService.java",
            "class": "net.openid.appauth.AuthorizationService$TokenRequestTask"
        },
        {
            "methodName": "call",
            "lineNumber": 394,
            "file": "AsyncTask.java",
            "class": "android.os.AsyncTask$3"
        },
        {
            "methodName": "run",
            "lineNumber": 266,
            "file": "FutureTask.java",
            "class": "java.util.concurrent.FutureTask"
        },
        {
            "methodName": "run",
            "lineNumber": 305,
            "file": "AsyncTask.java",
            "class": "android.os.AsyncTask$SerialExecutor$1"
        },
        {
            "methodName": "runWorker",
            "lineNumber": 1167,
            "file": "ThreadPoolExecutor.java",
            "class": "java.util.concurrent.ThreadPoolExecutor"
        },
        {
            "methodName": "run",
            "lineNumber": 641,
            "file": "ThreadPoolExecutor.java",
            "class": "java.util.concurrent.ThreadPoolExecutor$Worker"
        },
        {
            "methodName": "run",
            "lineNumber": 923,
            "file": "Thread.java",
            "class": "java.lang.Thread"
        }
    ],
    "userInfo": null,
    "message": "Network error",
    "code": "token_exchange_failed",
    "line": 2552,
    "column": 45,
    "sourceURL": "http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mobileclient&modulesOnly=false&runModule=true"
}

Did anyone have this error and can anyone help me to solve it?
Thanks in advance.


text:
Q: How to model distance and interpret predictors I have a set of 2 - 10 explanatory variables which I'd like to use to predict the response variable, distance. The explanatory variables describe the flight of a projectile (velocity, spin, angle) and the conditions of the air it is flying through (temperature, altitude, etc.). I'd like to end up with an interpretable model that makes the best predictions possible, though I know these don't always go hand-in-hand. For example, I want to know much an increase/decrease in sidespin affects distance.
Now, this almost sounds like an ideal problem for linear regression, but the issue is the relationship between distance and angle, for example, is not linear, as if the ball is launched at too high of an angle (say 90 degrees straight up), obviously the distance will be small. In fact, I've tried a linear model already in which I square the angle term (and include some interaction terms), but the predictions are worse than I would like. Furthermore, since linear regression outputs a "line" in multi-dimensional space, it makes some negative predictions, and taking log() still doesn't help the predictions all that much.
Now, I talked to some people and we thought a neural network might be a good choice, since neural nets are very good approximators of functions, and I believe there is some underlying non-linear function at play here. Some of the neural nets I've tried so far give much better predictions than the linear model, however it obviously isn't easy to interpret the main effects.
Does anyone have any thoughts as for the overall approach here? Could it make sense to use a linear model to interpret the influence of the main effects on distance while then using a neural net to make predictions?

A: If you can, you would benefit from defining your models based on physical principles, to properly capture the nonlinear relationships you are interested in.
If that is not possible for all predictors, a simple alternative would be to use generalized-additive-models (GAMs), which are linear models that allow you to model responses as smooth, nonlinear functions of predictors. So distance can be made a smooth function of angle (and any other predictors), without specifying the functional form. Other predictors can be constrained to follow linear relationships, as in a linear regression.
You can also use neural networks or other machine learning methods, and then generate partial dependence plots to visualise the nonlinear response to specific predictors. This is a key trick in what is called 'interpretable machine learning', for which I recommend this free online book by Christoph Molnar.


text:
Q: Convert a user's 24h input to 12h So for some reason this comes up with an error message saying that 'no overload for method'ParseExact' takes 1 argument'. Does anyone know what I've done wrong?
 static void runTimeConverter()
{
 double arrivalTime;
 arrivalTime = getArrivalTime();
 string time = DateTime.ParseExact(arrivalTime).ToString("HH:mm tt");
 Console.WriteLine("Equals " + time);
}

 static double getArrivalTime()

    {
        Console.WriteLine
            ("Enter time in 24 hour format to convert to 12hour");
        string timeSelected = Console.ReadLine();
        int timeInput = int.Parse(timeSelected);
        return timeInput;
    }

A:
So for some reason this comes up with an error message saying that 'no overload for
  method'ParseExact' takes 1 argument'. Does anyone know what I've done
  wrong?

Yes. YOu can not read or refuse to process the error message the compiler shows you - that is VERY exact in what is wrong.
YOur code:

DateTime.ParseExact(arrivalTime)

That is one argument. The compiler says it is wrong.
If you check the documentation:
http://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx
it shows he method as:
public static DateTime ParseExact(
    string s,
    string format,
    IFormatProvider provider
)

THat is 3 arguments. You only give one. DOes not get more obvious. Fix your code.

A: Because ParseExact expects the exact format to parse the given string as date, which you aren't providing.


text:
Q: How to Remove Client Headers in Nginx before passing request to upstream server? The Upstream server is wowza , which does not accept the custom headers if I don't enable them on application level.
Nginx is working as a proxy server, from the browser I want to send few custom headers which should be received and logged by Nginx Proxy  but before forwarding request to upstream server those headers should be removed from the request.
So upstream server never come to know that there where any custom headers.
I tried proxy_hide_header as well as proxy_set_header "<header>" "" , but seems like they apply to response headers not the request headers.
And even if I accept to enable the headers on wowza, then again I am not able to find a way to enable headers at server level for all application. Currenlty I have to add headers to each newly created application which is not feasible for me to do.
Any help would be appreciated.

A: The proxy_set_header HEADER "" does exactly what you expect. See https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header.

If the value of a header field is an empty string then this field will not be passed to a proxied server:
proxy_set_header Accept-Encoding "";

I have just confirmed this is working as documented, I used Nginx v1.12.


text:
Q: Erro ao executar projeto no TomCat Olá pessoal estou tentando executar um projeto JavaWeb no TomCat, porém quando executo ele dá esse erro:

HTTP Status 404 - /Drogaria/faces/templates/modeloSistema.xhtml
type Status report
message /Drogaria/faces/templates/modeloSistema.xhtml
description The requested resource is not available.
Apache Tomcat/7.0.82

Em outros projetos executo e roda normal , só este que está com problemas, o servidor está configurado certinho, está estartado, e sincronizado.

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
 xmlns:h="http://java.sun.com/jsf/html"
 xmlns:f="http://java.sun.com/jsf/core"
 xmlns:p="http://primefaces.org/ui">

<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Drogaria</title>
</h:head>
<h:body>
 <p:layout fullPage="true">
  <p:layoutUnit position="north">
  </p:layoutUnit>

  <p:layoutUnit position="center">
  </p:layoutUnit>
 </p:layout>
</h:body>
</html>


text:
Q: Where can I find binance python documentation for USD-M futures? I am trying to build a cryptocurrency trading bot using binance as my chosen exchange. I have found the binance python documentation but this seems to be geared to spot accounts. I want to design my trading bot to trade on my USD-M futures account.
Where can I find documentation to help with this?


text:
Q: The method must return a double, but I am getting an error public double accessor(int n)
{
    switch(n)
    {
    case 0:
        return this.a;
        break;
    case 1:
        return this.b;
        break;
    case 2:
        return this.c;
        break;
    case 3:
        return this.d;
        break;
    case 4:
        return this.e;
        break;
    }
}

a,b,c,d,e are all of type double, but it's telling me that the break statements are unreachable and I must return a type double. I'm new to java so forgive if this sounds stupid

A: What if n isn't in the range of 0-4?  There is no case for that, and no associated return statement.
Have a default case that either returns a value (if that value is valid) or throws an IllegalArgumentException for it being an invalid value.
Also, although including break; statements is normally a good practice, here it is incorrect, because they're unreachable statements.  The return statement in a switch case is as good as a break here, because it also prevents "falling through" to the next case.

A: you can't call anything after you call return. Just delete de break after each return, and also make a default: case,


text:
Q: Remove duplication in OneToMany/ManyToOne bidirectional relationship using a JoinTable (with an OrderColumn) I have a OneToMany/ManyToOne bidirectional relationship using a join table. The children are in a List and are ordered.
Here's the setup:
Parent:
@OneToMany(cascade=CascadeType.ALL)
@JoinTable(
    name="parent_child",
    joinColumns=@JoinColumn(name="parent_id"),
    inverseJoinColumns=@JoinColumn(name="child_id")
)
@OrderColumn(name="child_order")
public List<Child> getChildren() {
    return children;
}

Child:
@ManyToOne
public Parent getParent() {
    return parent;
}

Here's my issue: The parent table is as expected, but here are the child and parent_child tables:
child:
int8 id,
int8 parent_id <---

parent_child:
int8 parent_id, <---
int8 child_id,
int8 child_order

There's duplication with the parent_id - it's specified in the join table and in the child table which means that it's possible to call parent.getChildren().get(0).getParent() and end up with a different parent than you started with, which should be impossible (and I'd like that to be enforced at the database level).
The only way I can see to fix this is to use a join column in the child, and not use a join table at all. But I don't like that because then I have to move the order to the child, plus the hibernate docs say that a JoinColumn with OneToMany should be avoided (but they don't really say why).
Is there any other way of getting rid of this duplication/possible inconsistency? I.e. some way of having the child know its parent by using the data from the join table?

A: Try this if it works. Note the use of JoinColumn
   @OneToMany(cascade=CascadeType.ALL)
   @OrderColumn(name="child_order")
   public List<Child> getChildren() {
         return children;
   }

child
   @ManyToOne
   @JoinColumn("parent_id")
   public Parent getParent() {
       return parent;
   }

A:
There's duplication with the parent_id - it's specified in the join table and in the child table which means that it's possible to call parent.getChildren().get(0).getParent() and end up with a different parent than you started with

I don't understand how can that be possible, when a child can have only one parent. There should be one and only one record int database for a given parent-child tuple and the child will never exists in any other tuple of parent-child. Ofcourse the parent will be repeated in the parent_child table but never will a child be repeated. Have you specified the foreign key constraints on the database tables? Use the mappedBy element on the getParent() method.

A: I answer to a similar question in Constraint violation in Hibernate unidirectional OneToMany mapping with JoinTable and OrderColumn when removing elements
Please have a look
I think your constraints on your association table is bad and incompatible with the principle of a List.


text:
Q: PermissionError: [Errno 13] Permission denied: Read Image pixel data using PIL I'm using PIL to get image pixel data and store it to an array but it is giving following error.
from PIL import Image
import os

image_data = []

path = "plasmodium_images/"
for i in os.listdir("images"):
        Image.open(path+i)

error
---------------------------------------------------------------------------
PermissionError                           Traceback (most recent call last)
6 path = "plasmodium_images/"
      7 for i in os.listdir("plasmodium_images"):
----> 8         Image.open(path+i)

c:\users\csvankhede\anaconda\envs\tensorflow2\lib\site-packages\PIL\Image.py in open(fp, mode)
   2310
   2311     if filename:
-> 2312         fp = builtins.open(filename, "rb")
   2313
   2314     try:

PermissionError: [Errno 13] Permission denied: 'plasmodium_images/plasmodium-phone-0001.jpg'

I have tried changing mode and giving full path also but it doesn't work.
.png can be opened but it doesn't work for .jpg images.

A: Try running your code from a command prompt that you are running as an administrator. Right click "command prompt" from the start menu and click "Run as Administrator."


text:
Q: Error: unable to use groupby to summarize table in Pandas I am trying to sum the elements in a df by column using Pandas, and I am obtaining an error. Here is the script
Thank you very much!
from google.colab import files
uploaded = files.upload()
import pandas as pd
import io
df = pd.read_csv(io.BytesIO(uploaded['Book1.csv']))
print(df)
df.groupby(['x']).sum()

         x;y
0  guazaba;1
1  guazaba;1
2  guazaba;1
3     pera;1

860                 in_axis, level, gpr = False, gpr, None
    861             else:
--> 862                 raise KeyError(gpr)
    863         elif isinstance(gpr, Grouper) and gpr.key is not None:
    864             # Add key to exclusions

KeyError: 'x'

A: Default separator for csv is ,, you separator is ;, so you should define it explicitly
df = pd.read_csv(io.BytesIO(uploaded['Book1.csv']), sep=';')