text:
Q: How to render a multiline UILabel with NSMutableAttributedString I am trying to create a multiline UILabel with an NSMutableAttributedString.
This works fine when I assign an attribute to the complete string like this:
UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,100)];
[contentLabel setLineBreakMode:NSLineBreakByWordWrapping];
[contentLabel setNumberOfLines:0];
[contentLabel setFont:[UIFont systemFontOfSize:13];

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"hello I am a long sentence that should break over multiple lines"];
[string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13] range:NSMakeRange(0, [string length])];

contentLabel.attributedText = string;

But I what I need is to apply a number of attributes for different subranges of the NSAttributedString (to bold certain words).
UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,100)];
[contentLabel setLineBreakMode:NSLineBreakByWordWrapping];
[contentLabel setNumberOfLines:0];
[contentLabel setFont:[UIFont systemFontOfSize:13];

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"hello I am a long sentence that should break over multiple lines"];
[string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13] range:NSMakeRange(3, 5)];

contentLabel.attributedText = string;

What I am finding is that if I do this, the text isn't rendered over multiple lines in the label anymore. It is rendered as a single line, centered vertically in the label's frame.
Is there something I'm missing here?

A: As discussed in the question's comments, the code presented in the question actually works correctly, and does render the attributed string as intended. (The problem was elsewhere in my code)

A: I use frequently the UITextView and assign it a text attributed with a similar way:
        // creiamo textView descrizione
    UITextView *description = [[UITextView alloc] init];
    description.frame = CGRectMake(20, 453, 500, 190);

    NSDictionary *attribute1 = @{NSForegroundColorAttributeName: [UIColor blackColor],
                                     NSBackgroundColorAttributeName: [UIColor clearColor],
                                     NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Bold" size:22.0],
                                     };

    NSDictionary *attribute2 = @{NSForegroundColorAttributeName: [UIColor blackColor],
                                        NSBackgroundColorAttributeName: [UIColor clearColor],
                                        NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:10],
                                        };

    NSDictionary *attribute3 = @{NSForegroundColorAttributeName: [UIColor blackColor],
                                           NSBackgroundColorAttributeName: [UIColor clearColor],
                                           NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14.0]
                                           };

    NSMutableAttributedString *info = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ %@ %@ \n\n%@ \n     ", string1, string2 , string3, string4]];

    [info setAttributes:attribute1 range:NSMakeRange(0, ([string1 length]))];
    [info setAttributes:attribute2 range:NSMakeRange(([string1 length]),([string2 length]+[string3 length]))];
    [info setAttributes:attribute3 range:NSMakeRange(([string1 length] [string2 length]+[string3 length]), [string4 length])];

    description.attributedText = info;
    description.backgroundColor = [UIColor clearColor];
    description.editable = NO;
    description.textColor = [UIColor blackColor];
    [viewInfo addSubview:description];
    [description sizeToFit];


text:
Q: Make file that compiles gcc and puts the objects in a separate folder I am trying to create a make file that will work accordingly
OBJECT_DIRECTORY := out/obj
C_SOURCE_FILES = (Path and files fetched from different make files)
CFLAGS += -mcpu=$(CPU) -mthumb -mabi=aapcs -mfloat-abi=soft
CFLAGS += -Wall -Werror
CFLAGS += -D$(DEVICE) -std=gnu99

$(OBJECT_DIRECTORY)/%.o: %.c
    $(CC) $(C_SOURCE_FILES) $(CFLAGS) -c -o $@ $<

I verified that the C_SOURCE_FILES variable actually contains the c source files. This since I am able to compile using this:
$(OBJECT_DIRECTORY)/%.o:
    $(CC) $(C_SOURCE_FILES) $(CFLAGS) -c

Problem with that is that the object files are not placed in the folder where I need them for the linking.
By the way, I am executing the make file from the Eclipse C/C++ IDE
I would be extremely happy if someone could help me solve this problem.

A: Try this:
$(OBJECT_DIRECTORY)/%.o: %.c
    $(CC) $(CFLAGS) -c -o $@ $<

You don't need the C_SOURCE_FILES variable here.  This recipe will create out/obj/{file}.o for every file called {file}.c.
You don't show it, but the dependency list for the executable being created from the object files must explicitly call out each object file.

A: I solved the problem, I think... By creating a list of target files to be used in the compilation.
# Create the object file names needed for the target. Make needs these file names as target for the compilation
TEMP := $(notdir $(C_SOURCE_FILES:.c=.o))
C_OBJECT_FILES := $(addprefix $(OBJECT_DIRECTORY)/, $(TEMP:.c=.o) )
TEMP_1 := $(notdir $(ASSEMBLER_SOURCE_FILES:.s=.o))
ASSEMBLER_OBJECT_FILES := $(addprefix $(OBJECT_DIRECTORY)/,$(TEMP_1:.s=.o) )

# Tells make to compile all the files in the C_OBJECTS_VARIABLE
all: $(C_OBJECT_FILES)

# Do the compilation of the c files and place the object files in the out/obj folder
$(C_OBJECT_FILES): $(C_SOURCE_FILES)
$(CC) $(CFLAGS)  -M $< -MF "$(@:.o=.d)" -MT $@
$(CC) $(CFLAGS) -c -o $@ $<

# Tells make to compile all the files in the ASSEMBLER_OBJECTS_VARIABLE
all: $(ASSEMBLER_OBJECT_FILES)

# Do the compilation of the assembler files and place the object files in the out/obj folder
$(ASSEMBLER_OBJECT_FILES): $(ASSEMBLER_SOURCE_FILES)
    $(CC) $(ASMFLAGS) -c -o $@ $<

This works well and consistently. Issue I have now is that the rule for linking is not executed at all...
## Link C and assembler objects to an .out file
$(BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out: $(C_OBJECT_FILES) $(ASSEMBLER_OBJECT_FILES) $(LIBRARIES)
    $(CC) $(LDFLAGS) -o $(BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out

I am wondering if it has anything to do with "all:"

A: Found the solution to that problem as well. I created a couple of new rules to make sure that the linking is getting executed. Now the make file works well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript div box that follow cursor position I'm trying to create a circle navigation button to follow mouse movement when the cursor is inside a certain box.

var cer = document.getElementById('cerchio');
var pro = document.getElementById('prova');

pro.addEventListener("mouseover", function() {
var e = window.event;
var x = e.clientX;
var y = e.clientY;
cer.style.top = y + "px";
cer.style.left = x + "px";
cer.style.transition = "2s";
});

pro.addEventListener("mouseout", function() {
cer.style.top = "15px";
cer.style.left = "15px";
});
#prova {
width: 200px;
height: 200px;
border: 1px solid black;
}

#cerchio {
width: 90px;
height: 90px;
border: 1px solid red;
border-radius: 90px;
position: absolute;
left: 15px;
top: 15px;
}

#innercircle {
width: 120px;
height: 120px;
position: relative;
left: 40px;
top: 30px;
border: 1px solid red;
}

so it actually follows the first position of the mouse inside the black bordered box, i want it to update the cursor positioning every time and follow it, also i don't want the red circle to go out the red box, any suggestion? please javascript only not jquery, thanks!

A: The main problem is your usage of window.event and wrong event handlers.
Here's a solution that uses standard event handling:

var cer = document.getElementById('cerchio');
var pro = document.getElementById('prova');
var proR = pro.getBoundingClientRect();
var cirR = cer.getBoundingClientRect();
// radii
var rW = (cirR.right - cirR.left) / 2;
var rH = (cirR.bottom - cirR.top) / 2;
// page coords of center
var oX = (proR.right + proR.left) / 2;
var oY = (proR.bottom + proR.top) / 2;
var x, y;
// max movement
var max = 15;

function setPos(x, y) {
  cer.style.left = (x + oX - rW) + "px";
  cer.style.top = (y + oY - rH) + "px";
}

pro.addEventListener("mouseleave", function() {
  setPos(0, 0);
});

pro.addEventListener("mousemove", function(e) {
  // 0,0 is at center
  x = e.clientX - oX;
  y = e.clientY - oY;
  // limit to max
  if (x < -max) x = -max;
  if (x > max) x = max;
  if (y < -max) y = -max;
  if (y > max) y = max;
  // set circle position
  setPos(x, y);
});

setPos(0, 0);
#prova {
  display: inline-block;
  border: 1px solid black;
  padding: 40px;
}

#innercircle {
  width: 120px;
  height: 120px;
  border: 1px solid red;
}

#cerchio {
  width: 90px;
  height: 90px;
  border: 1px solid red;
  border-radius: 50%;
  transition: .5s;
  position: absolute;
  pointer-events: none;
}

#prova,
#innercircle,
#cerchio {
  box-sizing: border-box;
}

I've also changed the calculation to

*

*determine the x,y values such that the center of the area is (0, 0)

*limit the values to a set boundary

*add back the offset to position the circle

A: "mousemove" is the event you want to track for this as you want the position of the mouse as it moves inside the element. You should also pass the event as a callback to the event handler
I also fixed the positioning using the getBoundingClientRect() method.

var cer = document.getElementById('cerchio');
var pro = document.getElementById('prova');
var innerC = document.getElementById('innercircle');

innerC.addEventListener("mousemove", function(e) {
  var square = this.getBoundingClientRect();
  var squareX = square.x;
  var squareY = square.y;
  var squareWidth = square.width;
  var squareHeight = square.height;
  var mouseX = e.clientX;
  var mouseY= e.clientY;

  var x = e.clientX;
  var y = e.clientY;

  cer.style.top = (-squareY + mouseY - (squareHeight / 2 - 15)) + "px";
  cer.style.left = (-squareX + mouseX - (squareWidth / 2 - 15)) + "px";
  cer.style.transition = "2s";
});

innerC.addEventListener("mouseout", function() {
  cer.style.top = "15px";
  cer.style.left = "15px";
});
#prova {
width: 200px;
height: 200px;
border: 1px solid black;
}

#cerchio {
width: 90px;
height: 90px;
border: 1px solid red;
border-radius: 90px;
position: absolute;
z-index: -1;
left: 15px;
top: 15px;
}

#innercircle {
width: 120px;
height: 120px;
position: relative;
  z-index: 2;
left: 40px;
top: 30px;
border: 1px solid red;
}

A: Your main problem is that you're using 'mouseover'. This event only activates when the mouse enters the element. This way, if works the first time you move over the rectangle, or when you move between the black and red rectangles.
If you use 'mousemove', it works right.

var cer = document.getElementById('cerchio');
var pro = document.getElementById('prova');

pro.addEventListener("mousemove", function() {
var e = window.event;
var x = e.clientX;
var y = e.clientY;
cer.style.top = y + "px";
cer.style.left = x + "px";
cer.style.transition = "2s";
});

pro.addEventListener("mouseout", function() {
cer.style.top = "15px";
cer.style.left = "15px";
});
#prova {
width: 200px;
height: 200px;
border: 1px solid black;
}

#cerchio {
width: 90px;
height: 90px;
border: 1px solid red;
border-radius: 90px;
position: absolute;
left: 15px;
top: 15px;
}

#innercircle {
width: 120px;
height: 120px;
position: relative;
left: 40px;
top: 30px;
border: 1px solid red;
}


text:
Q: Как установить Google Play Music Desktop Player в Fedora? Пытаюсь поставить GPMDP в ОС Fedora Workastation 31. Способ который использовал:
sudo snap install google-play-music-desktop-player

после использования этой команды GPMDP ставится, но не запускается с ошибкой
WARNING: cgroup v2 is not fully supported
yet, proceeding with partial confinement

