text:
Q: How to prevent closing of parent window before child window is closed I know that, from here,

grab_set() [#]:
  Routes all events for this application to this widget.

OK but it doesn't prevent the user to close the parent window with X button. In addition to other events, how can I route "X button close" event as well?
MWE:
from Tkinter import *

class Window(Toplevel):

    def __init__(self, master):
        Toplevel.__init__(self)

class MainWindow(Tk):

    def __init__(self):
        Tk.__init__(self)
        Button(self, command=self.open_window).grid(row=0, column=0)

    def open_window(self):
        win = Window(self)
        win.grab_set()

app = MainWindow()
app.mainloop()

A: For windows you can use:
root.protocol("WM_DELETE_WINDOW", your_function_here)
I don't know about other operating systems as I have not tested it on anything other than windows.
Works fine in a class as well.
self.root.protocol("WM_DELETE_WINDOW", self.your_method_here)
I have added some code to your post to illustrate its use. Note when you press the X button the program will rune the close_program method.
Edit: Without being able to test on Mac I have added what I think will fix your problem. I have added an if statement in the close_program method to check if the top level exist before attempting to close.
Update: I added a check for the variable win to deal with possible errors if toplevel was never opened but still trying to close root window.
from tkinter import *

class Window(Toplevel):

    def __init__(self, master):
        Toplevel.__init__(self)
        self.protocol("WM_DELETE_WINDOW", self.close_program)

    def close_program(self):
        print ("destroying Window")
        self.destroy()

class MainWindow(Tk):

    def __init__(self):
        Tk.__init__(self)
        Button(self, command=self.open_window).grid(row=0, column=0)
        self.protocol("WM_DELETE_WINDOW", self.close_program)

    def open_window(self):
        global win
        win = Window(self)
        win.grab_set()

    def close_program(self):
        if 'win' in globals():
            if win.winfo_exists() == 1:
                print("top level still active")
            else:
                print("destroying MainWindow")
                self.destroy()
        else:
            print("destroying MainWindow")
            self.destroy()

app = MainWindow()
app.mainloop()

A: Lets say that if the child window exists, trying to close the parent window will put it into focus, this would require a few changes:

*

*override the close protocol with .protocol("WM_DELETE_WINDOW") so it checks for a child window.

*Keep a reference to a child window

class MainWindow(Tk):

    def __init__(self):
        Tk.__init__(self)
        Button(self, text="hello there", command=self.open_window).grid(row=0, column=0)
        self.protocol("WM_DELETE_WINDOW", self.try_to_close)
        self.win = None

    def open_window(self):
        if self.win is None or not self.win.winfo_exists():
            self.win = Window(self)
        self.win.lift(self)
        self.win.focus_set()

    def try_to_close(self):
        if self.win is not None and self.win.winfo_exists():
            self.win.lift()
        else:
            self.destroy()


text: Q: Convert a Ubuntu OS tgz file to iso or qcow2 How can I convert my Ubuntu OS image in .tgz format to .iso or .qcow2 format. I need my OS image in the form of qcow2 or iso as I have to create a VM using this image with the help of virsh tools.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is this animation not moving? Matplotlib animation I am trying to plot an animation of the time evolution of a multiple top hat functions with different values of x_0 and alpha("a" in the code). It looks like it is plotting correctly, but it doesn't actually animate. I've tried varying frame_num, the frames and the interval. I've also tried calling the f_xtsqrd function before defining the line in the animation function, and testing the f_xtsqrd function to see if it actually changes with t, which it does. The labels are just placeholders at the moment. I know that the first chunk of code which I've lined off with ---- works, but the rest I'm not sure. I'm baffled as to what I've done wrong here, any help would be much appreciated.
----------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from IPython import display

def energy_eigen_odd(x,n,t=0): # Even meaning even n
  energy=n**2*np.pi**2/2
  eigen = np.sqrt(2)*np.cos(np.pi*n*x)*np.cos(energy*t)
  return eigen,energy

def energy_eigen_even(x,n,t=0):
  energy=n**2*np.pi**2/2
  eigen = np.sqrt(2)*np.sin(np.pi*n*x)*np.cos(energy*t)
  return eigen,energy

def energy_eigen_odd_image(x,n,t=0): # Even meaning even n
  energy=n**2*np.pi**2/2
  eigen = np.sqrt(2)*np.cos(np.pi*n*x)*np.sin(energy*t)
  return eigen,energy

def energy_eigen_even_image(x,n,t=0):
  energy=n**2*np.pi**2/2
  eigen = np.sqrt(2)*np.sin(np.pi*n*x)*np.sin(energy*t)
  return eigen,energy

def fn_odd(n,alpha,x_0): # Definining functions for fn for if it's being applied to odd or even psi.

  return np.sqrt(8/alpha)*(1/(n*np.pi))*np.cos((n*np.pi*x_0))*np.sin((n*np.pi*alpha)/2)

def fn_even(n,alpha,x_0):

  return np.sqrt(8/alpha)*(1/(n*np.pi))*np.sin((n*np.pi*x_0))*np.sin((n*np.pi*alpha)/2)
alpha=0.5
x_0=0.5
x=np.linspace(-1,1,1000)
def f_xt(x,n,x_0,alpha,t=0):
  sum_real=0
  sum_imag=0

  for i in range(1,n):

      if i % 2 == 0:# Determining the function is even
        sum_real += fn_even(i,alpha,x_0)*energy_eigen_even(x,i)[0]
        sum_imag += fn_even(i,alpha,x_0)*energy_eigen_even_image(x,i)[0]

      if i % 2 == 1: # Determining the function is odd
        sum_real += fn_odd(i,alpha,x_0)*energy_eigen_odd(x,i)[0]
        sum_imag += fn_odd(i,alpha,x_0)*energy_eigen_odd_image(x,i)[0]

  return sum_real, sum_imag
def f_xtsqrd(x,n,x_0,alpha,t=0):
  x,y=f_xt(x,n,x_0,alpha)
  return x**2 + y**2

----------------------------------------------------------------------------

fig=plt.figure()
ax=plt.axes()
x_01=-0.1
x_02=0.2
x_03=0.4
a1=0.8
a2=0.5
a3=0.2
line1, = ax.plot([],[],label=f'Alpha={a1}, x_0={x_01}')#Making empty lines to fill later.
line2, = ax.plot([],[],label=f'Alpha={a2}, x_0={x_02}')
line3, = ax.plot([],[],label=f'Alpha={a3}, x_0={x_03}')

x=np.linspace(-0.5,0.5,1000)
plt.xlabel('Time(Units)')
plt.ylabel('Values of data')
ax.legend(loc='upper right')#Defining where the legend is so it doesn't bounce around during the animation

# Setting axes so they don't move from frame to frame
ax.set_xlim(-0.5,0.5)
ax.set_ylim(0,10)

def animate(frame_num): # Defining the animation function

    n=50
    line1.set_data(x,f_xtsqrd(x,n,x_01,a1,t=0.1*frame_num))
    line2.set_data(x,f_xtsqrd(x,n,x_02,a2,t=0.1*frame_num))
    line3.set_data(x,f_xtsqrd(x,n,x_03,a3,t=0.1*frame_num))

    return line1,line2,line3

anim=FuncAnimation(fig,animate,frames=200, interval=10) #Setting the animation function to animate the figure, with 200 frames.

#The code needed to make the animation display
video = anim.to_html5_video()
html = display.HTML(video)
display.display(html)
plt.close()

A: The problem is that the code stops passing the t variable made from frame_num to the relevant functions. (Also since you defined a default value t=0 in these functions, no error is shown as a result of this.) See the modified functions below that make the animation run properly:
def f_xt(x, n, x_0, alpha, t=0):
    sum_real = 0
    sum_imag = 0

    for i in range(1, n):

        if i % 2 == 0:  # Determining the function is even
            sum_real += fn_even(i, alpha, x_0) * energy_eigen_even(x, i, t)[0]
            sum_imag += fn_even(i, alpha, x_0) * energy_eigen_even_image(x, i, t)[0]

        if i % 2 == 1:  # Determining the function is odd
            sum_real += fn_odd(i, alpha, x_0) * energy_eigen_odd(x, i, t)[0]
            sum_imag += fn_odd(i, alpha, x_0) * energy_eigen_odd_image(x, i, t)[0]

    return sum_real, sum_imag

def f_xtsqrd(x, n, x_0, alpha, t=0):
    x, y = f_xt(x, n, x_0, alpha, t)
    return x ** 2 + y ** 2


text:
Q: Prolog - summing up predicate results Let's say i have the following predicate:
func1(X,B,R)

I provide it with a certain X and B and in return it gives me 5 different results for R.
EDIT:
The X and B do not specify a range. rather, X specify an integer (say 120) and B specifies all integers (starting from 1) whose cubic is less than X.
What func1 does is calculating R as the result the remainder.
In this case where X=120:
B = 1, R = 119 (120-1^3)
B = 2, R = 112 (120-2^3)
B = 3, R = 93 (120-3^3)
B = 4, R = 56 (120-4^3)

It would not calculate B=5 since 5^3 = 125 which is greater than 120, so it stops here.
How can i make a predicate such as:
func2(R,S)

That would accept all of the results given by R, sum them up and store them in S?
Thanks!

A: To start with, since the values of B are totally derivable from the value of X, I wouldn't include both as arguments in func1. I'll introduce a predicate func3/2 which is true if the second argument is derivable from the first (i.e., func3(X, B) is true if B is derivable from X):
func1(X, R) :-
    func3(X, B),
    ...

What will happen if you query func1(120, R) is you'd get one or more results for R. Then you can use findall/3 as I indicated in my comment:
func2(X, S) :-
    findall(R, func1(X, R), Rs),
    sumlist(Rs, S).

To define func3/2 the cleanest approach would be to use CLP(FD):
:- use_module(library(clpfd)).

func3(X, B) :-
    B #>= 0,
    (X - B^3) #>= 0,
    label([B]).

Here's an example of what func3 does:
?- func3(120, B).
B = 1 ;
B = 2 ;
B = 3 ;
B = 4.

A much less desirable way to do this if you can't use CLP(FD) would be to use between and define the upper limit of B to be the greatest integer not exceeding the cube root of X:

func3(X, B) :-
    Limit is floor(exp(log(X) / 3)),
    between(1, Limit, B).

Which yields the same result as above.


text:
Q: Cовместимость Angular с IE 7 Вчера задался этим вопросом и до сих пор не получается, хотя в доках anglare всё черным по белому написано и много ответов на stackoverflow.. Сделал самый просто пример и буду рад, если Вы подскажете на его примере ( лучше прям его изменить ), чтобы он заработал.
index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Tests</title>

{{ message }}

app.js
var app = angular.module('app', [])
.controller('TestCtrl', function($scope){
    $scope.message = "Hello!";
})

A: Читайте доки глубже:

Note: AngularJS 1.3 is dropping support for IE8. Read more about it on our blog. AngularJS 1.2 will continue to support IE8, but the core team does not plan to spend time addressing issues specific to IE8 or earlier.

AngularJS 1.3 уже не поддерживает IE8. AngularJS 1.2 будет поддерживать IE8, но разработчики не планируют тратить время на баги, которые специфичны для IE.
Там же, описано, как заставить работать под 7 IE, но с определенными ограничениями. Если у Вас AngularJS 1.3 - то работать не будет, только на AngularJS 1.2.


text:
Q: How to make input text field to accept only specific special character - angularjs I want to restrict the input text field to accept only specific special characters and also the special character should not be the first character.
I have tried but could not able to find a solution for this problem.
<input type="text" ng-model="model.value" required="required" ng-pattern="/^[a-zA-Z0-9]+[^]*$/"/>

A: Given your attempt, I believe you want only A-Z, a-z and 0-9 for the first character, and after that, you want all characters except A-Z, a-z and 0-9.
The regex/ng-pattern for this is ^[a-zA-Z\d]+[^a-zA-Z\d]*$
So the field will be
<input type="text" ng-model="inputField" required="required" ng-pattern="/^[a-zA-Z\d]+[^a-zA-Z\d]*$/"/>


text:
Q: Brand new AngularFullstack app won't deploy to Heroku I'm having trouble deploying my app to Heroku.  I don't have this issue with an app I started several months ago so I think it must be something wrong with the lastest Angular Fullstack.  After several hours of trouble shooting I decided to start from scratch just to see if AngularFullstack would deploy if you create a completely fresh app in an empty directory.
I created the app in the terminal with:
yo angular-fullstack
Without doing anything else I deployed the app to Heroku by typing this in the terminal:
yo angular-fullstack:heroku
Finally I went to the Heroku webaddress and I get the following "Application Error":
An error occurred in the application and your page could not be served. Please try again in a few moments.
If you are the application owner, check your logs for details.
When I look at the Heroku logs I get the exact same error I was getting in my finished project:
Error: ENOENT, no such file or directory '/app/dist/public/favicon.ico'
I've tried putting this file everywhere in my directory structure.  There is no 'dist' in directory structure of the new app.  I put this directory in the old app with grunt serve:dist but that doesn't fix the problem of locating favicon.ico even though it is there in the public folder. There is no 'app' directory at the top however and it begins looking all the way in my Mac 'User' path.  I think this part of the problem that I don't know how to fix.


text:
Q: Force HINT In DB2 in SQL server I can force hint parellelism in execution of query using the HINT 'OPTION(MAXDOP 1)'.
Can you please help me with an equivaluent hint in DB2
My query in SQL server
select
from
table_name
option (maxdop 1)

A: Assuming you are using Db2 for LUW, query parallelism is controlled by the current degree. It does not need to be set as a hint. Parallel processing for applications


text:
Q: APACHE POI - Not able to give background colour to a cell I am generating excel file using java poi and trying to add a background color for the column heading in the excel.
Row row = sheet.createRow(0);

        CellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        style.setFillPattern(CellStyle.BIG_SPOTS);
        row.setRowStyle(style);

        for(RiskVo h : selectedExcel){
            row.createCell(h.getIndex()).setCellValue(h.getRisk_disc_en());
        }

But the color only displayed in the low to empty columns.

I want the background color for the first row. How can I fix this.

A: First, create the cell and then set the style inside the loop. It's work for me.
Row row = sheet.createRow(0);

CellStyle style = workbook.createCellStyle();
  style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
  style.setFillPattern(CellStyle.SOLID_FOREGROUND);

for(RiskVo h : selectedExcel){
    row.createCell(h.getIndex()).setCellValue(h.getRisk_disc_en());
    row.getCell(h.getIndex()).setCellStyle(style);
}

A: I guess your h.getIndex() starts from the beginning of worksheet. So after setting style for a row, you create new cells at the beginning of row and move existing cells to the right. Your solutions are:

*

*Create headers cells and then set style

Example
Row row = sheet.createRow(0);

for(RiskVo h : selectedExcel){
    row.createCell(h.getIndex()).setCellValue(h.getRisk_disc_en());
}

CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
style.setFillPattern(CellStyle.BIG_SPOTS);
row.setRowStyle(style);

*After setting style, don't create new cells, but get cells from row instead and insert value.

A: I have a really handy utility class I created to very easily color the background of a cell, change text color, and a lot of other stuff you might need to create really awesome spreadsheets from code. They are static methods and they instantly return CellStyle.
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Workbook;

/*
    Utility Class for Spreadsheet Cell Styling
 */

public class CellStyles {

public static CellStyle getTableHeaderStyle(Workbook workbook){
    CellStyle style = workbook.createCellStyle();

    Font font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontName("Times New Roman");
    style.setWrapText(true);
    style.setFont(font);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setLocked(true);

    return style;
}

public static CellStyle getShadedCellStyle(Workbook workbook, HSSFColor foreground, HSSFColor background ){
    CellStyle style = workbook.createCellStyle();

    Font font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontName("Times New Roman");
    style.setFont(font);

    style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    style.setFillForegroundColor(foreground.getIndex());
    style.setFillBackgroundColor(background.getIndex());
    style.setBorderBottom(CellStyle.BORDER_THIN);
    style.setBorderTop(CellStyle.BORDER_THIN);
    style.setBorderLeft(CellStyle.BORDER_THIN);
    style.setBorderRight(CellStyle.BORDER_THIN);
    style.setWrapText(true);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setLocked(true);

    return style;
}

public static CellStyle getColoredTextCellStyle(Workbook workbook, HSSFColor color){
    CellStyle style = workbook.createCellStyle();

    Font font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    font.setFontName("Times New Roman");
    style.setFont(font);
    style.setFillBackgroundColor(color.getIndex());
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setWrapText(true);
    font.setColor(color.getIndex());

    return style;
}

}
An example would be:
Workbook workbook = new HSSFWorkbook();
CellStyle style = CellStyles.getShadedCellStyle(workbook, new HSSFColor.BRIGHT_GREEN(), new HSSFColor.BLACK()));
...
someCell.setCellStyle(style);