(google-play-music-desktop-player:3150):
Gtk-WARNING **: 10:40:11.680: cannot open
display: :0

Удаляю snap пакет, иду на сайт разработчков и скачиваю версию для Fedora x86_64(именно такая у меня стоит).
Далее делаю
cd Загрузки
sudo rpm -i google-play-music-desktop-player-4.6.1.x86_64.rpm

Пакет устанавливается успешно, но при попытке запуска Возникает
Ошибка сегментирования, стек сброшен на диск
Очень хочется использовать именно этот плеер, да и поддержка Fedora на сайте разрабов заявлена. Как поставить?
В Ubuntu 18.04 при скачивании с сайта разраба и установки .deb пакета путем
sudo dpkg -i <имя пакета>

Недоустанавливаются зависимости но помогает
sudo apt install -f

Может быть есть в Fedora аналог такой команды, которая установит зависимости для пакета?
В хэлпе по yum вычитал про
sudo yum-builddep <имя пакета>

Но попытка им вспользоваться не увенчалась успехом ибо ошибка
нет подходящих пакетов: google-play-music-desktop-player
Ошибка: Некоторые пакеты не удалось найти

и не понятно, какие именно пакеты не удалось найти. Я б их сам поискал, если б знал какие. Как узнать, какие пакеты нужно доустановить?
UPD:
Использовал
sudo yum deplist google-play-music-desktop-player

но данная команда ничего не вывела
UPD2:
нашел проблему. В Fedora gnome запускается на Wayland по умолчанию. Переключил на Gnome на xorg при входе в систему, переустановил программу, перезагрузился, все заработало...

A: Самый простой способ установки данного приложения, через flatpak. На Flathub оно есть. Нормально устанавливается и стабильно работает с Wayland в Fedora 31 Workstation.
Установил и проверил на своей системе:

Следом перегрузился в Xorg и проверил там, также всё стабильно работает.
Если репозиторий Flathub ранее не добавлялся на машину, то до установки необходимо будет его добавить:
$  flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo

Далее установка при помощи магазина приложений, или через терминал:
$ flatpak install flathub com.googleplaymusicdesktopplayer.GPMDP

Запуск через меню, либо с помощью терминала:
$ flatpak run com.googleplaymusicdesktopplayer.GPMDP


text:
Q: If any of these variables equals this, corresponding variable does this. How to code this? If this question was repeated, I'm sorry but I couldn't find the answer.
My question is how to code for "If any of these variables equals this" and change it to a new value corresponding to that variable. For instance, I'm trying to do HTML conversions:
        int hex1 = (int)(Math.floor((work[j][k]) / 1048576)) % 16;
        int hex2 = (int)(Math.floor((work[j][k]) / 65536)) % 16;
        int hex3 = (int)(Math.floor((work[j][k]) / 4096)) % 16;
        int hex4 = (int)(Math.floor((work[j][k]) / 256)) % 16;
        int hex5 = (int)(Math.floor((work[j][k]) / 16)) % 16;
        int hex6 = (int)(work[j][k]) % 16;

Above would be my list of multiple variables. So pseudocode would be "if any of the above variables equals this". So if either hex1,hex2,hex3,hex4,hex5,hex6 equals, say 10. Then the corresponding variable would do something. For instance:
         String html = "";
           if (hex1==10){
              html += "A";
           }
           else if (hex1==11){
              html += "B";
           }
           else if (hex1 >= 0 && hex1 <=9){
              html += hex1;
           }
        html = "#" + html;

Is there a way to do this above code, without having to copy/paste the code 6 different times with a different variable each time (ie, hex1 would be hex2, hex3,...)?

A: You can create a function and call that with different values of variables:
void doSomething(int in){
 // put your logic here
}

doSomething(hex1);
doSomething(hex2);

and so on...

A: Yes, you are looking for Maps. Use a Map<Integer, String> in your case. Then you could do:
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(10, "A");
map.put(11, "B");
String str = map.get(hex5);
if (str != null)
{
    html += str;
}

Please, use arrays, instead of hex1, hex2, hex3, hex4, etc... Create a simple:
int[] hex = new int[6];

Next you could optimize those lines to something like this:
int hex5 = (int)(Math.floor((work[j][k]) / 16)) % 16;

would be:
int hex5 = (work[j][k] >> 4) & 0xF;

which is much much faster, assuming work[j][k] is an integer.

A: Try something like this:
int[] hex = new int[6];

//code to fill in hex digits

for(int i = 0; i < hex.length;i++){
    if(hex[i]==10){
        //do stuff
    }else if(hex[i]==11){
        //do stuff
    }
   //other conditions

}

EDIT:
Or you could use a list to contain arbitrary numbers of hex digits as follows:
List<Integer> hexList = new ArrayList<Integer>();

//code to add hex digits to list

if(hexList.contains(10)){
//do stuff
}else if(hexList.contains(11)){
//do stuff
}
//other conditions


text:
Q: Gradient derived from Jacobian? I was reading this wikipedia page on gradient descent (section: Solution of non-linear system) when I came across this formula:
$\nabla F(\mathbf {x} ^{(0)})=J_{G}(\mathbf {x} ^{(0)})^{\mathrm {T} }G(\mathbf {x} ^{(0)})$
How did this equation come about? Sorry for my shaky calculus if this sounds stupid, but this is the only point in this section that I don't understand.

A: From the article
$$
F({\bf x}) = \frac{1}{2}G^T({\bf x}) G({\bf x}) = \frac{1}{2}\sum_j G_j({\bf x}) G_j({\bf x}) \tag{1}
$$
Take the derivative w.r.t to $x_i$
\begin{eqnarray}
\frac{\partial F}{\partial x_i} &=&
\frac{1}{2}\sum_j \frac{\partial}{\partial x_i}\left[G_j({\bf x}) G_j({\bf x}) \right]  = \sum_j  \color{blue}{\frac{\partial G_j({\bf x})}{\partial x_i}} G_j({\bf x}) \\
&=& \sum_j \color{blue}{[J_G({\bf x})]_{ij}} G_j({\bf x}) = [J_{G}({\bf x}) G({\bf x})]_i \tag{2}
\end{eqnarray}
where the $(i,j)$-th component of matrix $J_G$ is defined as
$$
[J_G({\bf x})]_{ij} = \frac{\partial G_j({\bf x})}{\partial x_i} \tag{3}
$$
Eq. (2) tells you what the $i$-th component of the gradient is, if you put them all together you get
$$
\nabla F({\bf x}) = J_G({\bf x}) G({\bf x}) \tag{4}
$$


text:
Q: finding optimum lambda and features for polynomial regression I am new to Data Mining/ML. I've been trying to solve a polynomial regression problem of predicting the price from given input parameters (already normalized within range[0, 1])
I'm quite close as my output is in proportion to the correct one, but it seems a bit suppressed, my algorithm is correct, just don't know how to reach to an appropriate lambda, (regularized parameter) and how to decide to what extent  I should populate features as the problem says : "The prices per square foot, are (approximately) a polynomial function of the features. This polynomial always has an order less than 4".
Is there a way we could visualize data to find optimum value for these parameters, like we find optimal alpha (step size) and number of iterations by visualizing cost function in linear regression using gradient descent.
Here is my code : http://ideone.com/6ctDFh
from numpy import *

def mapFeature(X1, X2):
    degree = 2
    out = ones((shape(X1)[0], 1))
    for i in range(1, degree+1):
        for j in range(0, i+1):
            term1 = X1**(i-j)
            term2 = X2 ** (j)
            term  = (term1 * term2).reshape( shape(term1)[0], 1 )
            """note that here 'out[i]' represents mappedfeatures of X1[i], X2[i], ..........   out is made to store features of one set in out[i] horizontally """
            out   = hstack(( out, term ))
    return out

def solve():
    n, m = input().split()
    m = int(m)
    n = int(n)
    data = zeros((m, n+1))
    for i in range(0, m):
        ausi = input().split()
        for k in range(0, n+1):
            data[i, k] = float(ausi[k])
    X = data[:, 0 : n]
    y = data[:, n]

    theta = zeros((6, 1))

    X = mapFeature(X[:, 0], X[:, 1])
    ausi = computeCostVect(X, y, theta)
    # print(X)
    print("Results usning BFGS : ")
    lamda = 2
    theta, cost = findMinTheta(theta, X, y, lamda)

    test = [0.05, 0.54, 0.91, 0.91, 0.31, 0.76, 0.51, 0.31]
    print("prediction for 0.31 , 0.76 (using BFGS) : ")
    for i in range(0, 7, 2):
        print(mapFeature(array([test[i]]), array([test[i+1]])).dot( theta ))

    # pyplot.plot(X[:, 1], y, 'rx', markersize = 5)
    # fig = pyplot.figure()
    # ax = fig.add_subplot(1,1,1)
    # ax.scatter(X[:, 1],X[:, 2], s=y) # Added third variable income as size of the bubble
    # pyplot.show()

The current output is:
183.43478288
349.10716957
236.94627602
208.61071682
The correct output should be:
180.38
1312.07
440.13
343.72


text:
Q: Touch function in Postgres with PostGis I have PostgreSQL installed with PostGis, I try to run the following:
SELECT N1.edname AS "Borders Royal Exchange A"
FROM eds_census2011 N1, eds_census2011 N2
WHERE Touch(N1.the_geom, N2.the_geom)
AND N2 = 'Royal Exchange A'

And I get an error (below) is there anything I have to add to Postgres or enable something?

ERROR:  function touch(geometry, geometry) does not exist
LINE 3: WHERE Touch(N1.the_geom, N2.the_geom)
              ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

********** Error **********

ERROR: function touch(geometry, geometry) does not exist
SQL state: 42883
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Character: 96

A: Run these two queries (in the same session you are trying the above query) to pin down the problem:
In which schema does the function touch() live?
SELECT p.proname, n.nspname
FROM   pg_proc p
JOIN   pg_namespace n ON n.oid = p.pronamespace
WHERE  proname = 'touch';

What is the current schema search_path of my role:
SHOW search_path;

If the function exists, the schema must be in the current search_path so that Postgres can find it. How to adapt the search_path?
How does the search_path influence identifier resolution and the "current schema"
BTW, I can't find a function Touch() in the function reference of the Postgis manual. There is one called ST_Touches(). Any chance you meant that one?
Be aware that this query has a cost of O(N²), since it calculates a value for every combination of any two qualifying rows in eds_census2011. If your condition N2.edname = 'Royal Exchange A' is selective enough, this won't be a problem.
Also, you may want to exclude rows joining themselves with an additional WHERE item like:
AND N1.pk_id <> N2.pk_id

Error after Update
Your updated query makes more sense:
SELECT N1.edname AS "Borders Royal Exchange A"
FROM   eds_census2011 N1, eds_census2011 N2
WHERE  ST_Touches(N1.the_geom, N2.the_geom)=1
AND    N2.edname = 'Royal Exchange A';

But ST_Touches() returns boolean, so the Where clause should just be:
WHERE  ST_Touches(N1.the_geom, N2.the_geom)

A: Got it - thanks to everyone, used the following:
SELECT N1.edname AS "Borders Royal Exchange A"
FROM eds_census2011 N1, eds_census2011 N2
WHERE ST_Touches(N1.the_geom, N2.the_geom)
AND N2.edname = 'Royal Exchange A'