text:
Q: While reading from socket how to detect when the client is done sending the request? I am now writing a http server and I am having problem with reading from a socket.
My problem is that the inputStream from the client never ends and it keeps reading until the client is closed.
I know that the client doesn't close the connection with the server immediately after sending the http request.
How can I quit the while loop when client has sent all the request data (i.e. headers + body).
while (in.hasNextLine()) {
    String line = in.nextLine();

    if (line.equals("")){ // last line of request header is blank
        break; // quit while loop when last line of header is reached
    } else {
        request = request + line + "\n";
    }
}

After reading comments and answer from you guys, this is what I came up with,
     is = incoming.getInputStream();
            os = incoming.getOutputStream();
            in = new Scanner(is);
            out = new DataOutputStream(os);

            RequestHandler rh = new RequestHandler();
            int length = 0;
            while (in.hasNextLine()) {
                String line = in.nextLine();
                if (line.equals("")) { // last line of request message
                                        // header is a
                                        // blank line
                    break; // quit while loop when last line of header is
                            // reached
                }

                if (line.startsWith("Content-Length: ")) { // get the
                                                            // content-length
                    int index = line.indexOf(':') + 1;
                    String len = line.substring(index).trim();
                    length = Integer.parseInt(len);
                }

                request = request + line + "\n";
            }

             byte[] body = new byte[length];
             int i = 0;
             while (i < length) {
             byte b = in.nextByte();
             body[i] = b;
             i++;
             }

but, I still don't get it about reading by bytes. I can write my code to read until -1, but still stuck when there is no EOF and client is not closing connection.

A: There are 3 ways of detecting the end of the stream depending on what requests you are handling:

*

*If it is a GET or HEAD request, you only need to read the HTTP headers, request body is normally ignored if it exists, so when you encounter \r\n\r\n, you reach the end of the request(actually the request headers).

*If it is a POST method, read the Content-Length in the header and read up to Content-Length bytes.

*If it is a POST method and the Content-Length header is absent, which is most likely to happen, read until -1 is returned, which is the signal of EOF.

A: I've got it :) Thank you guys for comments and answers...
     is = incoming.getInputStream(); // initiating inputStream
            os = incoming.getOutputStream(); // initiating outputStream

            in = new BufferedReader(new InputStreamReader(is)); // initiating
                                                                // bufferReader
            out = new DataOutputStream(os); // initiating DataOutputSteream

            RequestHandler rh = new RequestHandler(); // create a
                                                        // requestHandler
                                                        // object

            String line;
            while ((line = in.readLine()) != null) {
                if (line.equals("")) { // last line of request message
                                        // header is a
                                        // blank line (\r\n\r\n)
                    break; // quit while loop when last line of header is
                            // reached
                }

                // checking line if it has information about Content-Length
                // weather it has message body or not
                if (line.startsWith("Content-Length: ")) { // get the
                                                            // content-length
                    int index = line.indexOf(':') + 1;
                    String len = line.substring(index).trim();
                    length = Integer.parseInt(len);
                }

                request.append(line + "\n"); // append the request
            } // end of while to read headers

            // if there is Message body, go in to this loop
            if (length > 0) {
                int read;
                while ((read = in.read()) != -1) {
                    body.append((char) read);
                    if (body.length() == length)
                        break;
                }
            }

            request.append(body); // adding the body to request

A: I want to share my code that works great:
private static String getClientRequest(Socket client) throws IOException, SocketException {
    System.out.println("Debug: got new client " + client.toString());
    BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));

    StringBuilder requestBuilder = new StringBuilder();
    String line;
    int contectLegnth = 0;

    while (!(line = br.readLine()).isBlank()) {
        requestBuilder.append(line + "\r\n");
        if (line.toLowerCase().startsWith("content-length")) {
            contectLegnth = Integer.parseInt(line.split(":")[1].trim());
        }
    }

    StringBuilder requestBodyBuilder = new StringBuilder();
    if (contectLegnth > 0) {
        int read;
        while ((read = br.read()) != -1) {
            requestBodyBuilder.append((char) read);
            if (requestBodyBuilder.length() == contectLegnth)
                break;
        }
        requestBuilder.append("\r\n" + requestBodyBuilder);
    }

    return requestBuilder.toString();
}


text:
Q: How to format output of system function PHP? I use function system() to run system process.
$buff = system('python excel.py ' . $handle->file_dst_pathname, $retval);

It displays messages in line without separations.
In Python I use this line to print data:
 print "# %d - article \"%s\" was inserted!" % (i, article)

A: Precede the output of system(...); with echo "
"; and follow with echo "
";
Or shorter:
$buff = "
" . system('python excel.py ' . $handle->file_dst_pathname, $retval) . "
";

You could also change all the "\n" chars of your output into "
".


text:
Q: Running a feature using @RunWith(Cucumber.class) instead of @RunWith(CucumberWithSerenity.class) I am getting this warning in Eclipse. Any idea how to resolve this?
[main] WARN cucumber.runtime.SerenityBackend - It looks like you are running a feature using @RunWith(Cucumber.class) instead of @RunWith(CucumberWithSerenity.class). Are you sure this is what you meant to do?

And also the below issue while trying to open Google page through Serenity-Cucmber:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.google.inject.internal.cglib.core.$ReflectUtils$1 (file:/C:/Users/304090/.m2/repository/com/google/inject/guice/4.2.0/guice-4.2.0.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of com.google.inject.internal.cglib.core.$ReflectUtils$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
    Given Open the google home page                                              # StepDefinitions.the_launch_link()
      java.lang.NullPointerException
    at org.apache.commons.lang3.SystemUtils.isJavaVersionAtLeast(SystemUtils.java:1654)
    at org.apache.commons.lang3.ClassUtils.isAssignable(ClassUtils.java:760)
    at net.thucydides.core.steps.StepFactory$ParameterAssignementChecker.cannotBeAssignedTo(StepFactory.java:332)
    at net.thucydides.core.steps.StepFactory.parametersMatchFor(StepFactory.java:242)
    at net.thucydides.core.steps.StepFactory.argumentTypesFrom(StepFactory.java:218)
    at net.thucydides.core.steps.StepFactory.immutableStepLibrary(StepFactory.java:212)
    at net.thucydides.core.steps.StepFactory.createProxyStepLibrary(StepFactory.java:203)
    at net.thucydides.core.steps.StepFactory.instantiateUniqueStepLibraryFor(StepFactory.java:179)
    at net.thucydides.core.steps.StepFactory.getUniqueStepLibraryFor(StepFactory.java:115)
    at net.serenitybdd.screenplay.Tasks.instrumented(Tasks.java:12)
    at net.serenitybdd.screenplay.actions.Open.url(Open.java:19)
    at step_defenitions.StepDefinitions.the_launch_link(StepDefinitions.java:30)
    at ✽.Open the google home page(C:/Users/304090/eclipse-workspace/evms-qa-test-automation/src/test/resources/features/CreatePreViolReport.feature:5)

A: This issue resolved after changing the serenity version to the latest. And also had to update my browser version too.


text:
Q: Is using a Mutex to prevent multiple instances of the same program from running safe? I'm using this code to prevent a second instance of my program from running at the same time, is it safe?
Mutex appSingleton = new System.Threading.Mutex(false, "MyAppSingleInstnceMutx");
if (appSingleton.WaitOne(0, false)) {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new MainForm());
    appSingleton.Close();
} else {
    MessageBox.Show("Sorry, only one instance of MyApp is allowed.");
}

I'm worried that if something throws an exception and the app crashes that the Mutex will still be held. Is that true?

A: It is more usual and convenient to use Windows events for this purpose. E.g.
static EventWaitHandle s_event ;

bool created ;
s_event = new EventWaitHandle (false,
    EventResetMode.ManualReset, "my program#startup", out created) ;
if (created) Launch () ;
else         Exit   () ;

When your process exits or terminates, Windows will close the event for you, and destroy it if no open handles remain.
Added: to manage sessions, use Local\ and Global\ prefixes for the event (or mutex) name. If your application is per-user, just append a suitably mangled logged-on user's name to the event name.

A: In general yes this will work.  However the devil is in the details.
Firstly you want to close the mutex in a finally block.  Otherwise your process could abruptly terminate and leave it in a signaled state, like an exception.  That would make it so that future process instances would not be able to start up.
Unfortunately though, even with a finally block you must deal with the potential that a process will be terminated without freeing up the mutex.  This can happen for instance if a user kills the process through TaskManager.  There is a race condition in your code that would allow for a second process to get an AbandonedMutexException in the WaitOne call.  You'll need a recovery strategy for this.
I encourage you to read up on the details of the Mutex class.  Using it is not always simple.

Expanding upon the race condition possibility:
The following sequence of events can occur which would cause a second instance of the application to throw:

*

*Normal process startup.

*Second process starts up and aquires a handle to the mutex but is switched out before the WaitOne call.

*Process #1 is abruptly terminated.  The mutex is not destroyed because process #2 has a handle.  It is instead set to an abandoned state.

*The second process starts running again and gets an AbanonedMutexException.

A: On Windows, terminating a process has the following results:

*

*Any remaining threads in the process are marked for termination.

*Any resources allocated by the process are freed.

*All kernel objects are closed.

*The process code is removed from memory.

*The process exit code is set.

*The process object is signaled.

Mutex objects are kernel objects, so any held by a process are closed when the process terminates (in Windows anyway).
But, note the following bit from the CreateMutex() docs:

If you are using a named mutex to limit your application to a single instance, a malicious user can create this mutex before you do and prevent your application from starting.

A: Yes, it's safe, I'd suggest the following pattern, because you need to make sure that the Mutex gets always released.
using( Mutex mutex = new Mutex( false, "mutex name" ) )
{
    if( !mutex.WaitOne( 0, true ) )
    {
        MessageBox.Show("Unable to run multiple instances of this program.",
                        "Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
    }
    else
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
}

A: Here's the code snippet
public enum ApplicationSingleInstanceMode
{
    CurrentUserSession,
    AllSessionsOfCurrentUser,
    Pc
}

public class ApplicationSingleInstancePerUser: IDisposable
{
    private readonly EventWaitHandle _event;

    /// <summary>
    /// Shows if the current instance of ghost is the first
    /// </summary>
    public bool FirstInstance { get; private set; }

    /// <summary>
    /// Initializes
    /// </summary>
    /// <param name="applicationName">The application name</param>
    /// <param name="mode">The single mode</param>
    public ApplicationSingleInstancePerUser(string applicationName, ApplicationSingleInstanceMode mode = ApplicationSingleInstanceMode.CurrentUserSession)
    {
        string name;
        if (mode == ApplicationSingleInstanceMode.CurrentUserSession)
            name = $"Local\\{applicationName}";
        else if (mode == ApplicationSingleInstanceMode.AllSessionsOfCurrentUser)
            name = $"Global\\{applicationName}{Environment.UserDomainName}";
        else
            name = $"Global\\{applicationName}";

        try
        {
            bool created;
            _event = new EventWaitHandle(false, EventResetMode.ManualReset, name, out created);
            FirstInstance = created;
        }
        catch
        {
        }
    }

    public void Dispose()
    {
        _event.Dispose();
    }
}

A: You can use a mutex, but first make sure that this is really what you want.
Because "avoiding multiple instances" is not clearly defined. It can mean

*

*Avoiding multiple instances started in the same user session, no matter how many desktops that user session has, but allowing multiple instances to run concurrently for different user sessions.

*Avoiding multiple instances started in the same desktop, but allowing multiple instances to run as long as each one is in a separate desktop.

*Avoiding multiple instances started for the same user account, no matter how many desktops or sessions running under this account exist, but allowing multiple instances to run concurrently for sessions running under a different user account.

*Avoiding multiple instances started on the same machine. This means that no matter how many desktops are used by an arbitrary number of users, there can be at most one instance of the program running.

By using a mutex, you're basically using the define number 4.

A: I use this method, I believe it to be safe because the Mutex is destroyed if no long held by any application (and applications are terminated if if they can't initially create the Mutext). This may or may not work identically in 'AppDomain-processes' (see link at bottom):
// Make sure that appMutex has the lifetime of the code to guard --
// you must keep it from being collected (and the finalizer called, which
// will release the mutex, which is not good here!).
// You can also poke the mutex later.
Mutex appMutex;

// In some startup/initialization code
bool createdNew;
appMutex = new Mutex(true, "mutexname", out createdNew);
if (!createdNew) {
  // The mutex already existed - exit application.
  // Windows will release the resources for the process and the
  // mutex will go away when no process has it open.
  // Processes are much more cleaned-up after than threads :)
} else {
  // win \o/
}

The above suffers from from notes in other answers/comments about malicious programs being able to sit on a mutex. Not a concern here. Also, unprefixed mutex created in "Local" space. It's probably the-right-thing here.
See: http://ayende.com/Blog/archive/2008/02/28/The-mysterious-life-of-mutexes.aspx -- comes with Jon Skeet ;-)

A: Here is how I have approached this
In the Program class:

*

*Get a System.Diagnostics.Process of YOUR application using Process.GetCurrentProcess()

*Step through the collection of open processes with the current name of your application using Process.GetProcessesByName(thisProcess.ProcessName)

*Check each process.Id against thisProcess.Id and if an instance is already opened then at least 1 will match name but not Id, otherwise continue opening instance
using System.Diagnostics;

.....

static void Main()
{
   Process thisProcess = Process.GetCurrentProcess();
   foreach(Process p in Process.GetProcessesByName(thisProcess.ProcessName))
   {
      if(p.Id != thisProcess.Id)
      {
         // Do whatever u want here to alert user to multiple instance
         return;
      }
   }
   // Continue on with opening application

A nice touch to finish this off would be to present the already opened instance to the user, chances are they didn't know it was open, so let's show them it was. To do this I use User32.dll to Broadcast a message into the Windows messaging loop, a custom message, and I have my app listen for it in the WndProc method, and if it gets this message, it presents itself to the user, Form.Show() or whatnot.

A: If you want to use a mutex-based approach, you should really use a local mutex to restrict the approach to just the curent user's login session. And also note the other important caveat in that link about robust resource disposal with the mutex approach.
One caveat is that a mutex-based approach doesn't allow you to activate the first instance of the app when a user tries to start a second instance.
An alternative is to PInvoke to FindWindow followed by SetForegroundWindow on the first instance. Another alternative is to check for your process by name:
Process[] processes = Process.GetProcessesByName("MyApp");
if (processes.Length != 1)
{
    return;
}

Both of these latter alternatives have a hypothetical race condition where two instances of the app could be started simultaneously and then detect each other. This is unlikely to happen in practice - in fact, during testing I couldn't make it happen.
Another issue with these two latter alternatives is that they won't work when using Terminal Services.

A: Use app with timeout and security settings with avoiding AbandonedMutexException. I used my custom class:
private class SingleAppMutexControl : IDisposable
    {
        private readonly Mutex _mutex;
        private readonly bool _hasHandle;

        public SingleAppMutexControl(string appGuid, int waitmillisecondsTimeout = 5000)
        {
            bool createdNew;
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
            _mutex = new Mutex(false, "Global\\" + appGuid, out createdNew, securitySettings);
            _hasHandle = false;
            try
            {
                _hasHandle = _mutex.WaitOne(waitmillisecondsTimeout, false);
                if (_hasHandle == false)
                    throw new System.TimeoutException();
            }
            catch (AbandonedMutexException)
            {
                _hasHandle = true;
            }
        }

        public void Dispose()
        {
            if (_mutex != null)
            {
                if (_hasHandle)
                    _mutex.ReleaseMutex();
                _mutex.Dispose();
            }
        }
    }

and use it:
    private static void Main(string[] args)
    {
        try
        {
            const string appguid = "{xxxxxxxx-xxxxxxxx}";
            using (new SingleAppMutexControl(appguid))
            {
                //run main app
                Console.ReadLine();
            }
        }
        catch (System.TimeoutException)
        {
            Log.Warn("Application already runned");
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Fatal Error on running");
        }
    }

A: It is important to remember that this mutexes\events can be easily seen via programs like handle.exe from Microsoft sysinternals and then if constant name used someone evil may use this to prevent your app from starting.
Here is some quote from Microsoft recommendations on safe alternatives:

However, a malicious user can create this mutex before you do and
  prevent your application from starting. To prevent this situation,
  create a randomly named mutex and store the name so that it can only
  be obtained by an authorized user. Alternatively, you can use a file
  for this purpose. To limit your application to one instance per user,
  create a locked file in the user's profile directory.

Taken from here :
https://learn.microsoft.com/en-us/sysinternals/downloads/handle


text:
Q: pointer passing between functions fails with error I am trying to write two functions, one calls the other and passes in an argument:
int RegisterImage( const char * streamID, IMGStream & c ) {
...
}

int OpenImage( const char * streamid, int dsize ) {
ImageStream * im;
int idx = -1;

if ( GetImgRegIdx(streamid, dsize, im) )
          idx = RegisterImage (streamid, im);
return idx;
}

The calling of "RegisterImage()" fails. It complains about:
"in passing argument 2 of 'int Core::RegisterImage(const char*, IMGStream&)'"
Can anybody help me understand why it's complaining, and how to fix it?
Thanks so much

A: ImageStream * im; is a pointer, your RegisterIMage() expects a reference as its second argument. You need to pass in *im. References implicitly refer to objects, not to addresses. Your ImageStream* is type that holds an address.

A: It's asking for an IMGStream& which you read as 'IMGStream Reference'.  Although this acts very much like passing a pointer, the syntax must not be.
Try de-referencing your pointer with a * (the de-reference operator)
     idx = RegisterImage (streamid, *im);

A: Assuming IMGStream and ImageStream objects are the same type (one being a typedef of the other or something), then the function is expecting a reference and you're passing a pointer.
So, if IMGStream and ImageStream objects are actually the same type, you should pass *im instead of im.


text:
Q: Kraken API error "EFunding:Unknown withdraw key" I'm currently using the Kraken API to make orders and withdraw currency.
The problem is when I want to withdraw EUR thanks to the Kraken API, they ask me to put my ithdrawal key name. I thought it was my API key or my key description, but none of these methods actually works.
 aclass = asset class (optional):

    currency (default)

 asset = asset being withdrawn

 key = withdrawal key name, as set up on your account

 amount = amount to withdraw, including fees

Where can I retrieve my withdrawal key name on my account ?
Thanks.

A: "key = withdrawal key name, as set up on your account"
You must declare the addresses (send to), and assign a unique name (key) to each address.
I know... it's terrible.


text:
Q: JQ: Merging different objects into a new array I use jq 1.5 in a Windows enviroment to modify json files.
Hi have following json file:
{"player_container":{"74016":["None","None","None","None","None","None","None","None"],"74002":["None","None","None","ta81a928e0624295b01499d7035d0308","tdd4e222600d42f9954b0be0448da0b1","None","None","None"],"74007":["None","None","None","None","None","None","None","None"],"74009":["None","None","None","None","None","None","kcb810a423dd4e179027f0feaae9ea60","None"],"74012":["x720ed571876471fab173ba05f71e4b3","None","None","None","None","None","None","None"],"74013":["None","None","None","None","None","None","None","None"],"74014":["vd86094b5a6e448f8c416d6fe75bec7c","None","None","h6ef696cf767464f9c367150fdb29fe4","None","g77b124cd46b41399c3db219ac0a76bd","None","None"],"74015":["None","None","None","None","None","None","None","None"]}}

In the object player_container are different objects (the "name" of the object and the number objects differs from time to time).
I use following jq command actually to join them into a new array:
.player_container | .[] | [{ user_id: .[]}]

But it generates different json Arrays and not one. What i need looks like:
   [
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  }
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "ta81a928e0624295b01499d7035d0308"
  },
  {
    "user_id": "tdd4e222600d42f9954b0be0448da0b1"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  }
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  }
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "kcb810a423dd4e179027f0feaae9ea60"
  },
  {
    "user_id": "None"
  }
  {
    "user_id": "x720ed571876471fab173ba05f71e4b3"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  }
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  }
  {
    "user_id": "vd86094b5a6e448f8c416d6fe75bec7c"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "h6ef696cf767464f9c367150fdb29fe4"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "g77b124cd46b41399c3db219ac0a76bd"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  }
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  },
  {
    "user_id": "None"
  }
]