text:
Q: 'linear-gradient(rgb(255, 255, 255), rgb(230, 230, 230))' Http Requests every day I get a ton of these requests below, 400 today which throw 404 errors. Where and why are these being called to my site?  The user agent looks legit.
System.Web.HttpException: A public action method 'linear-gradient(rgb(255, 255, 255), rgb(230, 230, 230))' was not found on controller 'Tournaments.Controllers.EventController'.

Url
https://basketball.exposureevents.com/128833/third-annual-its-lit-basketball-tournament/linear-gradient(rgb(255, 255, 255), rgb(230, 230, 230))

A: I've been receiving similar requests to my site on a daily basis for a long time.
The requests contain a uriEncoded linear-gradient. The referer is the same URL minus the gradient crap. The userAgent indicates it's done primarily by two crawlers: Squidbot and Echobox.
We couldn't find any exact matches for the linear-gradient in our code. We use hsla format for our colors and the requests contained rgba colors!
But then I realized: yep, we did have the exact same gradient in our code, just in a different format.
The origin was a CSS file where this gradient was used as a background-image
background-image: linear-gradient(...
What assume is going on: These crawlers are trying to crawl all images on a site by making requests to any background-image values they find.
And they interpret all css in their preferred color format (rgb based instead of hsl) so that's why there's often no direct match for the exact code.

A: Just aborted the requests.
<rule name="LinearGradientRequest" enabled="true" stopProcessing="true">
          <match url="^.*linear-gradient.*$" />
          <action type="AbortRequest" />
        </rule>


text:
Q: How to define stateles services that will run per environment in Service Fabric I have an application manifest with five stateless services defined. I have multiple Application Parameters files, one per environment, to change the number of instances for each service. For one of the environments, I don't want two specific services to run at all (zero instances) but SF doesn't accept 0 instance parameter. How can I achieve that?

A: The best way to achieve this would be to stop using default services and instead use a script to start the required services in the appropriate environments.
The following links offer some comprehensive detail on this subject:
https://stackoverflow.com/a/50445801/490282
https://devblogs.microsoft.com/premier-developer/how-not-to-use-service-fabric-default-services/


text:
Q: How can the gsutil cp command copy files older than x minutes? The current Powershell script used to archive files and subdirectories recursively to a cloud bucket is as follows:
gsutil rsync -u -r -C M:\backups gs://archive-bucket
https://cloud.google.com/storage/docs/gsutil/commands/cp
This works fine, however I need a filter to only affect files older than x minutes. Based on the documented feature (see link above) of being able to pipe in a file list, I'd like to apply the timestamp rule to generate a filtered list of all files and subdirectories under M:\backups recursively with some script represented by the placeholder "list_generator" into via -I, the standard input, provided by using cp instead of rsync, roughly like this:
list_generator | gsutil -m cp -n -r -c -I gs://archive-bucket
I presume in the above that the argument -r won't be needed as the recursive action will be relocated into the preceding routine represented by list_generator, while the -n and -c arguments need to be retained to prevent destination overwriting and provide error handling.

A: Your question boils down to how to get a list of the paths of those file in the directory tree of M:\backups whose last-modified timestamp (LastWriteTime) is older than x minutes ago:
$cutoffDate = (Get-Date).AddMinutes(-20) # example: 20 minutes

Get-ChildItem -File -Recurse M:\backups |
  Where-Object LastWriteTime -lt $cutoffDate |
    ForEach-Object FullName |
      gsutil -m cp -n -c -I gs://archive-bucket

Note:

*

*In Windows PowerShell, you'll have to set preference variable $OutputEncoding to the character encoding that gsutil expects, so that file names with non-ASCII characters are properly passed; in PowerShell [Core] 6+, $OutputEncoding defaults to UTF-8.

*In PowerShell [Core] 6+, the ForEach-Object FullName command is no longer required, because the System.IO.FileInfo instances output by Get-ChildItem then consistently implicitly stringify to the value of their .FullName properties.


text:
Q: How do you compare a string to a vector value? How to you do a string comparison in a to a value in a vector<std::string>?
I tried str, the error is printed below.
.....
    vector<std::string> dat;
    vector<std::string> pdat;
    dat = my();
    for(int b = 2; b < dat.size(); b+=7){
    //      cout << dat[b] << " " << endl;
            if(!strcmp(dat[b], "String\n"){    // The error is here
                    pdat.push_back(dat[b]);
            }
    }

my.cpp: In function 'std::vector > ngr()':
my.cpp:53:32: error: cannot convert '__gnu_cxx::__alloc_traits > >::value_type {aka std::basic_string}' to 'const char*' for argument '1' to 'int strcmp(const char*, const char*)'

A: std::string is compared with plain ==. This works because the == operator is overloaded to do a string comparison for std::strings.
if (dat[b] == "String\n") {

If you're dealing with C++ strings, you shouldn't need any of the str* functions from string.h, so you might as well not include it at all.

A: Simply use operator== on to compare an std::string and a const char* :
if(dat[b] == "String\n"){    //
    pdat.push_back(dat[b]);
}

For the record, the exact overload used here is the function template :
template< class CharT, class traits, class Alloc >
bool operator==( const basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs );

strcmp (that you dont need here, and rarely need in C++) expects const char* arguments :
int strcmp( const char *lhs, const char *rhs );

So you could (but shouldn't) invoke it with th help of the c_str() member function :
if(!strcmp(dat[b].c_str(), "String\n")
...

A: strcmp() expects 2 const char*s but dat[b] is a string, so you aren't comparing apples with apples.
You can either do
if(!strcmp(dat[b].c_str(), "String\n"){
Or
if (dat[b] == "String\n") {
The second is the more C++ approach.


text:
Q: SpotBugs SE_NO_SERIALVERSIONID not triggering I am trying to add SpotBugs to my project specifically for SE_NO_SERIALVERSIONID and after running with effort=max I don't see a single class detected, but we know 10 examples we testing to see if they would get detected... all classes have this pattern
public final class SessionInfo implements Serializable
{
...
}

so we know clearly that the check should have happened but didn't.
Is there a way to see why or to explicitly enable this check?
EDIT:
I am trying to debug why this isn't triggering and see it should looking at the spotbugs source code https://github.com/spotbugs/spotbugs/blob/master/spotbugs/src/main/java/edu/umd/cs/findbugs/detect/SerializableIdiom.java#L410-L413
When I turn on debug logging I see
[spotbugs] Directly implements Serializable: org/apache/cassandra/streaming/SessionInfo
...
 [spotbugs] org.apache.cassandra.streaming.SessionInfo
 [spotbugs]   hasPublicVoidConstructor: false
 [spotbugs]   superClassHasVoidConstructor: true
 [spotbugs]   isExternalizable: false
 [spotbugs]   isSerializable: true
 [spotbugs]   isAbstract: false
 [spotbugs]   superClassImplementsSerializable: false
 [spotbugs]   isGUIClass: false
 [spotbugs]   isEjbImplClass: false
 [spotbugs]   isJSPClass: false

Not every variable is logged, but knowing the code being inspected it really should trigger...

A: In ant I set reportLevel="low", seems that this was getting filtered out


text:
Q: HATEOAS and storage of resource URL I have my system which receives data from another service and then I show the data to my users. I'd like to store an ID or a link to the data. Then UI will go for the data using the ID/link.
If we were to use HATEOAS, we'd go with links, so:

*

*Poll the data from that service

*Store links to the resources

*When UI opens - it gets the links from my DB and follows those links

But if service location changes or the URL format changes - we get broken links. Of course we can go with hacks like nginx URL rewrite, but this isn't pretty. Anyone has a good solution except for abandoning HATEOAS in this case?

A: TBH this isn't a HATEOAS issue, its just simple backwards compatibility or version management.
If you release a backward incompatible version of your api, one does not simply decommission the previous version. You have to keep it up and route the old version traffic to it with for example header or path routing.
Once the v-Old traffic drops to zero, then you can turn it off. This requires that you reach out to your consumers and get them to upgrade their systems.


text:
Q: jQuery: slide header when user scrolls past a point I have the following jQuery code:
if($(window).scrollTop()>=220) {
                    $('#header nav').slideUp('fast').removeClass('fixed');
                } else {
                    $('#header nav').addClass('fixed').slideDown('fast');
                }

What happens is that when a user scrolls further than 220 pixels down the page the header will get class of fixed and then slide down. When the user moves back up again then the header will slide up and have its class of fixed removed. The user will never see the header move back into its original position as its done around 180 pixels so is off screen.
The problem however is that it will do the slide over and over again when ever the user scrolls which isn't quite what I want. I've looked at the stop method but stopping the current animation is also not what I need.. Any ideas on how to fix this?
The code above is a function called like so:
$(window).scroll(function() {
                    fixedHeader();
                });

A: You want to change the if($(window).scrollTop()>=220) { line to be checking whether the user has transitioned from 0-220 to 220+ or reverse, rather than every the scroll wheel is used.
An example tutorial with lots of comments can be found here.

A: Doing this fixes the issue:
if(!$('#header nav').hasClass('fixed')) {
                        $('#header nav').addClass('fixed').slideDown('fast');
                    }

A: This resource might help you: Scroll Activated slide Down
$(function() {
    var bar = $('#headerSlideContainer');
    var top = bar.css('top');
    $(window).scroll(function() {
        if($(this).scrollTop() > 50) {
            bar.stop().animate({'top' : '0px'}, 500);
        } else {
            bar.stop().animate({'top' : top}, 500);
        }
    });
});

A: Try something like this, it worked for me.
<SCRIPT>
$(document).ready(function() {

var div = $('#header');
var start = $(div).offset().top;

$.event.add(window, "scroll", function() {
    var p = $(window).scrollTop();
    $(div).css('position',((p)>start) ? 'fixed' : 'static');
    $(div).css('top',((p)>start) ? '0px' : '');
});

});
</SCRIPT>

Taken from
Fixed Header


text:
Q: Getting AJAX request from Rails to activate I am trying to get JQueryUI autocomplete to work in a simple text box, and I am seeing no response in the browsers. I suspect I do not have things wired up completely. I'd also like to do it as "Rails 3" as possible.
In the controller (Brand is the model, derived from ActiveRecord::Base, with field 'name'):
class WelcomeController < ApplicationController
  def show
    @names = Brand.all.map(&:name)
    respond_to do |format|
      format.html
      format.js
    end
  end
end

show.html.erb:

Welcome

<%= form_tag :method => :get do %>
<%= text_field_tag :name %>
<% end %>

show.js.erb:
<%= raw @names %>

In application.js:
$(function() {

  $('brand_name').autocomplete({
    source: '/brands/new.js'
  });
});

What am I doing wrong, in terms of getting the making an AJAX request that will be handled by the Javascript I have set up?

A: Firstly, make sure that what you return from the server is really a JSON array. This is required by the jQuery UI autocomplete. Try rendering JSON  instead of Javascript:
respond_to do |format|
  format.html
  format.json { render :json => @names }
end

Then give your text field a proper class or id. Otherwise, I don't know how you want to match the element with jQuery.
<%= text_field_tag 'brand_name', nil, :class => 'brand_name' %>

Lastly, correct the javascript.
 $(function() {
   $('.brand_name').autocomplete({
     source: '/brands/new.json'
   });
 });

If another problem appears, use the webkit inspector to checkout if you receive the correct data from the server and its console whether there is a javascript error.


text:
Q: 'script-src' was not explicitly set but it was? I have added the script-src CSP directive to my AWS CloudFront distribution and my javascript will not run. In the browser console i can see the following error:
Refused to execute inline script because it violates the following Content Security
Policy directive: "default-src 'self' <<LIST OF DOMAINS>>
Either the 'unsafe-inline' keyword, a hash ('sha256-123abc='), or a nonce ('nonce-...') is required
to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used
as a fallback.

However, my CSP has the following code in it:
; script-src 'sha256-123abc=' "

When i remove the hash and use 'self', the script-src directive is picked up but that way my script can't run... does anyone know what the problem could be?

A: The problem here was that the CloudFront distribution was caching the response for a long period of time. I disabled caching and the problem was solved!


text:
Q: Gzip Mutliple files using single command Want to Gzip my all the .csv files into a gzip file.
I am using this command.
gzip *.csv;

Problem File contains '//' in its name that's why command is giving error.
Error : - '//File.csv' is not a directory or file.
So please suggest me what ways i can do this successfully.
one solution i thought.
gzip '//File1.csv' '//File2.csv' '//File3.csv'

Please suggest me if this is the right way to perform the same.

A: There are only two characters that are really not allowed in a filename in unix, and you've got one of them.
https://stackoverflow.com/questions/457994/what-characters-should-be-restricted-from-a-unix-file-name
Are the files on a usb stick formatted as some exotic file system?  You really have to try hard to get a "/" into a filename in unix.
http://www.unix.com/tips-and-tutorials/198879-how-manage-file-names-special-characters.html has some suggestions, the easiest of which is to go back to what ever system produced the files in the first place.

A: Use a loop! for F in *.csv; do gzip "$F"; done will work because of the quotes around $F


text:
Q: SQL Merge (with Temp Table) failing on SubQuery returned more than 1 value (But I am not using a Sub-Query.. in the update) I am hoping someone can help me out of this tedium...!?
As the title suggests I have a Temp Table (create dynamically in a select statement):
SELECT *
INTO #results
FROM Table_1
CROSS APPLY (   SELECT TOP 1 *
                FROM Table_2
                WHERE (Table_1.ItemId = Table_2.ItemId)
                ORDER BY CreatedDt DESC
             )

... which as you can see uses a Sub-Query in a cross join.
Next I am trying to use this temp table #results to update a related table with its values. have tried using an update:
UPDATE a
SET a.StatusId = b.StatusId
FROM Table_1    a
INNER JOIN #results     b on (a.ItemId = b.ItemId)

and with a Merge:
MERGE INTO Table_1 a
USING #results b
ON (a.ItemId = b.temId)
WHEN MATCHED THEN UPDATE SET a.StatusId = b.StatusId;

but I seem to always get a response:

Msg 512, Level 16, State 1, Procedure trg_dbo_PBITree_TreeModel_HierarchicalEscalationHistory_InsertNode,
  Line 7 [Batch Start Line 11] Subquery returned more than 1 value. This
  is not permitted when the subquery follows =, !=, <, <= , >, >= or
  when the subquery is used as an expression.

When I query the two tables in question (#results & Table_1) they both have 1 to 1 relationships and cannot see at all where it could be hiding some kind of Subquery!?
Can anyone help quickly on this at all please? This seems to be 1-0-1 stuff and its baking my burger!
-- Edit --
I have taken a look at the Trigger mentioned in the error message as it was suggested it could be trying to handle a single row update instead of a multiple row update which is what I am doing. Nothing looking too unusual to me...?
ALTER TRIGGER [dbo].[trg_dbo_PBITree_TreeModel_HierarchicalEscalationHistory_InsertNode]
ON [dbo].[Table_1]
AFTER UPDATE
AS
BEGIN
    -- NodeModelInsertOrUpdateTPH
    IF ((select [Item] from inserted) = 'X')
        BEGIN
            UPDATE tx
            SET
                tx.LastUpdatedBy = i.LastUpdatedBy,
                tx.LastUpdatedAt = i.LastUpdatedAt
            FROM
                [dbo].[Table_X] tx,
                inserted i
            WHERE
                tx.OtherItemId = i.OtherItemId
        END
END

Anyone have any ideas?

A: Your trigger is the issue here. Your IF statement has a query which would return more than 1 row and that exact message would be the result. You should make your trigger tolerant of multiple row operations. Here is the same logic but it can handle any number of rows being updated.
ALTER TRIGGER [dbo].[trg_dbo_PBITree_TreeModel_HierarchicalEscalationHistory_InsertNode]
ON [dbo].[Table_1]
AFTER UPDATE
AS
BEGIN
    UPDATE tx
    SET
        tx.LastUpdatedBy = i.LastUpdatedBy,
        tx.LastUpdatedAt = i.LastUpdatedAt
    FROM
        [dbo].[Table_X] tx
        join inserted i ON tx.OtherItemId = i.OtherItemId
        where i.Item = 'X'
END


text:
Q: Using polymorphic queries over interfaces in RavenDB I'm interested in switching over our application (or parts of it) to use RavenDB from SQL server with NHibernate.
The key feature that I can't seem to find in Raven is the usage of interfaces for queries eg:
ISearchable
{
  string Name {get;set;}
}

Class1 : ISearchable
{
  string Name {get;set;}
}
Class2 : ISearchable
{
   string Name {get;set;}
}

In NH I can search for the contents of the Name field in any ISearchable: QueryOver<ISearchable>().
I can't seem to find this in Raven, am I missing something? The closest that I've found is changing the string part at the front of the identifier, which I don't want to do; the main function of Class1 and Class2 is not to be searchable!
Thanks
Stu

A: Define an index like:
// ByName
from doc in docs
select new { doc.Name }

session.Query("ByName");


text:
Q: Is there a way to determine gaps in try/catch coverage? I'm debugging a service that's experiencing some problems on start-up. To aid me in this, I'm wrapping pretty much everything in a try/catch block, and writing any errors to a file. I don't want to put them in every method, I just want to put them in the highest level methods so that they catch exceptions from other methods.
Something is getting through, though, as the service does stop under some conditions. Is there a way to determine where the gaps in my try/catch coverage are, other than by sight?

A: You can catch AppDomain level exceptions like this:
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

void CurrentDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
{

    //Object exception = e.ExceptionObject;
    //Boolean terminating = e.IsTerminating;
}

You can check out this link for more examples.

A: try to try/catch main function and all thread functions. This should fill the gaps, unless third party code spawns threads

A: You didn't specify the environment (windows-service could mean managed or unmanaged). I'm going to guess you're working in native code, probably C or C++. If that's the case you need to be certain you're using structured exception handling from windows and not the C++ try/catch mechanism. Depending on your compiler vendor, the C++ implementation can't catch all exceptions.
In managed code, depending on framework version there are unhandleable exceptions. Excluding those, you also can fail to catch an exception if you don't prepare a constrained region and carefully follow the CER rules. Also as someone else mentioned, you can watch unhandled exceptions in your AppDomain. (You may not be in a single app domain but this is uncommon and you'd probably know if you weren't).
One more thing to remember in either case is that each thread has it's own stack and set of exceptions. If you're trying to try/catch all exceptions, you need to catch every thread that is working on your behalf. In managed code, the finalizer thread (garbage collector thread that executes "destructors" or finalizer code) is one place that is often missed.
However, before I jumped to either of those, I'd look for a process exit or a non-exception exit clause.


text:
Q: how to check whether CMake is installed in ubuntu?
Possible Duplicate:
install CMake occurs a error, how to deal with it?

i installed the CMake in ubuntu, how to check if it installed ?

A: Just type cmake --version in terminal, If cmake is not installed you will command not found error, If cmake is installed , you can see the cmake version

A: open your terminal and type as
dpkg --get-selections | grep cmake

If it was installed then you will get install message after them like below .

$ dpkg --get-selections | grep cmake
cmake                           install
cmake-data                      install

$

Hope that hlps .
credit goes Here :http://www.howtogeek.com


text:
Q: kickstart bootloader --driveorder configuration I use a kickstart file for a customized install CentOS.  On certain machines, if a memory stick is in the USB port, it fails because it tries to install CentOS on the memory stick. Kickstart current config:
# install the bootloader (GRUB)
bootloader --location=mbr --driveorder=sda

The failure occurs because the memory stick is /dev/sda and the hard drive is /dev/hda.  How do I change the --driveorder to ignore any USB memory stick on the system??
What is considered best practice for --driveorder for custom CentOS installations? Can always tell customers to remove USB sticks before installation...
Without the USB stick in the USB port, it installs fine on /dev/hda.

A: You can gently nudge the installation but telling the Kernel not to install drivers related to USB storage. This has the effect of stopping these devices from ever coming into the driveorder in the first place. From the GRUB menu:
linux nousbstorage ....

Kickstart Example
From a Kickstart .cfg file:
# Kickstart file automatically generated by anaconda.

install
cdrom
lang en_US.UTF-8
keyboard us
network --device eth0 --bootproto dhcp
rootpw --iscrypted $1$U.......
firewall --enabled --port=22:tcp
authconfig --enableshadow --enablemd5
selinux --enforcing
timezone --utc America/New_York
nousbstorage
bootloader --location=mbr --driveorder=sda --append="rhgb quiet"
...

References

*

*28.10. Starting a Kickstart Installation

A: Turns out that the nousbstorage would not work when placed in the ks.cfg file.  While installing CentOS 5.5, I would receive a 'Unknown command' error.  Turns out that nousbstorage needs to be added to the isolinux.cfg file:
default linux
prompt 1
timeout 0
display boot.msg
F1 boot.msg
F2 options.msg
F3 general.msg
F4 param.msg
F5 rescue.msg
label linux
  kernel vmlinuz
  append initrd=initrd.img text ks=cdrom:/ks.cfg nousbstorage
label text
  kernel vmlinuz
  append initrd=initrd.img text
label ks
  kernel vmlinuz
  append ks initrd=initrd.img
label local
  localboot 1
label memtest86
  kernel memtest
  append -

Installation is working perfect now for this problem I encountered.  Thanks to slm for pointing me in the right direction.


text:
Q: How to get external notifications into magento I am in interested in creating notification badges in magento for external applications such as email, crm, customer cat, etc.
i recently created links in magento's admin panel to redirect to my email, CRM system, etc. But i would also like to add notification badges to this.
Could you guys suggests ways to import notifications from external sources (email client/server, etc.)into magento?

A: You could use Magento's System->Notification system - the one that tells you about security patches, upgrades and the sort. The notifications appear right underneath the menu in the admin panel.
You'd need to do some custom development, but you should be able to easily hook into it with maybe one or two class rewrites. Also have a look at the following classes Mage_Adminhtml_NotificationController and Mage_AdminNotification_Model_Inbox.
edit:
There are a couple of blog-posts about what I mean:

*

*http://inchoo.net/magento/magento-frontend/utilizing-magento-notification-system/

*https://www.nicksays.co.uk/magento-custom-admin-notifications/


text:
Q: Javascript calling class function from initated class I can call class function from initiated class, but i cant display value of class property.
class A {
  constructor() {
    this.myvariable = "value";
    let b = new B(this.myCallback);
  }

  myCallback() {
    console.log(`myCallback() => ${this.myvariable}`);
  }
}

class B {
  constructor(cb) {
    cb();
  }
}

var a = new A();

I need to call class A method from class B. When I do as above, console prints this.myvariable as undefined.

A: That is happening as the myCallback is losing its context, you need to bind the myCallback to the context of the class A instance explicitly.
Without the context inside myCallback, this.myvariable would be undefined:

class A {
  constructor() {
    this.myvariable = "value";
    let b = new B(this.myCallback.bind(this));
  }

  myCallback() {
    console.log(`myCallback() => ${this.myvariable}`);
  }
}

class B {
  constructor(cb) {
    cb();
  }
}

var a = new A();

A: As the other answer has explained what is really happening clearly, here just provide an alternative to achieve that, since Arrow functions do not bind their own this, instead, they inherit the one from the parent scope, we can also do it like so:

class A {
  constructor() {
    this.myvariable = "value";
    let b = new B(this.myCallback);
  }

  myCallback = () => {
    console.log(`myCallback() => ${this.myvariable}`);
  }
}

class B {
  constructor(cb) {
    cb();
  }
}

var a = new A();

but using arrow function as class member is an experimental feature, so for better compatibility:

class A {
  constructor() {
    this.myvariable = "value";
    let b = new B(() => this.myCallback());
  }

  myCallback(){
    console.log(`myCallback() => ${this.myvariable}`);
  }
}

class B {
  constructor(cb) {
    cb();
  }
}

var a = new A();


text:
Q: write a file using FileSystem API I am trying to create a file using the File system API..i googled and i get a code
function onFs(fs) {

  fs.root.getFile('log.txt', {create: true, exclusive: true},
      function(fileEntry) {
           fileEntry.getMetaData(function(md) {
            }, onError);

      },
      onError
  );
}

window.requestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, onFs, onError);

can any one say what is the fs which is passed as function argument..
Please refer me a good example...

A: fs is a javascript object that allows you to make "system-like" level calls to a virtual filesystem.
So for instance you can use the fs object to create/get a reference to a file in the virtual filesystem with fs.root.getFile(...). The third argument (in your case, the following lines of code from your above snippet) in the .getFile(...) method happens to be a callback for successful obtaining of a file reference.
function(fileEntry) {
       fileEntry.getMetaData(function(md) {
        }, onError);
}

That file reference (in your case it is called fileEntry) can have various methods called such as .createWriter(...) for writing to files, .file(...) for reading files and .remove(...) for removing files. Your method calls .getMetaData(...) which contains a file size and modification date.
For more specifics as well as some good examples on the html5 file-system api you may find the following article helpful Exploring the File-System API
The location of the files differs on the browser, operating system and storage type (persistent vs. temporary) but the following link has served to be quiet useful as well Chrome persistent storage locations


text:
Q: Asynchronous programming in Java - Background processes I have got a REST-API in my Java Web Application. This has a method to take orders from a customer's Android app (client) and send (after a bunch of tasks, like price calculating etc.) a response back to the client.
    @POST
    @Path("order")
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public OrderResponse takeOrder(OrderRequest request
    ) throws IOException {
        OrderResponse response = new OrderResponse();

        String token = request.getTokenString();
        CustomerSession session = sessionPool.getSession(token);

        if (session != null) {

            OrderHeader order = new OrderHeader();
            order.setFkOrderHeaderCustomerID(session.getFkCustomerID());
            order.setOrderCreationDate(new Date());

Tasks as getting the session for authentication etc. have to be done synchronously, sure. 'Cause the response for the clients depends on it's success or failure.. So far so good.
At the end of this method the client gets an email about the state of his order request.
Email email = EmailGenerator.createOrderEmail(order);
            try {
                emailService.send(email);
            } catch (MessagingException ex) {
                Logger.getLogger(CustomerREST.class.getName()).log(Level.SEVERE, null, ex);
            }

            response.setStatus(OrderStatusEnum.SUCCESS);
        } else {
            response.setStatus(OrderStatusEnum.TOKEN_INVALID);
        }

        return response;
    }

This sometimes takes up to a few seconds for which the client has to wait for the response. That hurts.
Is there any way to send the response and do that email stuff in the background?

A:         Thread mailingThread = new Thread() {
            @Override
            public void run() {
                try {
                    Email email = EmailGenerator.createOrderEmail(order);
                    emailService.send(email);
                } catch (MessagingException | IOException ex) {
                    Logger.getLogger(CustomerREST.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };
        mailingThread.start();

Thaks Kyle! This seems to do what I attempted!


text:
Q: How can I find the last value in a multidimensional array in php? I am using a multidimensional array and I am trying to use php to find the last value of one of the arrays and based on that last number(value), add one more to it.
Here is my multidimensional array structure:
$_SESSION['cart']['add_complete'][1]['deck_id']

I am trying to create this structure, but instead of where it says 1 now, I want to find out what the last number in the add_complete array is and then add one more to it and put that in the place of the 1. How can I do that?

A: $new_num = count( $_SESSION['cart']['add_complete'] ) + 1;

A: If you're assigning a value you can also just remove the 1:
$_SESSION['cart']['add_complete'][]['deck_id'] = 'wtv';

... but this is frowned upon some, and I am under the impression it won't be supported in future versions of PHP, so stick with Justin Ethier's answer:
$_SESSION['cart']['add_complete'][count( $_SESSION['cart']['add_complete'] ) + 1]['deck_id']


text:
Q: how to change default options of vim editor permanently? I'm working on vim editor and want to edit some default options provided by vim editor.
i.e N+G(5G) to move to nth line but I want N+Enter to move to nth line
likewise:

^ want change to s
$ want change to e

etc

A: With the right terminology, you should be able to look up these simple tasks in the excellent and comprehensive :help.
Options influence the behavior of Vim. For example, :set wrap enables (soft) line breaking of long lines. You'll find it under :help 'wrap'; options are wrapped in single quotes in the help; :help options has them all.
That's not what you're after, though. You want to change the keys that trigger certain, built-in behavior. That's called mapping, documented under :help mapping.
To make <Enter> do the same thing as G (in normal mode), you'd use
:nnoremap <Enter> G

:help key-notation helps with how you specify the keys. You should use :noremap; it makes the mapping immune to remapping and recursion. The [N] count is separate from the command itself; you can ignore it here.
Likewise, you can do:
:nnoremap s ^
:nnoremap e $

However, note that this will override very useful built-in commands (s replaces the current [count] characters and starts editing, e moves to the end of word; you can look these up with :help s and :help e). Vim has attracted so many followers because of its very efficient mode-based command model; if you instead try to reconfigure Vim heavily, you're commiting a typical beginner's mistake!
Persistence
All the above commands only persist for the current Vim session, so you can safely try them out. To make them permanent, put them into a ~/.vimrc configuration file (:help vimrc), and restart Vim. The : prefix is optional in that file; scripts use Ex mode, not normal mode.


text:
Q: Using fscanf to scan a value or use default if no value exists I have a function to read a text file with the following format
 string int int
 string int int
 string int int

I want to write a function that will assign the values from the text file into variables, but there will also be some cases where the format of the text file will be
string int
string int
string int

In that case, I'd like to set the value of the last int variable to 1. My code I have so far works with the first example but I'm a bit stuck on getting the second scenario to work:
void readFile(LinkedList *inList, char* file)
    {
    char tempName[30];
    int tempLoc, tempNum;

    FILE* f;
    f = fopen(file, "r");
    if(f==NULL)
        {
        printf("Error: could not open file");
        }
    else
        {
        while (fscanf(f, "%s %d %d\n", tempName, &tempLoc, &tempNum) != EOF)
            {
            insertFirst (inList, tempName, tempLoc, tempNum);
            }
        }
    }

A: In the second case, fscanf will return 2 instead of 3.  So you can rewrite the code like this:
while (1) {
    int ret = fscanf(f, "%s %d %d\n", tempName, &tempLoc, &tempNum);
    if (ret == EOF) {
        break;
    }
    if (ret == 2) {
        tempNum = 1;
    } else if (ret != 3) {
        // line appear invalid, deal with the error
    }
    insertFirst (inList, tempName, tempLoc, tempNum);

}
A more hacky way would be to set tempNum to 1 before calling fscanf and just check for EOF as you did above.  But I think the code above is clearer.
Edit: to avoid overflows, this would be better.  The code would perform better but this is harder to write.  Just like above, I did not write any code for the error conditions but you definitely want to handle them
char lineBuf[255];
while (fgets(lineBuf, sizeof(lineBuf), f) != NULL) {
    int spaceIdx, ret;
    const int len = strlen(lineBuf);
    if (len == (sizeof(lineBuf) - 1) {
         // line is too long - either your buf is too small and you should tell the user
         // that its input is bad
         // I recommend to treat this as an error
    }
    lineBuf[len - 1] = '\0'; // remove \n
    --len;  // update len, we've removed one character
    if (isspace(*lineBuf)) {
        // error, line should not start with a space
    }
    spaceIdx = strcspn(lineBuf, "\t ");
    if (spaceIdx == len) {
        // error, no space in this line
    }

    // Ok, we've found the space.  Deal with the rest.
    // Note that for this purpose, sscanf is a bit heavy handed (but makes the code
    // simpler). You could do it with strtol.
    // Also, the first space in the format string is important, so sscanf skips
    // all the space at the beginning of the string.  If your format requires only
    // one space between fields, you can do sscanf(lineBuf + spaceIdx + 1, "%d %d"...

    ret = sscanf(lineBuf + spaceIdx, " %d %d", &tempLoc, &tempNum);
    if (0 == ret) {
        // error, no ints
    }
    else if (1 == ret) {
        tempNum = 1;
    }

    // at that point, you could copy the first part of lineBuf to tempName, but then
    // you have to deal with a potential overflow (and spend time on an useless copy),
    // so use lineBuf instead

    lineBuf[spaceIdx] = '\0';

    insertFirst (inList, lineBuf, tempLoc, tempNum);
}


text:
Q: Office 365 authentication via REST without registering an application Is there any way of authenticating a user via the Office 365 REST API, without registering an application first?
For example, the documentation of Microsoft Graph has numerous authentication scenarios, including how an application can

*

*Get access on behalf of a user
but there is no such scenario for a user calling the REST API with some credentials (e.g., username and password) and gets authentication tokens as a response, so that they can subsequently use the rich functionality provided.
The Azure Active Directory Authentication Libraries (ADAL) provide user-level authentication functionality, but they do not expose the REST API.

A: There is no way to call the Microsoft Graph without registering an app first. All calls to the graph are authenticated using a OAuth2 flow (of which there are several) and all require an app to be registered.

A: For your question, I think we can use background daemons or services to get authorize the user.We can use the following steps:

*

*Get access without a user.
We can refer to this document to learning more information.

2.Authorize the user
When we get the user's profile by using the access token in the step one, then we can authorize him by checking him is exist in our system.


text:
Q: How do I find Adjustments & Other Charges? I am using the UPS API for shipping and tracking orders.
Sometimes, UPS adds an additional amount to my invoice titled 'Adjustments & Other Charges'
Is there a way to access this data (after shipping) via the API? so my client doesnt have to type them in manually when he physically recieves the invoice?
Thanks!

A: If anyone stumbles across this, then here's the anwer from UPS:

Thank you for your inquiry. 'Adjustments & Other Charges' are provided
  by UPS Billing. There is no way to access them via the API. More
  information about billing adjustments can be found at the link
  provided below:
https://www.ups.com/content/us/en/resources/sri/bil_faq8.html?srch_pos=5&srch_phr=adjustments
Please contact us if you need any additional assistance.


text:
Q: Bad margins while printing I'm using geometry package like this:
\usepackage[landscape]{geometry}
\newgeometry{twocolumn, left=0.25cm, right=0.25cm, top=0.8cm, bottom=0.4cm}

and fancyhdr package like this:
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\fancyhead[L]{\bf{Some text}}
\fancyhead[C]{\leftmark}
\fancyhead[R]{\thepage}
\fancyheadoffset[L]{0.42cm}
\fancyheadoffset[R]{-0.26cm}

And everything with margins is ok. But when I'm printing pdf on paper all margins is changing. How can I fix page margins for printing?
All code looks like this:
\documentclass[8pt]{extarticle}

\usepackage[cp1251]{inputenc}

\usepackage[russian,english]{babel}

\usepackage[landscape]{geometry}

\usepackage{fancyhdr}

\pagestyle{fancy}

\fancyhf{}

\fancyhead[L]{\bf{Some text}}

\fancyhead[C]{\leftmark}

\fancyhead[R]{\thepage}

\fancyheadoffset[L]{0.42cm}

\fancyheadoffset[R]{-0.26cm}

\setlength{\headsep}{0.2cm}

\usepackage{listings}

\usepackage{color}

\definecolor{mygreen}{rgb}{0,0.6,0}

\definecolor{mygray}{rgb}{0.5,0.5,0.5}

\definecolor{myviolet}{rgb}{0.5,0,0.36}

\lstset{
backgroundcolor=\color{white},
language=C++,
keywordstyle=\color{myviolet},
commentstyle=\color{mygreen},
frame=single,
framerule=0.1pt,
rulecolor=\color{black},
breakatwhitespace=true,
breaklines=true,
numbers=left,
stepnumber=1,
numbersep=5pt,
numberstyle=\tiny\color{mygray},
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2,
framexleftmargin=10pt,
framexrightmargin=-10pt,

}

\usepackage{amsmath}

\begin{document}

\selectlanguage{russian}

\newgeometry{twocolumn, left=0.7cm, right=0cm, top=0.8cm, bottom=0.4cm}

\begin{lstlisting}
/* bfdlink.h -- header file for BFD link routines
   Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
   2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
   Free Software Foundation, Inc.
   Written by Steve Chamberlain and Ian Lance Taylor, Cygnus Support.

   This file is part of BFD, the Binary File Descriptor library.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
   MA 02110-1301, USA.  */

#ifndef BFDLINK_H
#define BFDLINK_H

/* Which symbols to strip during a link.  */
enum bfd_link_strip
{
  strip_none,       /* Don't strip any symbols.  */
  strip_debugger,   /* Strip debugging symbols.  */
  strip_some,       /* keep_hash is the list of symbols to keep.  */
  strip_all     /* Strip all symbols.  */
};

/* Which local symbols to discard during a link.  This is irrelevant
   if strip_all is used.  */
enum bfd_link_discard
{
  discard_sec_merge,    /* Discard local temporary symbols in SEC_MERGE
               sections.  */
  discard_none,     /* Don't discard any locals.  */
  discard_l,        /* Discard local temporary symbols.  */
  discard_all       /* Discard all locals.  */
};

/* Describes the type of hash table entry structure being used.
   Different hash table structure have different fields and so
   support different linking features.  */
enum bfd_link_hash_table_type
  {
    bfd_link_generic_hash_table,
    bfd_link_elf_hash_table
  };

/* These are the possible types of an entry in the BFD link hash
   table.  */

enum bfd_link_hash_type
{
  bfd_link_hash_new,        /* Symbol is new.  */
  bfd_link_hash_undefined,  /* Symbol seen before, but undefined.  */
  bfd_link_hash_undefweak,  /* Symbol is weak and undefined.  */
  bfd_link_hash_defined,    /* Symbol is defined.  */
  bfd_link_hash_defweak,    /* Symbol is weak and defined.  */
  bfd_link_hash_common,     /* Symbol is common.  */
  bfd_link_hash_indirect,   /* Symbol is an indirect link.  */
  bfd_link_hash_warning     /* Like indirect, but warn if referenced.  */
};

enum bfd_link_common_skip_ar_symbols
{
  bfd_link_common_skip_none,
  bfd_link_common_skip_text,
  bfd_link_common_skip_data,
  bfd_link_common_skip_all
};

struct bfd_link_hash_common_entry
  {
    unsigned int alignment_power;   /* Alignment.  */
    asection *section;      /* Symbol section.  */
  };

/* The linking routines use a hash table which uses this structure for
   its elements.  */

struct bfd_link_hash_entry
{
  /* Base hash table entry structure.  */
  struct bfd_hash_entry root;

  /* Type of this entry.  */
  ENUM_BITFIELD (bfd_link_hash_type) type : 8;

  unsigned int non_ir_ref : 1;

  /* A union of information depending upon the type.  */
  union
    {
      /* Nothing is kept for bfd_hash_new.  */
      /* bfd_link_hash_undefined, bfd_link_hash_undefweak.  */
      struct
    {
      /* Undefined and common symbols are kept in a linked list through
         this field.  This field is present in all of the union element
         so that we don't need to remove entries from the list when we
         change their type.  Removing entries would either require the
         list to be doubly linked, which would waste more memory, or
         require a traversal.  When an undefined or common symbol is
         created, it should be added to this list, the head of which is in
         the link hash table itself.  As symbols are defined, they need
         not be removed from the list; anything which reads the list must
         doublecheck the symbol type.

         Weak symbols are not kept on this list.

         Defined and defweak symbols use this field as a reference marker.
         If the field is not NULL, or this structure is the tail of the

\end{lstlisting}

\end{document}

Command line for compiling:
latex a.tex
dvipdfm a.dvi

A: Possible reasons:
Acrobat Reader/Shrink to printable area
Options for printing with Acrobat Reader are (naming can vary):

*

*None

*Fit to page area

*Shrink to printable area

The default is (3) that means, the page is scaled down to fit the printable
area if needed. Option (2) can also scale the page up. You need "None" to
avoid scaling.
Wrong paper size
Some TeX distributions can be configured for default paper sizes.
But that does not change the default for the standard classes.
Without paper size option, the standard classes uses letterpaper.
Then the margins are not correct on an A4 paper, if they are set
for letter size.
Remark: LaTeX and the standard classes do not tell the driver the
correct paper size. The latter is done by packages such as geometry,
hyperref, some pdftex.def (driver for graphics/color), …
Without such a package and a paper size option, the result can be a
PDF document with paper size A4 (TeX distribution/driver default),
but at LaTeX level the page layout inclusive margins are configured for
letter paper size.
Update: The used class is extarticle, its default is letter paper, thus option a4paper is needed:
\documentclass[a4paper,8pt]{extarticle}


text:
Q: I am having trouble populating an array using InputBox I am having trouble populating an array using InputBox.
private void btnOk_Click(object sender, EventArgs e)
{
    int array;
    int num;

    string value = Interaction.InputBox("Enter Array size","Enter Array size");
    if (int.TryParse(value, out array))
    {
        int[] Size = new int[array];

        txtOutput.Text = "Numbers: " + "\r\n";

        foreach (int i in Size)
        {
            string prompt = Interaction.InputBox("Enter values" + (i+1), "Enter values");
            if(int.TryParse(prompt, out num))

            txtOutput.Text += i + "\t";
        }
    }
}

A: string value = Interaction.InputBox("Enter Array size", "Enter Array size");
int array = 0;
if (int.TryParse(value, out array))
{
    int[] size = new int[array];
    txtOutput.Text = "Numbers: " + "\r\n";

    for (int i = 0; i < size.Length; i++)
    {
        string prompt = Interaction.InputBox("Enter values" + (i + 1), "Enter values");
        int num = 0;
        if (int.TryParse(prompt, out num))
        {
            size[i] = num;
            txtOutput.Text += size[i] + "\t";
        }
    }
}


text:
Q: How to cascade unknown number of conditions in Spark without looping through each condition I want to filter a data frame based on processed user queries, however the number of conditions are not constant and will change user by user. For example lets assume, Two user will have the following different conditions
1- df.filter( ( col('A') == 'book' ) & (col('B') == '1') & (col('C') == '0') )
2- df.filter( ( col('A') == 'film') ) & (col('B') == '0'))

One solution is to cascade the conditions sequentially
for k,v in argList:
   df = df.filter(col(k) == v)

where argList is a list of conditions per user, for example
[('A','book') ,('B','1'), ('C','0')]  or [('A','film') ,('B','0')] , .....
Is there a better way to cascade multiple conditions without looping through every condition?

A: There is nothing wrong with looping through the conditions as the Spark optimzer will combine all filters into a single one:
df = spark.createDataFrame([(1,2),(1,4),(5,6)], ['A', 'B'])
df = df.filter(F.col('A') == 1)
df = df.filter(F.col('B') == 4)
df.explain()

prints
== Physical Plan ==
*(1) Filter (((isnotnull(A#0L) AND isnotnull(B#1L)) AND (A#0L = 1)) AND (B#1L = 4))
+- *(1) Scan ExistingRDD[A#0L,B#1L]

and only one filter operation is executed.


text:
Q: Does truncating a counter column family have the same caveats as removing a single counter When truncating a Counter Column Family in Cassandra do the counters suffer from the same limitations as just removing a single column or row?
Will I have to drop the column family and recreate it to completely clear it out or should I be fine truncating it?

A: The issue is the same: if you are doing simultaneous deletes or truncates and increments, the result is undefined.
The issue is that delete is effectively setting the counter value to zero.  Truncate is setting all counter values to zero.  The 'set' operation does not commute with the 'inc' operation, so a mixture of simultaneous operations gives unpredictable results.
If you aren't doing increments or can pause them, then it is perfectly safe doing a truncate.  There is no need to drop the column family.  If you cannot stop the increments then it depends on your client.  Dropping the column family will cause the client to fail until it is recreated - if the client can survive those errors and then continue that might work.  But the best would be to temporarily pause the increments.


text:
Q: Stack Overflow error when compiling a program I am trying to create and relate four classes such as shape, circle, rectangle and square using inheritance as shown below.
However, when I compile the program, the error message is displayed as shown:
Exception in thread "main" java.lang.StackOverflowError
    at Square.setSide(Square.java:20)

I am not sure why is this so. Attached below are my codings
Square.java
public class Square extends Rectangle {
    public Square() {
        super();
    }

public Square(double side) {
    super(side, side);
}

public Square(double side, String color, boolean filled) {
    super(side, side, color, filled);
}

public double getSide() {
    return getSide();
}

public void setSide(double side) {
    this.setSide(side);
}

public void setWidth(double side) {
    this.setWidth(getWidth());
}

public void setLength(double side) {
    this.setLength(getLength());
}

public String toString() {
    return "Square[Rectangle" + "[" + "Shape" + "[" + "color=" + getColor() + "," + "filled=" + isFilled() + "]," + "width=" + getWidth() + "," + "length=" + getLength() + "]";
}
}

Rectangle.java
public class Rectangle extends Shape {

private double length;
private double width;

public Rectangle() {
    this.length = 1.0;
    this.width = 1.0;
}

public Rectangle(double length, double width)
{
    this.length = length;
    this.width = width;
}

public Rectangle(double width, double length, String color, boolean filled) {
    super(color, filled);
    this.width = width;
    this.length = length;
}

public double getWidth()
{
    return this.width;
}

public void setWidth(double width)
{
    this.width = width;
}

public double getLength()
{
    return this.length;
}

public void setLength(double length)
{
    this.length = length;
}

public double getArea() {
    return length * width;
}

public double getPerimeter() {
    return 2*length + 2*width;
}

public String toString() {
    return "Rectangle[Shape" + "[color=" + getColor() + "," + "filled=" + isFilled() + "]," + "width=" + width + "," + "length=" + length + "]";
}

}

Circle.java
public class Circle extends Shape {

    // TODO Auto-generated method stub
    private double radius;

    public Circle() {
        this.radius = 1.0;

    }

    public Circle(double radius) {
        this.radius = radius;
    }

    public Circle(double radius, String color, boolean filled) {
        super(color,filled);
        this.radius = radius;
    }

    public double getRadius() {
        return this.radius;
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }

    public double getArea() {
        return radius * radius * Math.PI;
    }

    public double getPerimeter() {
        return 2 * Math.PI * radius;
    }

    public String toString() {
        return "Circle[Shape" + "[color=" + getColor() + "," + "filled=" + isFilled() + "]," + "radius=" + radius + "]";
    }

}

Shape.java
public class Shape {
private String color;
private boolean filled;

public Shape() {
    this.color = "red";
    this.filled = true;
}

public Shape(String color, boolean filled) {
    this.color = color;
    this.filled = filled;
}

public String getColor() {
    return this.color;
}

public void setColor(String color) {
    this.color = color;
}

public boolean isFilled() {
    return this.filled;
}

public void setFilled(boolean filled) {
    this.filled = filled;
}

public String toString() {
    return "Shape[color=" + color + "," + "filled=" + filled + "]";
}

}

It would be better if someone can help me on that. Many thanks!
P.S The output was supposed to be like this
//Need copy the below codings for output

public class TestMain {
   public static void main(String[] args) {
      /* Test Shape class */
      // Test constructors and toString()
      Shape s1 = new Shape();
      System.out.println(s1);  // toString()
      Shape s2 = new Shape("green", false);
      System.out.println(s2);  // toString()
      // Test Setters and Getters
      s1.setColor("blue");
      s1.setFilled(true);
      System.out.println(s1);  // toString()
      System.out.println("Color is: " + s1.getColor());
      System.out.println("Filled is: " + s1.isFilled());

  /* Test Circle class */
  // Test constructors and toString()
  Circle c1 = new Circle();
  System.out.println(c1);
  Circle c2 = new Circle(1.1);
  System.out.println(c2);
  Circle c3 = new Circle(2.2, "green", false);
  System.out.println(c3);
  // Test Setters and Getters
  c1.setColor("orange");  // superclass
  c1.setFilled(true);     // superclass
  c1.setRadius(8.8);
  System.out.println(c1);
  System.out.println("Color is: " + c1.getColor());  // superclass
  System.out.println("Filled is: " + c1.isFilled()); // superclass
  System.out.println("Radius is: " + c1.getRadius());
  System.out.printf("Area is: %.2f%n", c1.getArea());
  System.out.printf("Perimeter is: %.2f%n", c1.getPerimeter());

  /* Test Rectangle class */
  // Test constructors and toString()
  Rectangle r1 = new Rectangle();
  System.out.println(r1);
  Rectangle r2 = new Rectangle(1.1, 2.2);
  System.out.println(r2);
  Rectangle r3 = new Rectangle(3.3, 4.4, "green", false);
  System.out.println(r3);
  // Test setters and getters
  r1.setWidth(5.5);
  r1.setLength(6.6);
  r1.setColor("orange");  // superclass
  r1.setFilled(true);     // superclass
  System.out.println(r1);
  System.out.println("Color is: " + r1.getColor());  // superclass
  System.out.println("Filled is: " + r1.isFilled()); // superclass
  System.out.println("Length is: " + r1.getLength());
  System.out.println("Width is: " + r1.getWidth());
  System.out.printf("Area is: %.2f%n", r1.getArea());
  System.out.printf("Perimeter is: %.2f%n", r1.getPerimeter());

  /* Test Square class */
  // Test constructor and toString()
  Square sq1 = new Square();
  System.out.println(sq1);
  Square sq2 = new Square(1.1);
  System.out.println(sq2);
  Square sq3 = new Square(2.2, "green", false);
  System.out.println(sq3);
  // Test Setters and Getters
  sq1.setSide(3.3);
  sq1.setColor("orange");  // superclass
  sq1.setFilled(false);    // superclass
  System.out.println(sq1);
  System.out.println("Color is: " + sq1.getColor());   // superclass
  System.out.println("Filled is: " + sq1.isFilled());  // superclass
  System.out.println("Side is: " + sq1.getSide());

  sq1.setWidth(4.4);  // overridden
  System.out.println(sq1);
  System.out.println("Width is: " + sq1.getWidth());   // superclass
  sq1.setLength(5.5);  // overridden
  System.out.println(sq1);
  System.out.println("Length is: " + sq1.getLength()); // superclass

  System.out.printf("Area is: %.2f%n", sq1.getArea());
  System.out.printf("Perimeter is: %.2f%n", sq1.getPerimeter());

  }
}

Output
Shape[color=red,filled=true]
Shape[color=green,filled=false]
Shape[color=blue,filled=true]
Color·is:·blue
Filled·is:·true
Circle[Shape[color=red,filled=true],radius=1.0]
Circle[Shape[color=red,filled=true],radius=1.1]
Circle[Shape[color=green,filled=false],radius=2.2]
Circle[Shape[color=orange,filled=true],radius=8.8]
Color·is:·orange
Filled·is:·true
Radius·is:·8.8
Area·is:·243.28
Perimeter·is:·55.29
Rectangle[Shape[color=red,filled=true],width=1.0,length=1.0]
Rectangle[Shape[color=red,filled=true],width=1.1,length=2.2]
Rectangle[Shape[color=green,filled=false],width=3.3,length=4.4]
Rectangle[Shape[color=orange,filled=true],width=5.5,length=6.6]
Color·is:·orange
Filled·is:·true
Length·is:·6.6
Width·is:·5.5
Area·is:·36.30
Perimeter·is:·24.20
Square[Rectangle[Shape[color=red,filled=true],width=1.0,length=1.0]]
Square[Rectangle[Shape[color=red,filled=true],width=1.1,length=1.1]]
Square[Rectangle[Shape[color=green,filled=false],width=2.2,length=2.2]]
Square[Rectangle[Shape[color=orange,filled=false],width=3.3,length=3.3]]
Color·is:·orange
Filled·is:·false
Side·is:·3.3
Square[Rectangle[Shape[color=orange,filled=false],width=4.4,length=4.4]]
Width·is:·4.4
Square[Rectangle[Shape[color=orange,filled=false],width=5.5,length=5.5]]
Length·is:·5.5
Area·is:·30.25
Perimeter·is:·22.00

A: Your StackOverFlow error is coming from the class Square
public class Square extends Rectangle {

private double side;

public Square() {
    super();
}

public Square(double side) {
    super(side, side);
}

public Square(double side, String color, boolean filled) {
    super(side, side, color, filled);
}

public double getSide() {
    return this.side;
}

public void setSide(double side) {
    this.side = side;
}

public void setWidth(double side) {
    super.setWidth(getWidth());
}

public void setLength(double side) {
    super.setLength(getLength());
}

public String toString() {
    return "Square[Rectangle" + "[" + "Shape" + "[" + "color=" + getColor() + "," + "filled=" + isFilled() + "]," + "width=" + getWidth() + "," + "length=" + getLength() + "]";
}
}

The methods setSide, setWidth and setLength are all calling themselves causing an infinite loop exceeding the amount of call stack memory allocated by the Java Virtual Machine.
Rather than using this, referring to the Square class use super.setSide to call the method in your parent class rectangle.

A: Your setter methods are calling themselves...which is not allowed. It appears you mean to reference the parent's setter methods using super.setFoo()


text:
Q: Unable to install requests in VS Code for working with Python I am unable to install the requests using sudo command in my VS Code terminal.
sudo pip3 install requests

sudo : The term 'sudo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:1
+ sudo pip3 install requests
+ ~~~~
    + CategoryInfo          : ObjectNotFound: (sudo:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


text:
Q: How fast can I pipe data through a TI Delfino in 1.5 KB chunks? Say I program a Delfino with this C snippet:
int main () {
    while (true) {
        byte packet[1536];
        readPacketFromUSB(packet);
        writePacketToSerial(packet);
    }
}

How quickly can I run the loop, copying 1536 bytes from USB to serial?
From the TMS320F28377S microcontroller datasheet:

Multichannel Buffered Serial Port (McBSP):
McBSP clock rate, \$CLKG = \frac{CLKSRG}{1+CLKGDV}\$
where CLKSRG source could be LSPCLK, CLKX, or CLKR.

It seems that the fastest available configuration is CLKGDV=1 and LSPCLK=200 MHz.
So \$CLKG = 100 MHz\$ or \$100 Mbps\$ baud rate.
Considering only read/write times, my loop should run at \$\frac{100 Mbps}{2*(1536 bytes)} ≈ 4.1 KHz\$.
Does 4.1 KHz sound right? Is there a substantial source of overhead that I'm missing?


text:
Q: how to add items name in alert dialog from strings.xml in android in my app when i click a button i am opening an Alert Dialog builder. My code is as follows
AlertDialog.Builder builder = new AlertDialog.Builder(BannerImage.this);
final CharSequence[] items = {"Skip", "video", "Audio", "Games"};
builder.setTitle(" Funn ");

here instead of typing the items name here i want to add those name from R.strings.xml file
but it shows some errors, as my user changes the locale i want to show different language for that i need to do like this. How to add the values from strings file...

A: final CharSequence[] items = {getString(R.string.skip), getString(R.string.video), getString(R.string.audio), getString(R.string.games)};

and then create your string.xml file
<resources>
<string name="skip">skip</string>
<string name="video">Video</string>
<string name="audio">Audio</string>
<string name="games">Games</string>
</resources>

<resources>
<string name="skip">Siguiente</string>
<string name="video">Video</string>
<string name="audio">Audio</string>
<string name="games">Juegos</string>
</resources>

A: You neeed to create seperate resource files for each language. E.G

*

*res/values/strings.xml - For all English strings that the application uses.

*res/values-fr/strings.xml - For all French strings that the application uses.

*res/values-ja/strings.xml - For all Japanese strings that the application uses.

Please read the Localization article for more info.


text:
Q: ios digital zoom for video recording. how to implement efficiently? I've searched to find that sdk do not support digital zoom in or out, you have to do it indirectly. The way I found on stackoverflow is transform the AVCaputureVideoPreviewLayer while recording, and do the corresponding transform postprocess to the output video(my present idea is use AVMutableVideoCompositionLayerInstruction's transform ramp function.).
The problem is how can you record all the continuous course of user's zoom activity, which I think can be a sirious of very complex zoom in and zoom out behaviors
I mean, for example, I design a slider for user to control the zoom, user may hold the slider zoom in 4x slowly(say last 3 seconds) and, without release the slider, quickly zoom out to 2X(say last 0.5 seconds), I have to record all this changes according the timeline.
I really feel this record complex, in addition you also have to guarantee it doesn't cost too much resources to keep smooth performance of video recording process!
Or any other way of implementation of digital zoom?
Grateful to any helper!

A: You could transform AVCaputureVideoPreviewLayer while recording and use the zoomvalue to manipulate the frames in the AVCaptureVideoDataOutput delegate. The delegate method captureOutput:didOutputSampleBuffer:fromConnection: can be used to process frames of video. See AVFoundation documentation AVFoundation documentation, Media Capture > Processing Frames of Video.


text:
Q: Mathematica DSolve for two functions I have the following two differential equations
y'[t] == k1*y[t] - k3*y2[t]
y2'[t] == k2*y2[t] - k4*y[t]

I can solve the equations using Mathematicas DSolve Function:
DSolve[{y'[t] == k1*y[t] - k3*y2[t], y2'[t] == k2*y2[t] - k4*y[t],
   y[0] == y10, y2[0] == y20}, {y[t], y2[t]}, t]

Mathematica gives me the analytical result of this system of differential equations, in the following form:
y[t] = f{t}

and
y2[t] f{t}

But what I want is a function for y[t] that depends not only on t, but also on y2[t]
y[t] = f{t, y2[t]}

The reason is that I have experimental data (the concentrations y and y2 over t) and I want to fit a curve for y (and later y2). I am thankful for any input! :-)

A: I would have just left this as a comment, but I can't (too low reputation), but Trying a simplification of your code:
DSolve[{D[y1[t, y2[t]], t] == 3*y1[t, y2[t]],   D[y2[t], t] == 2*y1[t, y2[t]], y1[0, 0]
== 0,
y2[0] == 2}, {y1[t, y2[t]], y2[t]}, t]

Produces the error
DSolve::ivar2: The independent variable t should not appear in two different arguments of the dependent variable y1[t,y2[t]].

So I'm not entirely sure if you can get Mathematica to do what you are asking for, if I understand what you wanted correctly. I suggest asking at The Mathematica Stack Exchange, Since they are most likely much more experienced with these types of issues.


text: Q: If $F$ is a field then every ideal in $F[x]$ is a principal ideal. I have got no clue of how to start with the problem .Now I know that an ideal is a kernel of a ring homorphism but why would it be a principal ideal in $F[x]$.What is the intuition behind this ?(I would like to know why is it happening instead of a formal proof)


text:
Q: Array of objects dynamic memory allocation I'm trying to allocate dynamic memory to an array of objects, but I keep getting the following error:
"error: C2143: syntax error : missing ';' before '*'"
"error: C2501: 'Figura' : missing storage-class or type specifiers"
Any help is welcomed. I'm using Visual Basic C++ 2006, but will switch to Turbo C++ 3.0 with Dosbox to get graphics.h working :( .
Here's the code:
#include<iostream.h>

class Grup {
    private:
        int nr_elemente;
        Figura *figuri;
    public:
        Grup() {
            figuri = new Figura[nr_elemente];
        }
};

class Figura {

public:
    Figura();
    ~Figura();
    Figura(const Figura&);

    friend Figura operator+(const Figura& fig1, const Figura& fig2) {};
    friend Figura operator+(const Grup& gr1, const Grup& gr2) {}

    friend Figura operator*(const Figura& fig) {}
    friend Figura operator*(const Figura& fig) {}

};

Figura operator+(const Figura& fig, const Grup& gr) {
    return fig;
}

class Punct : Figura
{
public:
    int x, y;

    Punct(int x, int y) {
        Punct::x = x;
        Punct::y = y;
    }
};

class Segment : Figura
{
public:
    int x, y, poz;
};

class Dreptunghi : Figura
{
public:
    int x, y, poz;
};

void main(void) {

}

A: In this line:
figuri = new Figura[nr_elemente];

The compiler does not know that a class Figura exists. Therefore, it generates an error, since "Figura" is an unknown token at that point. You should use a forward declaration:
class Figura; // forward-declare class Figura

class Grup {
/* ... */
};

class Figura {
/* ... */
};

The problem is that the compiler does not know the size of a class Figura, therefore it can't allocate an array of objects of this type. Therefore you will probably need to use pointers or modify your class design.

A: Your problem is that you're trying to do all in one file. You'll not have such kind of problems if you move the declaration and definition of classes to separate .hpp and .cpp files.
Move
// file grup.hpp

class Figura; // forward declaration

class Grup {
private:
    int nr_elemente;
    Figura *figuri;
public:
    Grup();
};

to grup.hpp file. Then implement the constructor of Grup in group.cpp file:
// file grup.cpp
#include "grup.hpp"
#include "figura.hpp"

Grup::Grup()
{
    figuri = new Figura[nr_elemente];
}

Also move the definition and declaration of Figura class to corresponding figura.hpp and figura.cpp files. Better to use the same approach with all classes you have.

A: You need to forward declare, already mentioned, but that is not enough, you need to know the size of the class in order to use it as an implementation.  Therefore...
class Figura;
class Grup{
  Figura * figuri;
  //.. other stuff, but ONLY declarations no implementations.
};

class Figura
{
  //Same as you already have...
};

After the classes have been declared, since they are in the same file you need to implement AFTER the other classes have been implemented (or declared).
//Still same file but below the Figura class definition..
Grup::Grup() {
   //Now you can use Figura...
   figuri = new Figura[nr_elemente];
}

@be
The problem you are seeing with your comment below has to do with the assignment operator for your fig class.
The operator looks like this...
     Fig& operator=(const Fig& );
But with your example you are assigning a pointer
     void func(const Fig * fig)
     {
      //...
      figcontainer[index] = fig; // if you did *fig; you would be ok
      //...
     }


text:
Q: Why is $Z_p[x]$ left and right distributive I did not get to the section on field theory in the book I am studying from, so I'm not looking for someone to generalize straight over my question with any results on fields that may make this an obvious exercise.
Let $Z_p[x]$ denote all polynomials of indeterminate $x$ with coefficients element of $Z_p$, i.e. the integers modulo $p$. Let the operations of addition ($+$) and multiplication (juxtaposition of elements) by doing ordinary polynomial addition and multiplication but reducing the coefficients modulo $p$.
I am trying to show that this multiplication in $Z_p[x]$ is left and right distributive over addition. I am totally aware I should be using the following:

*

*$(a+b)\bmod n = (a\bmod n)+(b\bmod n) \bmod n$

*$ab\bmod n = (a\bmod n)(b\bmod n)\bmod n$

*The above results and the commutativity of $Z_n$ imply that integers modulo $n$ are left and right distributive.

However I'm not sure at all how the above results imply left and right distributivity of $Z_p[x].$ I tried doing induction on the degrees of the polynomials involved in the expression $f(g+h)$ but I'm not sure if there's easier methods.
Any help would be appreciated.


text:
Q: A java application with J2V8 crashes when an exception happened in a some deferred section (e.g. setTimeout or process.nextTick) I use amazing J2V8 java library which allows execute any Javascript code in your Java application furthermore it can integrates a nodeJS engine.
But i have encountered with a next issue. This code interrupts a Java application immediately after nodejs invokes a callback function of setTimeout which throw an exception although there is a try..carch block. The exception doesn't even enter into the try..catch block.
// It is an example, in real case it can be a some erorr in a code.
nodeJS = NodeJS.createNodeJS();
try {
    nodeJS.getRuntime().executeVoidScript("setTimeout(function(){throw 'Error'}, 1000);");
} catch (Exception e) {
    e.printStackTrace();
}

The application is interrupted with message:
undefined:1
setTimeout(function(){throw 'Error'}, 10000);
                  ^
Error
Process finished with exit code 1

Another example shows that exceptions are not a cause of interruption of an application  always and it is a 'normal' case.
nodeJS = NodeJS.createNodeJS();
try {
    nodeJS.getRuntime().executeVoidScript("throw 'Error'");
} catch (Exception e) {
    e.printStackTrace();
}

In this case we see the only a error message in console but the application still works.
Exception in thread "Thread-2" undefined:1: Error
throw 'Error'
^
com.eclipsesource.v8.V8ScriptExecutionException
    at com.eclipsesource.v8.V8._executeScript(Native Method)
    at com.eclipsesource.v8.V8.executeScript(V8.java:940)
    at com.eclipsesource.v8.V8.executeScript(V8.java:595)
    at com.eclipsesource.v8.V8.executeObjectScript(V8.java:625)
    at com.eclipsesource.v8.V8.executeObjectScript(V8.java:608)
    at org.efc.origamiapp.v8.V8Environment.run(V8Environment.java:383)

The examples above are in the try..catch blocks, and you can see trace stack below it. So the interruption is fired in Native Method (the secod example), but in the first case the JS exception just kills the Java  application without any explanations in a console or in a trace log.

A: It looks like the error you are throwing in the javascript code is being propagated into the java environment. This is what one would expect to see given the js code you are trying to execute (throw 'Error'). What did you expect to happen? Simply catch any exceptions in java and handle appropriately - maybe by logging?
try {
    nodeJS.getRuntime().executeVoidScript("throw 'Error'");
}
catch(Exception e) {
    System.out.println(e.toString());
}

A: This is the best and correct solution.
process.on('unhandledRejection', (err) => {
    console.error('Unhandled promise rejection',err);
});
process.on('uncaughtException', (err) => {
    console.error('Uncaught exception',err);
});

For more information see the nodeJS documentation: Event: 'uncaughtException'

A: For now my workaround is this script.
let nativeSetTimeout = setTimeout;
setTimeout = function(fn, t){
    let safeFn = () => {
        try {
            fn();
        } catch(e){
            console.log(e);
        }
    };
    return nativeSetTimeout(safeFn,t);
}

let nativeNextTick = process.nextTick;
process.nextTick = function(){
    let args = Array.prototype.slice.call(arguments);
    let fn = args[0];
    let safeFn = () => {
        try {
            fn.apply(null,args.slice(1));
        } catch(e){
            console.log(e);
        }
    };
    return nativeNextTick(safeFn);
}

I invoke this script in a beginning of an application.
nodeJS.getRuntime().executeVoidScript(workaroundScript);


text:
Q: Put labels over negative and positive geom_bar I'd like to visualize a data using bar chart and ggplot.
I have the data below, when I want to vis this data the text for negative values are not showing below the Bar .
dat <- read.table(text = "sample Types Value
sample1 A   -36
sample2 B   31
sample1 C   15
sample2 D   -12
sample1 E   27
sample2 F  16
sample2 G  -10
sample2 H  2
sample2 I  6
sample2 J  -7
sample2 K  -8"
, header=TRUE)

library(ggplot2)
px <- ggplot(data = dat , aes(x = Types , y = Value , Colour = Types ))
px + geom_bar(stat = "identity" ,color = "#FFFFFF" , fill = "dodgerblue3") +
  geom_text(aes(label=Value), position=position_dodge(width=0.9), hjust= -.25,vjust=0.25 ,size =3.5 , angle = 90)

A: Pass position of geom_text on y axis with y = Value + 2 * sign(Value)
library(ggplot2)
ggplot(dat, aes(Types, Value)) +
    geom_bar(stat = "identity" ,color = "#FFFFFF" , fill = "dodgerblue3") +
    geom_text(aes(y = Value + 2 * sign(Value), label = Value),
              position = position_dodge(width = 0.9),
              size = 3.5 , angle = 90)

Another plot with minor visual tweaks that I do on my plots:
As you have numbers with bars you don't need y-axis (it's redundant).
ggplot(dat, aes(Types, Value)) +
    geom_bar(stat = "identity", color = "black" , fill = "grey",
             size = 0.7, width = 0.9) +
    geom_text(aes(y = Value + 2 * sign(Value), label = Value),
              position = position_dodge(width = 0.9),
              size = 5) +
    theme_classic() +
    theme(axis.text.x = element_text(size = 12),
          axis.title = element_text(size = 20),
          axis.text.y = element_blank(),
          axis.line = element_blank(),
          axis.ticks = element_blank())


text:
Q: Migration en Laravel Quiero realizar una migration a MySQL, cuando pongo en mi línea de comandos la instrucción php artisan migrate me sale el siguiente error en consola:

In Connection.php line 664:
                                                                                could not find driver (SQL: select * from information_schema.tables
  where t     able_schema = curso and table_name = migrations)
In Connector.php line 67:
                              could not find driver

En mi archivo .env tengo definido
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=curso
DB_USERNAME=root
DB_PASSWORD=root

¿Como podría solucionarlo?