Any tips?
BR
Timo

A: You only have to move one character:
[.player_container | .[] | { user_id: .[]}]

While your version creates a separate array for each output of .player_container | .[], this will collect everything into one array.


text:
Q: Hibernate.Integer cannot be resolved while using addScalar() method String qry = select max(total) as max_marks from student;
SQLQuery sq = ses.createSQLQuery(qry);
sq.addScalar("max_marks",Hibernate.Integer);

Compilation Error:
Hibernate.Integer ---> Cannot be resolved

please specify What are the modifications i have to do?


text:
Q: https://sessions.bugsnag.com": x509: certificate signed by unknown authority I have integrated bugsnag with my go-service, and it was working good on my local machine;
but when I deployed it on server it giving the above error whenever bugsnag try to notify error.
I am deploying it on ec2 with docker container.
after exploring Internet I have added below command to my docker file
RUN apk add --no-cache ca-certificates

but this also did not work for me
Below is simplified version of code I am using
package main

import (
    "fmt"
    "github.com/bugsnag/bugsnag-go/v2"
    "time"
)

func init() {
    ConfigureBugsnag()
}

func ConfigureBugsnag() {
    bugsnag.Configure(bugsnag.Configuration{
        APIKey:          "bugsnagKey",
        ReleaseStage:    "stage",
        ProjectPackages: []string{"main", "github.com/myapp"},
    })
}

func main() {

    bugsnag.Notify(fmt.Errorf("Test error"))

    time.Sleep(time.Hour)
}

this is working on local machine but giving the error on server

A: I don't have much explanation:
but adding following in the Dockerfile, solved the issue
RUN apk add -U --no-cache ca-certificates
FROM scratch as final
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/


text:
Q: Method decorator should return first execution result Typescript I have a method decorator that allows to execute a decorated method only once.This function works good,but at my third unit test it failes because it gives undefined but should return first execution result.
This is my decorator:
import "reflect-metadata";

const metadataKey = Symbol("initialized");

function once(
    target: any,
    propertyKey: string,
    descriptor: PropertyDescriptor
) {
    const method = descriptor.value;
    descriptor.value = function (...args) {
        const initialized = Reflect.getMetadata(
            metadataKey,
            target,
            propertyKey
        );

        if (initialized) {
            return;
        }

        Reflect.defineMetadata(metadataKey, true, target, propertyKey);

        method.apply(this, args);
    };
}

I think the problem is in the return from the if statement,it should return something but idk what.I played a little but got no succes,thats why i beg you for help.
These are the unit tests:
describe('once', () => {
    it('should call method once with single argument', () => {
        class Test {
            data: string;
            @once
            setData(newData: string) {
                this.data = newData;
            }
        }
        const test = new Test();
        test.setData('first string');
        test.setData('second string');
        assert.strictEqual(test.data, 'first string')
    });

    it('should call method once with multiple arguments', () => {
        class Test {
            user: {name: string, age: number};
            @once
            setUser(name: string, age: number) {
                this.user = {name, age};
            }
        }
        const test = new Test();
        test.setUser('John',22);
        test.setUser('Bill',34);
        assert.deepStrictEqual(test.user, {name: 'John', age: 22})
    });

    it('should return always return first execution result', () => {
        class Test {
            @once
            sayHello(name: string) {
                return `Hello ${name}!`;
            }
        }
        const test = new Test();
        test.sayHello('John');
        test.sayHello('Mark');
        assert.strictEqual(test.sayHello('new name'), 'Hello John!')
    })
});

Thanks in advance!

A: This decorator basically does memoization, but the result of the method call isn't stored anywhere. This is what's missing.
My suggestion would be to add another piece of metadata called result or something:
const meta = Reflect.getMetadata(...);

if (meta?.initialized) return meta.result;

const result = method.apply(this, args);
const newMeta = { initialized: true, result };

Reflect.defineMetadata(metadataKey, newMeta, target, propertyKey);


text:
Q: How to resolve UnicodeEncodeError storing data in json format I have scraped data from a website but for some items it shows me below error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\2019' in position 4: ordinal not in range(128)

I have even put "# -- coding: utf-8 --" at the top of the document but it is not worked. Please help.

A: Either always consider the unicode content or remove the unicode content entirely. The error is occurring because you (or some library methods you're using) are trying to convert utf-8 content into ascii without ignoring the errors.
# Ignore unicode content
content_string = content_string.encode('ascii', 'ignore')

# Or make sure you handle unicode content as such. It would have been
# easier if you're using Python3x.

The purpose of # -- coding: utf-8 -- is to allow explicitly adding Unicode content into a python code file, and not to set the default encoding.
# -- coding: utf-8 --
book_name = 'Les Misérables'


text:
Q: Add local repository in specific folder of GIT server repo I'm migrating code from SVN to GIT using SubGit.
Some of my SVN repositories are built as:
SVN-Repo
    + Project1
        + trunk
        + branches
        + tags
    + Project2
        + trunk
        + branches
        + tags

Using SubGit:
subgit import --svn-url <svn_server>/SVN-Repo/Project1 C:\GitRepos\SVN-Repo\Project1.git --username xxx --password xxx.

After what I clone in a local repo.
Then:
git clone <Git_server>/_git/GIT-Repo
git push -u origin --all

The result is that in GIT-Repo at the end I don' have a folder named Project1 like I had with SVN.
After investigation I dind't find  the command allowing me to create this Proejct1 folder GIT repo.
Could you pelase help me?
Thank you in advance.

A: There're 3 options
Option 1. What you already did (the most reasonable option).
Convert both projects in SVN into 2 separate Git repositories.
Then setup access to the repositories using GitLab, Atlassian Bitbucket Server, or any other Git server software.
Option 2. Treat the whole SVN repository as a single directory.
subgit configure --svn-url <svn_server>/SVN-Repo --layout directory C:\GitRepos\SVN-Repo\repo.git

subgit install C:\GitRepos\SVN-Repo\repo.git

Then you can run
subgit uninstall C:\GitRepos\SVN-Repo\repo.git

if you don't need continuous synchronization. In this case the Git repository will be rooted at SVN-Repo.
Option 3. One Git repository with branches from both projects.
subgit configure --svn-url <svn_server>/SVN-Repo C:\GitRepos\SVN-Repo\repo.git

Then edit repo.git/subgit/config to set
trunk = Project1/trunk:refs/heads/project1-master
branches = Project2/trunk:refs/heads/project2-master
branches = Project1/branches/*:refs/heads/project1-*
branches = Project2/branches/*:refs/heads/project2-*
shelves = shelves/*:refs/shelves/*
tags = Project1/tags/*:refs/tags/project1-*
tags = Project2/tags/*:refs/tags/project2-*

Then run
subgit install C:\GitRepos\SVN-Repo\repo.git

Then you can run
subgit uninstall C:\GitRepos\SVN-Repo\repo.git

if you don't need continuous synchronization.
In this case you have 1 Git repository with branches starting with project1- and project2- corresponding to your project. Instead of project1-/project2- you can also use project1//project2/.
So depeding on what you need you can choose one of these 3 options but the first one is the best one.

A: For a one-time conversion of SVN to git, I'd recommend using svn2git. There are many tools with this name. Probably the best is the KDE one at https://github.com/svn-all-fast-export/svn2git. To analyze the SVN repo history upfront for building up proper rules for svn2git, you might use svneverever from here: http://blog.hartwork.org/?p=763.
I transformed a couple of SVN repos to Git already with these and does a really great job.
And you can use the prefix rule there to get the subdirectory you want.


text:
Q: Caret disappears in Firefox when saving its position with Rangy This happens only in Firefox.
Important: I am saving the caret's position with rangy.saveSelection():

*

*when click the content editable div

*on keyup

*when adding an external html element (as a node) to the content editable div

I need the position saved constantly through multiple means to be able to insert html elements on click (I have some tags).
When I click in the contentEditable div and the div is empty (first focus, let's say), I cannot see the caret unless I start typing. If the caret is at the end, I cannot see it either.
Another weird behaviour is that I cannot use the arrows to navigate between the text in the contentEditable div.
If I remove the functions which (constantly) saves the caret's position (on input, click etc.) the caret returns to normal (the caret is visible).
The problem appears when I start saving the position of the caret. Clearly I should be doing some sort of reset or a clear.. but from what I understand, those seem counterproductive (as from my understanding they destroy the saved caret location).
The content editable div

                    <div
                            @keydown.enter.prevent
                            @blur="addPlaceholder"
                            @keyup="saveCursorLocation($event); fixDelete(); clearHtmlElem($event);"
                            @input="updateBooleanInput($event); clearHtmlElem($event);"
                            @paste="pasted"
                            v-on:click="clearPlaceholder(); saveCursorLocation($event);"
                            class="input__boolean-content"
                            ref="divInput"
                            contenteditable="true">Cuvinte cheie, cautare booleana..

My methods/functions
            inputLength($event){
                this.input_length = $event.target.innerText.length;
                if(this.input_length == 0)
                    this.typed = false;
            },
            addPlaceholder(){
                if(this.input_length == 0 && this.typed == false){
                    this.$refs.divInput.innerHTML = 'Cuvinte cheie, cautare booleana..'
                }
            },
            clearPlaceholder(){
                if(this.input_length == 0 && this.typed == false){
                    this.$refs.divInput.innerHTML = '';
                }
            },
            updateBooleanInput($event){
                this.typed = true;
                this.inputLength($event);
            },
            saveCursorLocation($event){
                if($event.which != 8){
                    if(this.saved_sel)
                        rangy.removeMarkers(this.saved_sel)
                    this.saved_sel = rangy.saveSelection();
                }
                // if(this.input_length == 0 && this.typed == false){
                //  var div = this.$refs.divInput;
                //  var sel = rangy.getSelection();
                //  sel.collapse(div, 0);
                // }
            },
            insertNode: function(node){
                var selection = rangy.getSelection();
                var range = selection.getRangeAt(0);
                range.insertNode(node);
                range.setStartAfter(node);
                range.setEndAfter(node);
                selection.removeAllRanges();
                selection.addRange(range);
            },
            addBooleanTag($event){
                // return this.$refs.ChatInput.insertEmoji($event.img);
                this.$refs.divInput.focus();
                console.log(this.input_length);
                if(this.typed == false & this.input_length == 0){
                    this.$refs.divInput.innerHTML = ''
                    var space = '';
                    this.typed = true
                    this.saveCursorLocation($event);
                }
                rangy.restoreSelection(this.saved_sel);

                var node = document.createElement('img');
                node.src = $event.img;
                node.className = "boolean-button--img boolean-button--no-margin";
                node.addEventListener('click', (event) => {
                    // event.currentTarget.node.setAttribute('contenteditable','false');
                    this.$refs.divInput.removeChild(node);
                })
                this.insertNode(node);
                this.saveCursorLocation($event);
            },
            clearHtmlElem($event){
                var i = 0;
                var temp = $event.target.querySelectorAll("span, br");
                if(temp.length > 0){
                    for(i = 0; i < temp.length; i++){
                        if(!temp[i].classList.contains('rangySelectionBoundary')){
                            if (temp[i].tagName == "br"){
                                temp[i].parentNode.removeChild(temp[i]);
                            } else {
                                temp[i].outerHTML = temp[i].innerHTML;
                            }
                        }
                    }
                }
            },
            pasted($event){
                $event.preventDefault();
                var text = $event.clipboardData.getData('text/plain');
                this.insert(document.createTextNode(text));
                this.inputLength($event);
                this.typed == true;
            },
            insert(node){
                this.$refs.divInput.focus();
                this.insertNode(node);
                this.saveCursorLocation($event);
            },

As you can see in the saveCursorLocation(), I was trying to solve the scenario in which you click in the contentEditable div and there's no caret - which is confusing for the user.
                // if(this.input_length == 0 && this.typed == false){
                //  var div = this.$refs.divInput;
                //  var sel = rangy.getSelection();
                //  sel.collapse(div, 0);
                // }

It was a dead end - most likely because of my poor understanding of Rangy and how should I use those functions.
Expected behaviour vs actual results on Firefox
When I click on the contentEditable div I expect the caret to appear (while in the background to save my position). When typing, I expect the caret to appear after the last typed character while also on keyup to save my caret's position. Also I expect to be able to navigate the text via left/right arrows and see the caret when doing so.
All of these are generated by
v-on:click="..... saveCursorLocation($event);"

and
@keyup="saveCursorLocation($event);....."

If anybody believes that it would be helpful, I can record the content editable div and its behaviour in Firefox.
EDIT: I managed to isolate the problem and reproduce it into a JSFiddle - https://jsfiddle.net/Darkkz/6Landbj5/13.
What to look for?

*

*Open the fiddle link in Firefox, then press one of the blue buttons (SI, SAU, NU) and then look at the input, the caret is not displayed.

*Click the input, the caret is not displayed

*While typing in the input,the caret is not displayed. Although, if you click in a word/in between content, the caret will be displayed

A: Apparently rangy's Selection Save and Restore module can't be used to keep track of the current selection while the user interacts with a contenteditable, like you want.
I digged into it a bit, and the problem is that rangy inserts hidden s as markers, and updates the selection to be after the marker, instead of keeping it inside the #text node the user's editing:

    #text [This is something I typed ]

Firefox has trouble displaying the caret in this scenario (I haven't found a bug about this specific issue, but here's a similar one where the caret is not displayed when the selection is between two s).
Commenting this code out seems to fix the issue with the disappearing caret. It's unclear to me why that code is needed -- it was added before 1.0 in a large commit with its message saying: "Fixes for save/restore problems with control ranges and multiple range selections. Added demos for save/restore and CSS class applier modules." -- so I'm not comfortable to suggest fixing this in rangy (and since it's unmaintained for a few years, I don't have much hope in getting its author's input on this).
So I tried to figure out why you needed this in the first place, to suggest other solutions not involving rangy.saveSelection (for example, rangy's Text Range module provides getSelection().saveCharacterRanges(containerNode) that works without modifying the DOM.
It appears that you have a
 and some "buttons" (s), clicking on which would insert some HTML at the caret position. The problem you were trying to solve was that when the "buttons" were clicked, the selection moved from the contenteditable into the button, and you were unable to detect the insert position.
Instead of storing and restoring the selection, you can instead make the buttons user-select: none - this will keep the caret in the contenteditable.
To test this, I commented out all references to rangy.saveSelection and rangy.restoreSelection and changed the this.$refs.divInput.focus(); call in the "button"'s onclick handler to run only when the contenteditable wasn't already focused by wrapping it in an if (!this.$refs.divInput.contains(document.activeElement)). See how this works in this updated fiddle:
https://jsfiddle.net/fjxsgvm2/


text:
Q: binding images from xml to listbox in windows phone application My xml file look's like this
<people><person> <firstname>venakt</firstname> <lastname>es</lastname> <age>27</age> <Image>http://www.livetut.com/wp-content/uploads/2012/06/Logo1.png</Image> </person></people>

My XAML file looks like
<ListBox.ItemTemplate>
 <DataTemplate>
  <StackPanel>
    <Image Source="{Binding ImageSource}" Height="120" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center" Tap="textBlock1_tap" />
    <TextBlock Text="{Binding UserName}" Style="{StaticResource PhoneTextSubtleStyle}" Width="100" TextAlignment="Center"/>
  </StackPanel>
 </DataTemplate>
</ListBox.ItemTemplate>

in my xaml.cs file i have add
public string Image { get { return Image; } set { Image = value; } }

XDocument loadedData = XDocument.Load("People.xml");
    var data = from query in loadedData.Descendants("person")
                  select new Person
                  {
                      FirstName = (string)query.Element("firstname"),
                      LastName = (string)query.Element("lastname"),
                      Image= query.Element("Image").Attribute("url").Value

                  };
    listBox.ItemsSource = data;

can u help me how to bind a image

A: Just change the name ImageSource to Image (Image is the property name of your Person class .. so)
<ListBox.ItemTemplate>
 <DataTemplate>
  <StackPanel>
    <Image Source="{Binding Image}" Height="120" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center" Tap="textBlock1_tap" />
    <TextBlock Text="{Binding UserName}" Style="{StaticResource PhoneTextSubtleStyle}" Width="100" TextAlignment="Center"/>
  </StackPanel>
 </DataTemplate>
</ListBox.ItemTemplate>


text:
Q: Matching [],{},() in Mac In the Windows system, the keyboard shortcuts
Matching [] Alt+]
Matching {} Alt+}
Matching () Alt+)
works fine.
This functionality does not seem to work with MacOS.
Opt+] gives '
Opt+} gives "
Opt+) gives '
Is there any way to ensure the same functionality as Windows?


text:
Q: Jquery Address или похожие библиотеки Подскажите, столкнулся с вот такой вот проблемой. Нужно, чтобы на сайте работал ajax с изменением url страницы по выполнению! Но как-то не очень идет с ним. Подскажите, есть ли ещё тому подобные библиотеки? С таким же функционалом.
PS: случайно не знаете туториалов хороших про ajax + change link систему? Заранее спасибо!
A: HTML5 History API уже сегодня и без ограничений.


text:
Q: How to determine viewholder is left or right in RecyclerView with StaggeredGridLayoutManager I have read a lot of similar articles but still didnt find answer how to know view holder is left or right in RecyclerView with StaggeredGridLayoutManager.
Situation:
I have RecyclerView, StaggeredGrid and want to do padding like
8 dp [left view] 8 dp [right view] 8 dp

So since I cannot do it in XML I have to add some margins -
For left view: left margin 8dp, right margin 4dp
For right view: left margin 4dp, right margin 8dp
Usually views are placed like this:
[0][1]
[2][3]
[4][5]

So simpliest solution was to try determine it by position:
override fun onBindViewHolder(ViewHolder holder, int position) {
    ...
        val params = holder.cardView.layoutParams as FrameLayout.LayoutParams

        if (position % 2 == 0) {
            params.leftMargin = pxFromDp(context, 8f).toInt()
            params.rightMargin = pxFromDp(context, 4f).toInt()
        }
        if (position % 2 == 1) {
            params.rightMargin = pxFromDp(context, 8f).toInt()
            params.leftMargin = pxFromDp(context, 4f).toInt()
        }
        params.bottomMargin = pxFromDp(context, 2f).toInt()
        params.topMargin = pxFromDp(context, 6f).toInt()

        holder.cardView.layoutParams = params
    ...
}

And that works, but if view 2 has less height than view 1 they are placed
[0][1]
[3][2]
[5][4]

So it does not work.
How can I know if there are left or right viewholder?

A: The only one option which really helped is using custom RecyclerView.ItemDecoration()
class StaggeredGridDecoration(val margin: Int) : RecyclerView.ItemDecoration() {
    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {
        super.getItemOffsets(outRect, view, parent, state)
        val position = parent.getChildAdapterPosition(view)
        val spanIndex = (view.layoutParams as StaggeredGridLayoutManager.LayoutParams).spanIndex
        val type = parent.adapter.getItemViewType(position)
        val halfOfMargin = margin / 2
        when (type) {
            1 -> {//use here 0 if you didnt create custom types
                var top = 0
                val bottom = pxFromDp(parent.context, margin.toFloat()).toInt()
                //for first 2 elements I need additional margin top
                if (position < 3) {
                    top = pxFromDp(parent.context, margin.toFloat()).toInt()
                }
                if (spanIndex == 0) {
                    //settings for left column
                    val left = pxFromDp(parent.context, margin.toFloat()).toInt()
                    val right = pxFromDp(parent.context, halfOfMargin.toFloat()).toInt()
                    setMargins(view, left, right, top, bottom)
                } else {
                    //settings for right column
                    val left = pxFromDp(parent.context, halfOfMargin.toFloat()).toInt()
                    val right = pxFromDp(parent.context, margin.toFloat()).toInt()
                    setMargins(view, left, right, top, bottom)
                }
            }
        }
    }

    private fun setMargins(view: View, left: Int, right: Int, top: Int, bottom: Int) {
        val cardView: CardView = view.findViewById(R.id.cardView)
        val params = cardView.layoutParams as FrameLayout.LayoutParams

        params.rightMargin = right
        params.leftMargin = left
        params.bottomMargin = bottom
        params.topMargin = top

        cardView.layoutParams = params
    }

}

And just added it
recyclerView.addItemDecoration(new StaggeredGridDecoration(8));


text:
Q: Docker : How to connect one container to another container via a network I have been researching docker with eureka, and I thought I understood how it works, but instead I have confused my self.
There is a container for the eureka server, and a container for the eureka client. The eureka client needs to be able to access the eureka server.
So what I did was find the IP address of the container which is this case is 172.20.0.2
so in my eureka client I have
defaultZone: http://172.20.0.2:8761/eureka/
I have connected both services to a network
"Containers": {
            "128e40236b9dc7e45cd046e34a0e2d5851a24c6da4d9510003615079c6c07a1e": {
                "Name": "bankhost",
                "EndpointID": "c5fa49a2d2d17232fa03b38835430e10eb5f40017d092b80aa624f1245bf6ec1",
                "MacAddress": "02:42:ac:14:00:03",
                "IPv4Address": "172.20.0.3/16",
                "IPv6Address": ""
            },
            "151bb21fbae965d782d0aca6fbae3cb7d24b19755bc1f01049a7e7579621e171": {
                "Name": "eurekahost",
                "EndpointID": "dd260aecffc3336b96ecfab3c7f3e36191a2672e67ca29390c359fb6b30feb2f",
                "MacAddress": "02:42:ac:14:00:02",
                "IPv4Address": "172.20.0.2/16",
                "IPv6Address": ""
            }
        },

When I run docker compose up for my client service, it runs but I its not register with Eureka
my application.yml for Eureka server
server:
  port=8761
spring:
  application: eureka-service

eureka:
  client:
    validateCertificates: false
    registerWithEureka: false
    fetchRegistry: false
    healthcheck:
      enabled: true
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

my server docker-compose.yml
version: '3'

services:
  eureka-server:
    image:  eurekaservice
    hostname: eureka-server
    container_name: eurekahost
    ports:
      - "8761:8761"
networks:
  default:
    external: true
    name: opspec

my application.yml for Eureka client
server:
  port=8080
spring:
  application: name=user-service

eureka:
  client:
    validateCertificates: true
    registerWithEureka: true
    fetchRegistry: true
    healthcheck:
      enabled: true
    serviceUrl:
      defaultZone: http://172.20.0.2:8761/eureka/

Client docker-compose
version: '3'

services:
  bank-server:
    image:  bankservice
    hostname: bank-server
    container_name: bankhost
    ports:
      - "8083:8080"
networks:
  default:
    external: true
    name: opspec

A: All I really need to know is what do I need to put in the my application.yml for Eureka client
for  defaultZone: http://XXXXXXXXX:8761/eureka/
All I need to know is what XXXXXXXX should be then I can work backwords.
There is the name of the container that contains the Eureka Server
The IP address of of the container that contains the Eureka Server
The service name of the image
And even  0.0.0.0


text:
Q: Align image to the right So I am very new to the whole coding thing and for this site I am building for class I want to align this photo I have at the bottom and move it to the right hand side of the page.

This is the code for the image and I tried to add put something like align=center, but that has presented no results. What is the proper code for moving my image to the right hand side of the page?

A: While you can use float:right that will mean you need to clear that float for anything after that element. You can use text-align on the parent element for a simpler option:

div {
  text-align: right;
}

An example of float messing up your layout without clearing it (note that this looks fine on Stackoverflow's small width, clicking full page will show the actual result).

img {
  float: right;
}

HELLO WORLD

HELLO WORLD

An example using flexbox

div {
  display: flex;
  justify-content: flex-end;
}

An example using float and clearing:

.clear::after {
  display: block;
  content: "";
  clear: both;
}

.float {
  float: right;
}

HELLO WORLD

A: You can do this in your HTML with  or in a seperate .css file with img {float: right;}


text:
Q: where can I learn about how do developer browser bookmarklets (language, framework, IDE, techniques etc)? where can I learn about how do developer browser bookmarklets (language, framework, IDE, techniques etc)?  Perhaps they are more of a Javascript development thing?
To give examples of what I'm talking about see:
http://www.evernote.com/about/download/web_clipper.php
and
http://readitlaterlist.com/bookmarklets/
Thanks

A: http://www.webreference.com/js/column35/ ?


text:
Q: Intents keep giving me a error even though the intents code is a C&P from a working bot I have tried this which is a copy of existing code from another one of my bots that works but when i run it i get a error saying "Intents is not defined"
const client = new Discord.Client({
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES,
    Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
    Intents.FLAGS.GUILD_PRESENCES,
  ],
})

Error:
ReferenceError: Intents is not defined

A: Simply, you should define the Intents by doing this:
const { Client, Intents } = require('discord.js')

Edit: You dont need to use Discord on discord.js v13 since its not needed, instead do it like this:
const { Client, Intents } = require('discord.js')

const client = new Client({
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES,
    Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
    Intents.FLAGS.GUILD_PRESENCES,
  ],
})


text:
Q: Read system call for C unix socket only returns and gets triggered when new line is detected. Is this the default behaviour? The sources on the Internet and books I've been reading seem to not specify exactly how the unix read system call behaves and when exactly it is triggered. They simply say that as soon as data are sent from the other end this data are available for consuming with the read and as soon as the EOF signal is received ( for example because of FIN ) the returns -1.
1) How come that the read in this server is ONLY triggered when data are sent that include an \n new line  character ?
2) Why does the read get stuck if \n is not detected ?
3) How come that if I try to reverse the situation ( the server sends data and the client reads it this situation doesn't occur ?
4) Has this behaviour something to do with some TCP/IP protocol stack settings on my OS that set different behaviours when read is applied to client or server respectively?
This is the server :
#define PORT 1026

int main(){

 int sockfd, connfd;
 unsigned int len;
 struct sockaddr_in servaddr, cli;

//SOCKET CREATION
sockfd = socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
if (sockfd == -1) {
        printf("socket creation failed...\n");
        exit(0);
    }

bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr =htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
//BIND
if ((bind(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr))) != 0) {
        printf("socket bind failed...\n");
        exit(0);
    }
//LISTEN
if ((listen(sockfd, 5)) != 0) {
        printf("Listen failed...\n");
        exit(0);
    }

for(;;){

len = sizeof(cli);

connfd = accept(sockfd, (struct sockaddr*)&cli, &len);

if (connfd < 0) {
        printf("server accept failed...\n");
        exit(0);
    }else{
        printf("New connection accepted !\n");
    }

char buffr;
int r;
while( (r=read(connfd,&buffr,sizeof(buffr))) > 0 ){
    if(buffr=='#') break;
    printf("%c",buffr);
};

close(connfd);
};

return 0;

}

And this is the client sending data :
#define PORT 1026

int main(){

int sockfd;
struct sockaddr_in servaddr, cli;
//CREATE SOCKET
sockfd = socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
    if (sockfd == -1) {
        printf("socket creation failed...\n");
        exit(0);
    }
bzero(&servaddr, sizeof(servaddr));

    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    servaddr.sin_port = htons(PORT);

if (connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) != 0) {
        printf("connection with the server failed...\n");
        //exit(0);
    }

char s[]="Hello World !#";  // DOESN'T WORK !
/*char s[]="Hello World !#\n"; DOES WORK*/
write(sockfd,s,sizeof(s));

close(sockfd);

return 0;

}

I'm using Mac OS and I've also checked on the wireshark traffic and it seems there are no problems with the packets. So, what's going on here ?

A: The problem is in how you print the characters, not about how you receive the data.
By default, when stdout (where printf writes) is connected to an interactive terminal, it will be line buffered. That means all output written to stdout will be buffered until either one of four things happens:

*

*The buffer is full

*The buffer is explicitly flushed (with fflush(stdout))

*There's a newline being written

*The process exits

If the data you receive doesn't contain a newline, then it will be kept in the buffer and not written to the actual terminal.
The solution is simple: Write a newline, or call fflush(stdout).


text:
Q: Changing localStorage Variables in Javascript through the Server I have a variable localStorage.lastUpdate which stores a timestamp such as 1332237161. I need to pass that timestamp to the server which im trying to do by the line below with:
listener.php?q="+localStorage.lastUpdate
I also have another variable, localStorage.numUpdates that should receive the number of updates back from the server. I am confused whether I can use the below code with xml to run commands. Can my server side php file do something of the following
echo "localStorage.numUpdates=".$currentCount.";";
echo "localStorage.lastUpdate=".time().";";
where it would take affect on my localStorage variables in the javascript portion?
function contactServer()
{
    if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest();}
    else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","listener.php?q="+localStorage.lastUpdate,true);
    xmlhttp.send();
}

Any information would be helpful, thanks!

A: That won't work (and don't use eval()!).
But you can just output JSON in your PHP script:
echo json_encode( array('lastUpdate' => time(), 'numUpdated' => $currentCount) );

And in your JavaScript code:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
  var result = JSON.parse(xmlhttp.responseText);
  localStorage["lastUpdate"] = result["lastUpdate"];
  localStorage["numUpdated"] = result["numUpdated"];
}


text:
Q: difference between assigning an int and an int literal to a byte ? byte b = 100 ;

compiles without any errors, but
int i = 100 ;
byte b = i ;

throws an error. Why? Even when assigning 100 directly to b, we are assigning an int literal. So why did I get an error?

A: byte b = 100 ;

Here 100 is a compile time constant. And hence can be assigned to the byte.
int i = 100 ;
// i = i + 100;  // It's allowed to add this statement later on,
                 // if `i` is not declared final. And hence, the next assignment
                 // will clearly fail at runtime. So, compiler saves you from it
byte b = i ;

Now in this case, since i is not declared final, so it is no more a compile time constant. And in that case, you can later on come and modify the value of i, in between the initialization of i, and assignment of i to byte, as in the above case. Which will certainly fail.
That is why compiler does not allow the assignment of i to byte type.
But, you can use an explicit casting for it to compile, which may of course crash at runtime. By doing an explicit cast, you tell the compiler that - "I know what I'm doing, just do it for me". So, it will not bother about runtime behaviour of that casting, and will trust you that you are not doing anything wrong.
So, either you can declare your int i as final, or you need to do the casting: -
int i = 100 ;    // replace 100 with 130, and you will be surprised that it works
byte b = (byte)i ;

So, when you use a value 130 and cast it to byte, you pass through the compiler, but will certainly crash at runtime. And this is the problem that the compiler was trying to avoid.

Now let's go back the first case: -
byte b = 128;

The above assignment will now fail to compile. Because even though the value 128 is a compile time constant, it is not big enough to fit in a byte, and that the compiler knows.

A: byte b=100 would compile because byte's range is from -128 to 127.
    int i = 100 ; byte b = 129 ;// would give a compiler error

A: i is not final and could have changed in the mean time.
Following would work:
final int i = 100;
byte b = i;


text:
Q: Infovis - Javascript test for graph.ready Hello I am using the infovis toolkit to draw an organisational chart,in order to accomplish this I need to draw a graph inside a graph node (I have this part working)
The problem is at what point in my code do I test that the parent graph is ready to be manipulated. I have tried testing when the canvas is ready, when the canvas is live, and also when the div label that I am writing the child graph to is ready however none of these seem to work and report
Cannot read property offsetWidth of null
which is because it cannot read the width of an element which does not yet exist and this is because even though the dom registers it the canvas hasn't finished rendering it yet.
Does anybody know in infovis to test for a graph being ready to be manipulated?
Thanks
scrineym

A: I figured out the answer, there isn't a definite way for testing the canvas is ready ,
however when creating the tree in infovis there is two functions onBeforeCompute and onAfterCompute
onAfterCompute is fired when the graph is finished loading, so you can place any necessary code in there and it will run when the graph is finished rendering.
Hope this helps !!


text:
Q: Confused on permutation cycles I am a bit confused on how to interpret permutation cycle notation. I am going by the Wolfram definition. My initial interpretation of $(431)(2)$ was "4 moves to position 3, 3 to position 1, 1 to 4, 2 remains in place". which would leave me at ${3, 2, 4, 1}$ which apparently is incorrect, since the solution is ${4, 2, 1, 3}$. So it would appear that the correct way to read $(431)(2)$ is "element 4 is replaced by 3, 3 by 1, 1 by 4, 2 remains in place".
I am also unclear on the definition of a cycle, which seems to mean a subset of elements which are permuted. Wolfram says, "any rotation of a given cycle specifies the same cycle", but I do not see why $(413)(2)$ cannot be considered a cycle of $(431)(2), (314)(2), (143)(2), (2)(431), (2)(314), (2)(143)$. The elements lookthe same, only permuted.

A: The notation $(431)(2)$ means the function from $\{1,2,3,4\}$ to itself that maps things as follows: $4\mapsto3$; $3\mapsto 1$; $1\mapsto4$; and $2\mapsto2$.  Notice that this looks a lot like your description, except that I've avoided "position" and "moves".  Despite the terminology, a permutation is, officially, a function, not a bunch of things moving around.
Nevertheless, people often describe permutations by writing things in certain positions; there are several conventions for how to do this.  The clearest is the "two-line" notation, where you write the inputs to the permutation on a horizontal line and write the corresponding outputs directly below them.  Thus, the function described above with $\mapsto$ could be written as $\pmatrix{4&3&1&2\\3&1&4&2}$.  Usually, though, when people use two-line notation, they arrange the top line in increasing order (assuming that the entities being permuted are real numbers), so the same permutation would be written $\pmatrix{1&2&3&4\\4&2&1&3}$.  This contains exactly the same information as the previous two-line notation; notice that the columns are the same (and are the same as the $\mapsto$ items in the preceding paragraph).  You could write a lot of other two-line presentations of the same permutation; list $1,2,3,4$ in the top row in any order you like, and fill in, beneath each entry, the number that the permutation maps it to.
When people decide to write the top line in increasing order, they can save some space by not writing that line at all, relying on the reader to mentally fill it in.  So these people just write the bottom line, which in this case is $4,2,1,3$.  But for this to work, it's absolutely essential to agree that the unwritten top line is understood to be the same numbers in increasing order.  This convention accounts for "the answer" that you cited in your question.
In some alternative world, people could have decided to always write two-line notation with the bottom line in increasing order.  So the permutation in your example would be $\pmatrix{3&2&4&1\\1&2&3&4}$.  And then they could have decided to save space by writing only the top line, relying on the reader to mentally fill in the bottom line in increasing order.  So they would write your example as $3,2,4,1$, which is the answer you proposed.  So you'd be right in this alternative world; unfortunately, you're in our world, where people use the conventions of the preceding paragraph, not this one.
If you follow the path from your original cycle notation $(431)(2)$ to the $\mapsto$ description, to the two-line notation with increasing top row, to the one-line notation, you'll find the following (and three more facts just like it).  The fact that $4\mapsto3$ in your permutation means that $4$ is directly above $3$ in any version of two-line notation (no matter how you arrange the top row), which means in turn that $4$ is above $3$ in column $4$ of two-line notation when you arrange the top row in increasing order, which means that $3$ is in position $4$ of the one-line notation.  (In the alternative world, the two-line notation would have $4$ above $3$ in column $3$, so the one-line notation would have $4$ in position $3$, as you originally expected.)

A: Your initial interpretation of $(123)$ would seem to suggest that it sends $1$ to the middleman $2$ and then to the final destination of $3$. This would make the "middleman" $2$ completely superfluous; what's the point of having a midway station if it doesn't have any consequence at all?
No, $(123)$ means that $1$ ends up at $2$. It does not go any further. And $2$ ends up at $3$. And $3$ ends up at $1$. That is, if $\sigma=(123)$, then $\sigma(1)=2$, $\sigma(2)=3$ and $\sigma(3)=1$. Why is this called a "cycle" you may ask? One thing to notice is that if you start in any particular place, say $1$, then upon repeated application we get $\sigma^0(1)=1$, $\sigma^1(1)=2$, $\sigma^2(1)=\sigma(\sigma(1))=\sigma(2)=3$, and then back to $\sigma^3(1)=\sigma(\sigma^2(1))=\sigma(3)=1$ back where we began. We do go on a "round trip" through the numbers seen in the cycle notation, in the order they're listed, upon repeated application of $\sigma$.
An equivalent way of thinking about this is as follows: if we list out the numbers from the cycle notation on a circle in the order they appear, applying $\sigma$ to the numbers is the same as rotating.
Now, the numbers appearing in the notation $(132)$ are the same as those appearing in $(123)$, however they do not denote the same permutation. The first takes $1$ to $3$, whereas the second takes $1$ to $2$, so they cannot be the same. Yet, $(231)$ also looks different than $(123)$, and we can check that they represent exactly the same function (permutation) of the set $\{1,2,3\}$: each sends $1$ to $2$ and sends $2$ to $3$ and sends $3$ to $1$, so the notations $(123)$ and $(231)$ both specify the same exact permutation. Similarly, $(312)$ is another way of specifying this same permutation.
In general, if you take the numbers that appear in a cycle's cycle notation and, well, cycle them as they appear, you will not be changing the permutation that is being denoted. However if you permute the numbers that appear in a cycle notation arbitrarily you will not, in general, end up with the same permutation you started with. We already observed $(123)\ne(132)$ for instance.


text:
Q: Problem involving many squares and several variables. Let $a, b, c, d, e, f$ be nonnegative real numbers such that

*

*$a^2 + b^2 + c^2 + d^2 + e^2 + f^2 = 6$.

*$ab + cd + ef = 3$.

*What is the maximum value of $a+b+c+d+e+f$ ?.

I was thinking about somehow manipulating the numbers to get
$\left(a + b + c + d + e + f\right)^{2}$, but I don't really know what to do.

A: Since this is labeled pre-calculus here is a solution not involving calculus:
\begin{eqnarray}
(a+b)^2+(c+d)^2+(e+f)^2&=&a^2+2ab+b^2+c^2+2cd+d^2+e^2+2ef+f^2\\
&=&6+2(3)\\&=&12
\end{eqnarray}
Because of symmetry the maximum will occur when each of $(a+b),\,(c+d)$ and $(e+f)$ equals $2$ so the maximum value of $a+b+c+d+e+f$ is $6$.
Addendum: The symmetry argument.
Suppose we have $p>0$ and
$$ p^2+p^2+p^2=3p^2$$
and for $\alpha\beta\gamma\ne0$
$$ (p+\alpha)^2+(p+\beta)^2+(p+\gamma)^2=3p^2\tag{1}$$
Then we will show that $$ (p+\alpha)+(p+\beta)+(p+\gamma)< p+p+p$$
With a bit of algebra equation (1) becomes$$ \alpha+\beta+\gamma=-\dfrac{\alpha^2+\beta^2+\gamma^2}{2p} $$
So we have that
 $$ (p+\alpha)+(p+\beta)+(p+\gamma)=3p-\dfrac{\alpha^2+\beta^2+\gamma^2}{2p}<p+p+p $$

A: First we can set up the problem as $$\max_{a, b, \dots, f} a+ b +c + d+ e + f $$
s.t. $$ a^2 + b^2 + c^2 + d^2 + e^2 +  f^2 + ab + cd + ef = 9$$ and then form the Lagrangian:$$\mathcal{L} = a+ b +c + d+ e + f - \lambda(a^2 + b^2 + c^2 + d^2 + e^2 +  f^2 + ab + cd + ef - 9)$$
Which yields the following first order conditions:
$$1 = \lambda(2a + b)$$$$1 = \lambda(2b + a)$$$$1 = \lambda(2c + d)$$$$1 = \lambda(2d + c)$$$$1 = \lambda(2e + f)$$$$1 = \lambda(2f + e)$$
Taking the first two as an example and dividing through yields $$1 = \frac{2a+b}{2b+a} \Rightarrow 2b + a = 2a + b\Rightarrow b = a$$
The same procedure for the others yeilds $c=d$ and $e=f$.
Now, since all the variables are nonnegative and $ab + cd + ef = 3$, it must be that $a=b=c=d=e=f=1$ must be the max. This is the only way to get $x^2 + y^2 + z^2 = 3$ for any nonnegative variables $x,y,z$

A: I would formulate the problem as follows:
$\max_{a,b, \cdots, f} a+b+c+d+e+f$
s.t.
$a^2+b^2+c^2+d^2+e^2+f^2 = 6$
and
$ab+cd+ef = 3$
Then form the Lagrangian $\mathcal{L} = a+b+c+d+e+f -\lambda_1(a^2+b^2+c^2+d^2+e^2+f^2 - 6) -\lambda_2(ab+cd+ef - 3)$
Next set $\frac{\partial \mathcal{L}}{\partial a} = \frac{\partial \mathcal{L}}{\partial b} = \cdots = \frac{\partial \mathcal{L}}{\partial f} = 0$
You will get three identical pairs of equations: one for $a,b$, one for $c,d$ and one for $e,f$.
Just solve one pair (say for $a,b$) and conclude that $a=b$
Then $a=b=c=d=e=f$ follows and the maximum value is $6$

A: Here are provided both a Calculus of Variations and a Pre-calculus approach.

We want to maximize
$$
a+b+c+d+e+f\tag{1}
$$
under the constraint that
$$
a^2+b^2+c^2+d^2+e^2+f^2=6\tag{2}
$$
and
$$
ab+cd+ef=3\tag{3}
$$
Calculus of Variations Approach
We want
$$
\delta a+\delta b+\delta c+\delta d+\delta e+\delta f=0\tag{4}
$$
for every variation so that
$$
a\,\delta a+b\,\delta b+c\,\delta c+d\,\delta d+e\,\delta e+f\,\delta f=0\tag{5}
$$
and
$$
a\,\delta b+b\,\delta a+c\,\delta d+d\,\delta c+e\,\delta f+f\,\delta e=0\tag{6}
$$
Linearity says that we need $\lambda$ and $\mu$ so that
$$
\lambda a+\mu b=\lambda b+\mu a=\lambda c+\mu d=\lambda d+\mu c=\lambda e+\mu f=\lambda f+\mu e\tag{7}
$$
If $\lambda=\mu$, then we need only have
$$
a+b=c+d=e+f\tag{8}
$$
If $\lambda\ne\mu$, then we need
$$
a=b=c=d=e=f\tag{9}
$$
Since $(9)\implies(8)$, we will only assume $(8)$. Add twice $(3)$ to $(2)$ and we get that
$$
(a+b)^2+(c+d)^2+(e+f)^2=12\tag{10}
$$
and since $(8)$ says that each summand in $(10)$ is equal, we get
$$
|a+b|=|c+d|=|e+f|=2\tag{11}
$$
Trying all sign combinations of $(11)$, we get the maximum of $(1)$ to be
$$
\bbox[5px,border:2px solid #C0A000]{a+b+c+d+e+f=6}\tag{12}
$$

Pre-calculus Approach
If we subtract twice $(3)$ from $(2)$, we get
$$
(a-b)^2+(c-d)^2+(e-f)^2=0\tag{13}
$$
which implies that $a=b$, $c=d$, and $e=f$. Thus, $(13)$ reduces the problem to maximizing
$$
a+c+e\tag{14}
$$
under the constraint that
$$
a^2+c^2+e^2=3\tag{15}
$$
Furthermore,
$$
\begin{align}
(a+c+e)^2
&=a^2+c^2+e^2+2ac+2ce+2ea\\
&=3a^2+3c^2+3e^2-(a-c)^2-(c-e)^2-(e-a)^2\\[3pt]
&\le9\tag{16}
\end{align}
$$
Since $a=c=e=1$ gives $a^2+c^2+e^2=3$ and $(a+c+e)^2=9$, we get the maximum of $(14)$ to be
$$
a+c+e=3\tag{17}
$$
and, because of $(13)$, the maximum of $(1)$ to be
$$
\bbox[5px,border:2px solid #C0A000]{a+b+c+d+e+f=6}\tag{18}
$$


text:
Q: How do i fix shiny deployment issue in browser when running locally? I am running into issues deploying my shiny application. In R Studio, it states that the application has been deployed successfully, as per the image below.
Successful deployment message
However, I get "An error has occurred. The application failed to start. Contact the author for more information" when opening the application in the browser (chrome and safari).
Error in browser version of application
It also states the application is running on my shiny account.
enter image description here
Does anyone have any recommendations to what problem is occurring here that prevents the shiny app from being run in a browser? The app runs locally without any issues too.
I have all packages installed and up to date and the file directory is correct. I am not running on an SSL network either.
Thanks in advance.


text:
Q: Linux Docker container on Windows host: Device Mapper "snapshot" target is missing Take a look at this:
C:\> docker run --rm -it --privileged ubuntu:focal
root@4c806ae5de55:/# apt-get update
...
root@4c806ae5de55:/# apt-get install dmsetup
...
root@4c806ae5de55:/# dmsetup targets
verity           v1.7.0
thin-pool        v1.22.0
thin             v1.22.0
raid             v1.15.1
crypt            v1.22.0
striped          v1.6.0
linear           v1.4.0
error            v1.5.0

Conspicuous by its absence is the snapshot target that I'm trying to use. It exists on a real Ubuntu install, but not here. How do I make it come back?
I'm running Docker Desktop on Windows, which appears to be configured to use the WSL 2 backend.
Edit: I presume, given the way Docker works, this has nothing to do with what container I'm trying to run, and everything to do with what Linux kernel WSL is using. From what I can tell, you can install multiple WSL distributions, but they all use the same Microsoft custom kernel. Presumably I would have to somehow build a whole custom kernel, or at least build dm_snapshot.ko suitable for loading into the WSL kernel. (?)


text:
Q: Why am I getting an attribute error with Pygame when I try to call a method on my targets? I am creating a a simple shooting game with Pygame. I want my targets to move around the screen rather than be static, but can't seem to be able to do so. The code I am using flags up "AttributeError: 'Group' object has no attribute 'move'", but I don't understand why. The relevant sections are as below:
class Target(pygame.sprite.Sprite):
    leftwards = False
    rightwards = False
    upwards = False
    downwards = False
    new_x = 0
    new_y = 0
    def __init__(self, pos_x, pos_y):
        super().__init__()
        self.image = pygame.image.load("al.png").convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.center = [pos_x, pos_y]
        Target.new_x = pos_x
        Target.new_y = pos_y
        if pos_x > screen_width/2:
            Target.leftwards = True
        else:
            Target.rightwards = True
        if pos_y > screen_height/2:
            Target.upwards = True
        else:
            Target.downwards = True
    def move(self):
        if Target.new_x == screen_width:
            Target.leftwards = True
            Target.rightwards = False
        if Target.new_x == 0:
            Target.rightwards = True
            Target.leftwards = False
        if Target.new_y == screen_height:
            Target.upwards = True
            Target.downwards = False
        if Target.new_y == 0:
            Target.downwards = True
            Target.downwards = False
        if Target.leftwards:
            Target.new_x -= 20
        if Target.rightwards:
            Target.new_x += 20
        if Target.upwards:
            Target.new_y -= 15
        if Target.downwards:
            Target.new_y += 15
        self.rect.center = [Target.new_x, Target.new_y]

And:

target_group = pygame.sprite.Group()
for target in range(20):
    new_target = Target(random.randrange(0, screen_width), random.randrange(0, screen_height))
    target_group.add(new_target)

Running = True
while Running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            crosshair.shoot()

    pygame.display.flip()
    screen.blit(background, (0, 0))
    target_group.draw(screen)
    target_group.move()
    score = len(target_group.sprites())
    stats(score)
    crosshair_group.draw(screen)
    crosshair_group.update()
    clock.tick(60)

Have I gone about it the completely wrong way?