text:
Q: Java program not running while it should For a project in school we got a simple simulator for a parking lot, and it is our job to add features to this simulator. I'm trying to add a GUI to the simulator and so that you can fill in your values and that the simulation bases its simulation based upon those values. But i first made a simple button to go from 1 frame to the other but when i run the Frame1 file with the following code:
JButton btnSubmit = new JButton("Submit");
        btnSubmit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                frame.dispose();
                 Simulator mysimulator = new Simulator();
                mysimulator.run();
                }

it doesn't load, it just gives me a blank window.
the view of the simulator is made in the following code:
    //package Parkeersimulator;

import javax.swing.*;
import java.awt.*;

public class SimulatorView extends JFrame {
    public JFrame frame;
    private CarParkView carParkView;
    private int numberOfFloors;
    private int numberOfRows;
    private int numberOfPlaces;
    private int numberOfOpenSpots;
    private Car[][][] cars;

    public SimulatorView(int numberOfFloors, int numberOfRows, int numberOfPlaces) {
        this.numberOfFloors = numberOfFloors;
        this.numberOfRows = numberOfRows;
        this.numberOfPlaces = numberOfPlaces;
        this.numberOfOpenSpots =numberOfFloors*numberOfRows*numberOfPlaces;
        cars = new Car[numberOfFloors][numberOfRows][numberOfPlaces];

        carParkView = new CarParkView();

        Container contentPane = getContentPane();
        contentPane.add(carParkView, BorderLayout.CENTER);
        pack();
        setVisible(true);

        updateView();

                }

    public void updateView() {
        carParkView.updateView();
    }

    public int getNumberOfFloors() {
        return numberOfFloors;
    }

    public int getNumberOfRows() {
        return numberOfRows;
    }

    public int getNumberOfPlaces() {
        return numberOfPlaces;
    }

    public int getNumberOfOpenSpots(){
        return numberOfOpenSpots;
    }

    public Car getCarAt(Location location) {
        if (!locationIsValid(location)) {
            return null;
        }
        return cars[location.getFloor()][location.getRow()][location.getPlace()];
    }

    public boolean setCarAt(Location location, Car car) {
        if (!locationIsValid(location)) {
            return false;
        }
        Car oldCar = getCarAt(location);
        if (oldCar == null) {
            cars[location.getFloor()][location.getRow()][location.getPlace()] = car;
            car.setLocation(location);
            numberOfOpenSpots--;
            return true;
        }
        return false;
    }

    public Car removeCarAt(Location location) {
        if (!locationIsValid(location)) {
            return null;
        }
        Car car = getCarAt(location);
        if (car == null) {
            return null;
        }
        cars[location.getFloor()][location.getRow()][location.getPlace()] = null;
        car.setLocation(null);
        numberOfOpenSpots++;
        return car;
    }

    public Location getFirstFreeLocation() {
        for (int floor = 0; floor < getNumberOfFloors(); floor++) {
            for (int row = 0; row < getNumberOfRows(); row++) {
                for (int place = 0; place < getNumberOfPlaces(); place++) {
                    Location location = new Location(floor, row, place);
                    if (getCarAt(location) == null) {
                        return location;
                    }
                }
            }
        }
        return null;
    }

    public Car getFirstLeavingCar() {
        for (int floor = 0; floor < getNumberOfFloors(); floor++) {
            for (int row = 0; row < getNumberOfRows(); row++) {
                for (int place = 0; place < getNumberOfPlaces(); place++) {
                    Location location = new Location(floor, row, place);
                    Car car = getCarAt(location);
                    if (car != null && car.getMinutesLeft() <= 0 && !car.getIsPaying()) {
                        return car;
                    }
                }
            }
        }
        return null;
    }

    public void tick() {
        for (int floor = 0; floor < getNumberOfFloors(); floor++) {
            for (int row = 0; row < getNumberOfRows(); row++) {
                for (int place = 0; place < getNumberOfPlaces(); place++) {
                    Location location = new Location(floor, row, place);
                    Car car = getCarAt(location);
                    if (car != null) {
                        car.tick();
                    }
                }
            }
        }
    }

    private boolean locationIsValid(Location location) {
        int floor = location.getFloor();
        int row = location.getRow();
        int place = location.getPlace();
        if (floor < 0 || floor >= numberOfFloors || row < 0 || row > numberOfRows || place < 0 || place > numberOfPlaces) {
            return false;
        }
        return true;
    }

    private class CarParkView extends JPanel {

        private Dimension size;
        private Image carParkImage;

        /**
         * Constructor for objects of class CarPark
         */
        public CarParkView() {
            size = new Dimension(0, 0);
        }

        /**
         * Overridden. Tell the GUI manager how big we would like to be.
         */
        public Dimension getPreferredSize() {
            return new Dimension(800, 500);
        }

        /**
         * Overriden. The car park view component needs to be redisplayed. Copy the
         * internal image to screen.
         */
        public void paintComponent(Graphics g) {
            if (carParkImage == null) {
                return;
            }

            Dimension currentSize = getSize();
            if (size.equals(currentSize)) {
                g.drawImage(carParkImage, 0, 0, null);
            }
            else {
                // Rescale the previous image.
                g.drawImage(carParkImage, 0, 0, currentSize.width, currentSize.height, null);
            }
        }

        public void updateView() {
            // Create a new car park image if the size has changed.
            if (!size.equals(getSize())) {
                size = getSize();
                carParkImage = createImage(size.width, size.height);
            }
            Graphics graphics = carParkImage.getGraphics();
            for(int floor = 0; floor < getNumberOfFloors(); floor++) {
                for(int row = 0; row < getNumberOfRows(); row++) {
                    for(int place = 0; place < getNumberOfPlaces(); place++) {
                        Location location = new Location(floor, row, place);
                        Car car = getCarAt(location);
                        Color color = car == null ? Color.white : car.getColor();
                        drawPlace(graphics, location, color);
                    }
                }
            }
            repaint();
        }

        /**
         * Paint a place on this car park view in a given color.
         */
        private void drawPlace(Graphics graphics, Location location, Color color) {
            graphics.setColor(color);
            graphics.fillRect(
                    location.getFloor() * 260 + (1 + (int)Math.floor(location.getRow() * 0.5)) * 75 + (location.getRow() % 2) * 20,
                    60 + location.getPlace() * 10,
                    20 - 1,
                    10 - 1); // TODO use dynamic size or constants
        }
    }

}

and the simultion self is made in the following code:
    //package Parkeersimulator;

import java.util.Random;
import javax.swing.*;

public class Simulator {

    private static final String AD_HOC = "1";
    private static final String PASS = "2";

    private CarQueue entranceCarQueue;
    private CarQueue entrancePassQueue;
    private CarQueue paymentCarQueue;
    private CarQueue exitCarQueue;
    private SimulatorView simulatorView;

    private int day = 0;
    private int hour = 0;
    private int minute = 0;

    private int tickPause = 100;

    int weekDayArrivals= 100; // average number of arriving cars per hour
    int weekendArrivals = 200; // average number of arriving cars per hour
    int weekDayPassArrivals= 50; // average number of arriving cars per hour
    int weekendPassArrivals = 5; // average number of arriving cars per hour

    int enterSpeed = 3; // number of cars that can enter per minute
    int paymentSpeed = 7; // number of cars that can pay per minute
    int exitSpeed = 5; // number of cars that can leave per minute

    public static void main(String[] args){
        Simulator mySimulator = new  Simulator();
        mySimulator.run();
            }

    public Simulator() {
        entranceCarQueue = new CarQueue();
        entrancePassQueue = new CarQueue();
        paymentCarQueue = new CarQueue();
        exitCarQueue = new CarQueue();
        simulatorView = new SimulatorView(3, 6, 30);
    }

    public void run() {
        for (int i = 0; i < 10000; i++) {
            tick();
        }
    }

    private void tick() {
        advanceTime();
        handleExit();
        updateViews();
        // Pause.
        try {
            Thread.sleep(tickPause);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        handleEntrance();
    }

    private void advanceTime(){
        // Advance the time by one minute.
        minute++;
        while (minute > 59) {
            minute -= 60;
            hour++;
        }
        while (hour > 23) {
            hour -= 24;
            day++;
        }
        while (day > 6) {
            day -= 7;
        }

    }

    private void handleEntrance(){
        carsArriving();
        carsEntering(entrancePassQueue);
        carsEntering(entranceCarQueue);
    }

    private void handleExit(){
        carsReadyToLeave();
        carsPaying();
        carsLeaving();
    }

    private void updateViews(){
        simulatorView.tick();
        // Update the car park view.
        simulatorView.updateView();
    }

    private void carsArriving(){
        int numberOfCars=getNumberOfCars(weekDayArrivals, weekendArrivals);
        addArrivingCars(numberOfCars, AD_HOC);
        numberOfCars=getNumberOfCars(weekDayPassArrivals, weekendPassArrivals);
        addArrivingCars(numberOfCars, PASS);
    }

    private void carsEntering(CarQueue queue){
        int i=0;
        // Remove car from the front of the queue and assign to a parking space.
        while (queue.carsInQueue()>0 &&
                simulatorView.getNumberOfOpenSpots()>0 &&
                i<enterSpeed) {
            Car car = queue.removeCar();
            Location freeLocation = simulatorView.getFirstFreeLocation();
            simulatorView.setCarAt(freeLocation, car);
            i++;
        }
    }

    private void carsReadyToLeave(){
        // Add leaving cars to the payment queue.
        Car car = simulatorView.getFirstLeavingCar();
        while (car!=null) {
            if (car.getHasToPay()){
                car.setIsPaying(true);
                paymentCarQueue.addCar(car);
            }
            else {
                carLeavesSpot(car);
            }
            car = simulatorView.getFirstLeavingCar();
        }
    }

    private void carsPaying(){
        // Let cars pay.
        int i=0;
        while (paymentCarQueue.carsInQueue()>0 && i < paymentSpeed){
            Car car = paymentCarQueue.removeCar();
            // TODO Handle payment.
            carLeavesSpot(car);
            i++;
        }
    }

    private void carsLeaving(){
        // Let cars leave.
        int i=0;
        while (exitCarQueue.carsInQueue()>0 && i < exitSpeed){
            exitCarQueue.removeCar();
            i++;
        }
    }

    private int getNumberOfCars(int weekDay, int weekend){
        Random random = new Random();

        // Get the average number of cars that arrive per hour.
        int averageNumberOfCarsPerHour = day < 5
                ? weekDay
                : weekend;

        // Calculate the number of cars that arrive this minute.
        double standardDeviation = averageNumberOfCarsPerHour * 0.3;
        double numberOfCarsPerHour = averageNumberOfCarsPerHour + random.nextGaussian() * standardDeviation;
        return (int)Math.round(numberOfCarsPerHour / 60);
    }

    private void addArrivingCars(int numberOfCars, String type){
        // Add the cars to the back of the queue.
        switch(type) {
        case AD_HOC:
            for (int i = 0; i < numberOfCars; i++) {
                entranceCarQueue.addCar(new AdHocCar());
            }
            break;
        case PASS:
            for (int i = 0; i < numberOfCars; i++) {
                entrancePassQueue.addCar(new ParkingPassCar());
            }
            break;
        }
    }

    private void carLeavesSpot(Car car){
        simulatorView.removeCarAt(car.getLocation());
        exitCarQueue.addCar(car);
    }

}

please do note that i only just began programming and i have little to no knowledge at all.

A: You need a add the button to a panel.
 JPanel panel = new JPanel();
 JButton btnSubmit = new JButton("Submit");
 Container content = this.getContentPane(); // Get the content pane
 content.add(panel, BorderLayout.CENTER);
 content.add(btnSubmit, BorderLayout.SOUTH);
 setVisible(true); // Display the window


text: Q: 2 сетевые карты, реализация 2х подключений одновременно на компьютере с виндой 2 сетевые карты. 1 на интернет, 2  подключение к рабочему серверу FTP, так же через 2 работают программы типа вкс. интернет с динамическим IP, ни какие настройки не прописаны

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating anonymous function handle dynamically in MATLAB using numeric matrices as sources I'm kinda lost in a problem where I need to (dynamically) create an anonymous function handle from huge matrices and 192 variables.
I'll try to give you an (easier) example of what I have to do and what I have in mind to achieve it (but without a clue how to do it in MATLAB ):
syms x1 x2 x3 x4 real
X = [x1 x2 x3 x4]'
F = [1 2 3 4; 1 2 3 4]
Y = [9 8]'
my_fun = (F*X + Y)' * (F*X + Y)
%solve my_fun to min for X

So, this is what I want to have (my_fun).
The thing is, that there will be x1 to x192, F will be like 10000x192 and Y like 10000x1. Using symbolic tb is very slow and since I later have to calculate the Hessian it is superdupser slow.
I now found a way to numerically calculate the Hessian (from MATLAB file exchange) but have no clue, how to calculate my_fun as an (anonymous) function. I simply lack the skills of MATLAB + function handles. I already tried several things.
So, I think what I need to know is how to create X dynamically with x(1) to x(192) and then calculate my_fun = @(x) ...
EDIT: Thanks for the edit :)
The only thing that I can think of to solve this is by using a couple of loops to create the anonymous function handle as a string and then use str2fun, but I feel like this isn't the easiest way to get what I need :)

A: First of all: Delete your first two lines containing stuff from the symbolic toolbox. You won't need any of this.
You have two options:
Using a function-file:
These would be the contents of the file my_fun.m:
function result = my_fun(X)
   F = [1 2 3 4; 1 2 3 4];
   Y = [9 8]';
   result = (F*X + Y)' * (F*X + Y);

You would then pass this function as an argument using @my_fun.
Using an anonymous function
You could define a function handle using an anonymous function using:
F = [1 2 3 4; 1 2 3 4];
Y = [9 8]';
my_fun = @(X) (F*X + Y)' * (F*X + Y);

This will capture the current contents of your local variables Fand Y. So changing F or Y afterwards won't change my_fun.
In contrast to the above version you will pass this using my_fun.


text:
Q: Json.NET serializes enum as string even with default settings I am using Json.NET 7.0.1.
The documentation says that

Enum [is serialized as] Integer (can be the enum value name with StringEnumConverter)

In my Global.asax.cs, I specify the default settings as follows:
JsonConvert.DefaultSettings = (() =>
{
    var settings = new JsonSerializerSettings();
    settings.Converters.Add(new StringEnumConverter());
    return settings;
});

However, in certain situations, I want Enums to be serialized as integers, for instance when I build a JSON which is to be stored in the database.
Here is how I went about it:
public class JsonSerializedType<T> : IUserType where T : class
{
    private static readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings();

    public void NullSafeSet(IDbCommand cmd, object value, int index)
    {
        cmd.Parameters[index].Value = JsonConvert.SerializeObject(value as T, serializerSettings);
    }
}

However, even in this case Enums are serialized as strings. I checked that serializerSettings has no Converters and its ContractResolver is null.
Why is that so?

A: This is happening because JsonConvert.SerializeObject applies the incoming settings on top of the default settings, by internally calling JsonSerializer.CreateDefault(JsonSerializerSettings settings).  I don't know if/where this behavior is documented, but it's visible in the source code.  Thus the default list of converters will be used in addition to the empty list of locally specified converters, meaning the default StringEnumConverter will get used.
You have a couple options to work around this:

*

*Construct the JsonSerializer yourself without using the default settings:
public static class JsonExtensions
{
    public static string SerializeObjectNoDefaultSettings(object value, Formatting formatting, JsonSerializerSettings settings)
    {
        var jsonSerializer = JsonSerializer.Create(settings);
        jsonSerializer.Formatting = formatting;

        StringBuilder sb = new StringBuilder(256);
        StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
        using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
        {
            jsonWriter.Formatting = jsonSerializer.Formatting;
            jsonSerializer.Serialize(jsonWriter, value);
        }

        return sw.ToString();
    }
}

And then use it like:
var json = JsonExtensions.SerializeObjectNoDefaultSettings(value, Formatting.None, new JsonSerializerSettings());

*Supersede the default StringEnumConverter with one that does not serialize enums as strings, for instance:
public class IntegerEnumConverter : StringEnumConverter
{
    public override bool CanRead { get { return false; } }

    public override bool CanWrite { get { return false; } }
}

And then use it like:
var json = JsonConvert.SerializeObject(value, Formatting.None, new JsonSerializerSettings { Converters = new JsonConverter[] { new IntegerEnumConverter() } });

The locally specified converter will be picked up in preference to the default converter.
Temporarily nulling out the JsonConvert.DefaultSettings would be a bad idea since it would not be thread-safe.

A: REASON
The behavior we see here is by design, passed settings in JsonConvert methods are getting merged with provided DefaultSettings, Here is a small part of Json.Net source code from JsonSerializer class to demystify the situation.
 private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings)
    {
        if (!CollectionUtils.IsNullOrEmpty(settings.Converters))
        {
            // insert settings converters at the beginning so they take precedence
            // if user wants to remove one of the default converters they will have to do it manually
            for (int i = 0; i < settings.Converters.Count; i++)
            {
                serializer.Converters.Insert(i, settings.Converters[i]);
            }
        }

As we can see Converters are merged with provided Default ones albeit with higher precedence.
Solution
We can take advantage of higher precedence of recently merged converters and prevent StringEnumConverter conversion.
class PreventStringEnumConverter : StringEnumConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var type = value.GetType();
        var undertype = Enum.GetUnderlyingType(type);
        var converted=Convert.ChangeType(value, undertype);
        writer.WriteValue(converted);
    }
}

and the usage would be like:
var json = JsonConvert.SerializeObject(obj,
        new JsonSerializerSettings
        {
            Converters = new List<JsonConverter> {new PreventStringEnumConverter()}
        });


text:
Q: I made wkhtmltopdf to work on my local machine using ASP.NET, Is my code safe to run on server Code convert the current HTML page into PDF and show it to the user. I have never worked with wkhtmltopdf before and I am more concerned about security. Is it safe to run it on the server? What should I do to make it more secure?
string args = string.Format("\"{0}\" - ", Request.Url.AbsoluteUri);
    var startInfo = new ProcessStartInfo(Server.MapPath("bin\\wkhtmltopdf.exe"), args)
    {
        UseShellExecute = false,
        CreateNoWindow = true,
        RedirectStandardOutput = true

    };
    var proc = new Process { StartInfo = startInfo };
    proc.Start();

    string output = proc.StandardOutput.ReadToEnd();
    byte[] buffer = proc.StandardOutput.CurrentEncoding.GetBytes(output);
    proc.WaitForExit();
    proc.Close();
    Response.ContentType = "application/pdf";
    Response.BinaryWrite(buffer);
    Response.End();

I tried to us iTextSharp, but I had issues with it when using Arabic language.
Please suggest if I can do it in a better way.
My requirement is simple, I want to pass a URL to a function which will convert the HTML page into PDF and show it as a download to the user.

A: well, I am not sure if the arguments can run, just for the test try this  " | cmd.exe" to see if anything opens on server, or you can try for test the " | del . /Q" hmm, maybe not the del, you must have made backup OR, use a virtual pc, but how to test if not use anything like this ?
The pipeline command | is used on command to execute a second in the row command on the system, or to connect two commands together.
Normally the arguments not rus, so the next security is the .exe him self, what this .exe can do and what not.
To make it secure in general you must have give the correct permission to your asp.net application, and isolate in his directory.


text:
Q: Why L={wxw^R| w, x belongs to {a,b}^+ } is a regular language Using pumping lemma, we can easily prove that the language L1 = {WcW^R|W ∈ {a,b}*} is not a regular language. (the alphabet is {a,b,c}; W^R represents the reverse string W)
However, If we replace character c with "x"(x ∈ {a,b}+), say, L2 = {WxW^R| x, W ∈ {a,b}^+}, then L2 is a regular language.
Could you give me some ideas?

A: Any string in the language with |W| > 1 can be interpreted as a string in the language where |W| = 1. Thus, a string is in the language if it begins and ends with the same symbol. There are two symbols: a and b. So that language is equivalent to the language a(a+b)(a+b)*a + b(a+b)(a+b)*b. To prove this, you should formalize the argument that "if y is in WxW, then y is in a(a+b)(a+b)*a + b(a+b)(a+b)*b; and if y is in a(a+b)(a+b)*a + b(a+b)(a+b)*b, then y is in WxW".
It doesn't work in the other case since c is a fixed symbol, and can't include all but the characters on the ends. As soon as you bound the length of "x" in your example, the language becomes non-regular.

A: The question says W ∈ {a,b}^+ , so a^n(a+b)a^n should be in the language L2. Now there is no such DFA that will accept the string a^n(a+b)a^n because, after accepting n number of a and (a+b)^+, there is no way for the dfa to remember exactly how many a it accepted in the begining, so L2 should not be regular.........But every where i search for this answer it says it is regular.....this bugs me

A:
If we replace character c with x where (x ∈ {a,b}+), say, L2 = {WXWR| x, W ∈ {a,b}+}, then L2 is a regular language.

Yes, L2 is Regular Language :).
You can write regular expression for L2 too.
Language L2 = {WXWR| x, W ∈ {a,b}+}  means:

*

*string should start any string consist of a and b that is W and end with reverse string WR.

*notice: because W and WR are reverse of each other so string start and end with same symbol (that can be either a or b)

*And contain any string of a and b in middle that is X. (because of +, length of X becomes greater than one |X| >= 1)

Example of this kind of strings can be following:
aabababa, as follows:
   a    ababab    a
  --   --------   --
   w     X        W^R

or it can be also:
babababb, as follows:
   b    ababab    b
  --   --------   --
   w     X        W^R

See length of W is not a constraint in language definition.
so any string WXWR can be assume equals to a(a + b)+a or b(a + b)+b
    a    (a + b)+   a
   ---   --------  ---
    W      X       W^R

or
    b    (a + b)+   b
   ---   --------  ---
    W      X       W^R

And Regular Expression for this language is: a(a + b)+a + b(a + b)+b
Don't mix WXWR with WCWR, its X with + that makes language regular. Think by including X that is (a + b)* we can have finite choice for W that is a and b (finite is regular).
Language WXWR can be say: if start with a ends with a and if start with b end with b. so correspondingly we need two final states.

*

*Q6 if W is a

*Q5 if W is b
ITs DFA is as given below.


text:
Q: How do I get rid of the commas in the following JavaScript loop? The code:
var fileChapters = (function() {
  var results = [];
  for (i = 0, len = posts.length; i < len; _i++) {
    var post = posts[i];
    results.push("
" + post.title + "
\n\n");
  }
  return results;
});

console log to fileChapters:
["
Post 1
↵↵", "
Post 2
↵↵", "
Untitled
↵↵", "
Untitled
↵↵", "
Untitled
↵↵"]
Now when I do push:
file.unshift fileTOC

I end up with the following HTML:

Post 1

,
Post 2

,
Untitled

,
Untitled

,
Untitled

What's happening here? And how to solve it?

A: It is an array, it has commas when you do toString()
If you do not want the commas, use
return results.join("");


text:
Q: Sitecore 6.6 to 7.0 upgrade Upgrading from sitecore 6.6.0 (rev. 130529) to 7 and all worked fine until I tried to access 'Content Editor'. I get this strange error and have no idea what need to be done.
Exception: System.Web.HttpUnhandledException
Message: Exception of type 'System.Web.HttpUnhandledException' was thrown.
Source: System.Web
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean   includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint,    Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.sitecore_shell_applications_content_manager_default_aspx.ProcessRequest(HttpContext context) in c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\953a4a3d\d5c79dc4\App_Web_l41k3wf4.2.cs:line 0
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Nested Exception

Exception: System.Reflection.TargetInvocationException
Message: Exception has been thrown by the target of an invocation.
Source: mscorlib
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Sitecore.Reflection.ReflectionUtil.CallMethod(Type type, Object obj, String methodName, Boolean includeNonPublic, Boolean includeInherited, Boolean includeStatic, Object[] parameters)
at Sitecore.Shell.Applications.ContentManager.ContentEditorPage.OnPreRender(EventArgs e)
at System.Web.UI.Control.PreRenderRecursiveInternal()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

Nested Exception

Exception: System.TypeLoadException
Message: Access is denied: 'Sitecore.Shell.Applications.ContentEditor.RenderingDatasource'.
Source: mscorlib
at System.Reflection.RuntimeAssembly.GetType(RuntimeAssembly assembly, String name, Boolean throwOnError, Boolean ignoreCase, ObjectHandleOnStack type)
at System.Reflection.RuntimeAssembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase)
at Sitecore.Web.UI.XmlControls.ControlSource.ResolveType(String controlName, Assembly assembly)
at Sitecore.Web.UI.XmlControls.AssemblyControlSource.ResolveType(String controlName, Boolean includeDynamicTypes)
at Sitecore.Web.UI.XmlControls.ControlSource.GetControlType(String namespacePrefix, String controlName, String mode, Boolean includeDynamicTypes)
at Sitecore.Web.UI.XmlControls.ControlFactory.GetControlType(String controlName, String mode, Boolean includeDynamicTypes)
at Sitecore.Web.UI.XmlControls.ControlFactory.GetControl(Control parent, String controlName, String mode, Object[] properties, AllowGenericControl allowGeneric)
at Sitecore.Shell.Applications.ContentEditor.EditorFormatter.GetEditor(Item fieldType)
at Sitecore.Shell.Applications.ContentEditor.EditorFormatter.RenderField(Control parent, Field field, Item fieldType, Boolean readOnly, String value)
at Sitecore.Shell.Applications.ContentEditor.EditorFormatter.RenderField(Control parent, Field field, Item fieldType, Boolean readOnly)
at Sitecore.Shell.Applications.ContentEditor.EditorFormatter.RenderField(Control parent, Field field, Boolean readOnly)
at Sitecore.Shell.Applications.ContentEditor.EditorFormatter.RenderSection(Section section, Control parent, Boolean readOnly)
at Sitecore.Shell.Applications.ContentEditor.EditorFormatter.RenderSections(Control parent, Sections sections, Boolean readOnly)
at Sitecore.Shell.Applications.ContentEditor.Pipelines.RenderContentEditor.RenderStandardContentEditor.Process(RenderContentEditorArgs args)
at (Object , Object[] )
at Sitecore.Pipelines.PipelineMethod.Invoke(Object[] parameters)
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Pipelines.CorePipeline.Run(String pipelineName, PipelineArgs args, String pipelineDomain, Boolean failIfNotExists)
at Sitecore.Pipelines.CorePipeline.Run(String pipelineName, PipelineArgs args, String pipelineDomain)
at Sitecore.Pipelines.CorePipeline.Run(String pipelineName, PipelineArgs args)
at Sitecore.Shell.Applications.ContentManager.Editor.Render(RenderContentEditorArgs args, Control parent)
at Sitecore.Shell.Applications.ContentManager.Editor.Render(Item item, Item root, Hashtable fieldInfo, Control parent, Boolean showEditor)
at Sitecore.Shell.Applications.ContentManager.ContentEditorForm.RenderEditor(Item item, Item root, Control parent, Boolean showEditor)
at Sitecore.Shell.Applications.ContentManager.ContentEditorForm.UpdateEditor(Item folder, Item root, Boolean showEditor)
at Sitecore.Shell.Applications.ContentManager.ContentEditorForm.Update()
at Sitecore.Shell.Applications.ContentManager.ContentEditorForm.OnPreRendered(EventArgs e)

Tried few times but I cannot see this going away. Anyone else had this before?
Updated with full stack now. I'm not sure if first 2 exceptions has anything to do with this but it might be part of the problem.

A: The error is from Sitecore trying to load an assembly via reflection and getting a system level access denied on the DLL.  You should check that the identity your AppPool runs as has access to the webroot, in particular, the /bin folder and all it's contents.

A: Go the IIS and select the the site App pool. Then click on the Advance Setting and navigate to the Process Model Section. Change the Identity to NetworkService.
On your website folder, right click and go to properties. Select the Security Tab and add the following user:

*

*Everyone - check all checkboxes to provide full access

Also, make sure that NETWORK SERVICE is present in the list of usernames which all required access:


text:
Q: Git-garbage retention time I was trying to checkout a previous reflog hash after an accidental hard reset. Exactly for how long can GIT retain the reflog/ commits which were reset or garbage data?

A: By default it's 90 days, and you can configure it with gc.reflogExpire.
Also, it doesn't get altered by git reset commands. reflog is your safety net.


text:
Q: Using Single Domain SSL and Wildcard SSL in parallel on different IP addresses I have 2 different IIS websites on different IP addresses. One is abc.example.com and another is *.example.com
I have a single domain SSL certificate on abc.example.com and now considering putting a wildcard SSL on *.example.com
Will the wildcard SSL override the single domain SSL even if they have separate DNS entries?

A: They'll have no effect on each other whatsoever.


text:
Q: How do you add an UIView over a scroll but the view should stay still? iPhone Interface Builder question: Does anybody know how to add a small UIView over a ScrollView yet the image should stay still? Basically I already have a full image (320 x 480) over the Scroll, so the image scrolls, but now I need to add a AdMob View (320 x 48) on top of them. The problem is after i build and run, the ad scrolls as well. How do you make it stay still?
Thank you!

A: Not sure if this is how you've done it in your code, but if you've added the AdMob view as a subview of the scroller, then it will scroll.
It should not scroll if you add it as a subview elsewhere, either the superview of the scroller or the window itself.
I admit though that I generally do not use Interface Builder and would generally handle this programmatically, but I hope this helps.

A: Just place the AdMob view at the same hierarchical level of the ScrollView but being in front. Then when the Ad is available, set adMobView.hidden=NO, when it is not available set adMobView.hidden=YES. Essentially the hierarchy is:

RootView -
          |---- UIScrollView
                           |----- any UIView (to be scrolled)
          |---- AdMobView   --> not subview of ScrollView but subview of RootView

Of course when the Ad is visible you will not be able to tap on it to scroll, unless you subclass it to pass the tap to next level in hierarchy. But probably you have not this problem thanks to the reduced size of the Ad (48) with respect to the entire scrollView (480).


text:
Q: Double tap on a Flatlist React Native I'm trying to recreate Instagram's double tap on an item and a heart appears for a few seconds. Im currently rendering text items in a flatist (1 item per page) and I want the user to be able to double tap the text section and a heart will appear.
I can't seem to get both the flatList and the animation to work together. Any ideas? In my current code it will only render the flatList and not the Animated.image. I tried wrapping the animated image in an oppress in a touchable without feedback, still no luck
  const onDoubleTap = useCallback(() => {
    //console.log("tapped");
    scale.value = withSpring(1, undefined, (isFinished) => {
      if (isFinished) {
        scale.value = withDelay(500, withSpring(0));
        console.log("Double Tapped");
      }
    });
  }, []);

 return (
      <TapGestureHandler
        numberOfTaps={2}
        onActivated={onDoubleTap}
      >
        <Animated.View>
           <FlatList
            horizontal={false}
            decelerationRate={"fast"}
            snapToAlignment={"center"}
            snapToInterval={Dimensions.get("screen").height}
            data={flatl}
            // keyExtractor={(item, index) => `id_${index}`}
            style={styles.fullScreen}
            renderItem={({ item }) => (
              <View style={[{ ...styles.fullHeight }]}>
                <Text>{item.name}</Text>
              </View>
            )}
          />
          <AnimatedImage
            source={require("../assets/heart.png")}
            style={[
              styles.image,
              rStyle,
            ]}
            resizeMode={"center"}
          />
        </Animated.View>
      </TapGestureHandler>
  );
}


text:
Q: MongoTransactionException: Query failed with error code 251 Faced this Mongo exception when query a document in a transaction, with a specific id only (all other ids are fine):
Exception occured: org.springframework.data.mongodb.MongoTransactionException:
Query failed with error code 251 and error message
'Given transaction number 1 does not match any in-progress transactions. The active transaction number is -1' on server mongo-1:27017;
nested exception is com.mongodb.MongoQueryException:
Query failed with error code 251 and error message
'Given transaction number 1 does not match any in-progress transactions. The active transaction number is -1' on server mongo-1:27017
at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:136)
at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2902)
at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:2810)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:2555)
at org.springframework.data.mongodb.core.ExecutableFindOperationSupport$ExecutableFindSupport.doFind(ExecutableFindOperationSupport.java:216)
at org.springframework.data.mongodb.core.ExecutableFindOperationSupport$ExecutableFindSupport.oneValue(ExecutableFindOperationSupport.java:128)
at org.springframework.data.mongodb.repository.query.AbstractMongoQuery.lambda$getExecution$4(AbstractMongoQuery.java:153)
at org.springframework.data.mongodb.repository.query.AbstractMongoQuery.doExecute(AbstractMongoQuery.java:126)
at org.springframework.data.mongodb.repository.query.AbstractMongoQuery.execute(AbstractMongoQuery.java:101)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:618)

The MongoDB is a sharded cluster, and similar action is performed against a completely similar cluster (in another test environment) but no exception occurs.
Another info, this exception is always after a MongoDB socket exception as below:
Got socket exception on connection [connectionId{localValue:9, serverValue:11760}] to mongo-1:27017. All connections to mongo-1:27017 will be closed.

A: We had a similar issue in our project: some tests were failing with 251 'Given transaction number * does not match any in-progress transactions'. We wrote a test to reproduce the issue and then debugged it. I am 90% sure that we found the issue.
So the hypothesis is as follows:
when we use spring mongo transactions, actual transaction is started when the first request is sent to database (it does not matter what kind of request - query, update etc.). So, when first request is sent in parallel with any other requests, but was not able to complete before them, and they think that the transaction has been started (but it hasn't), then we see this error occur. "The transaction x+1 does not exist. Last transaction is x".
What led to this conclusion is the following log sequence (we enabled trace logs during test execution):

*

*2021-07-15 12:56:41.331 DEBUG 4900 --- [    Test worker] org.mongodb.driver.protocol.command      : Sending command '{"find": "items", "filter": {"_id": "d1"}, "limit": 1, "$db": "...", ..., "txnNumber": 1, "startTransaction": true, "autocommit": false, ...}' with request id 23 to database ... on connection ...

*...

*2021-07-15 12:56:41.334 DEBUG 4900 --- [    Test worker] org.mongodb.driver.protocol.command      : Sending command '{"find": "items", "filter": {"_id": "d2"}, "limit": 1, "$db": "...", ..., "txnNumber": 1, "autocommit": false, ...}' with request id 24 to database ... on connection ...

*...

*2021-07-15 12:56:41.337 DEBUG 4900 --- [ntLoopGroup-3-6] org.mongodb.driver.protocol.command      : Execution of command with request id 24 failed to complete successfully ...
com.mongodb.MongoCommandException: Command failed with error 251 (NoSuchTransaction): 'Given transaction number 1 does not match any in-progress transactions. The active transaction number is -1' on server ...

*...

*2021-07-15 12:56:41.379 DEBUG 4900 --- [ntLoopGroup-3-8] org.mongodb.driver.protocol.command      : Execution of command with request id 23 completed successfully ...

Notice how in first log we have "startTransaction": true, but in second - we don't. Yet, second request finished first, thus it errored. This error also occures if second request is starting in between first request start and first request complition, e.g.: first request starts, second request start, first request completes, second request completes.
Test code (in kotlin):
Service:
@Service
class TestService {

    @Autowired private lateinit var itemRepository: ItemRepository

    @Transactional
    fun parallelQuery(): Mono<Void> {
        return Flux.fromIterable(listOf("d1", "d2"))
            .flatMap {
                itemRepository.findById(it)
            }
            .then()
    }
}

Test itself:
internal class MonoZipTest: BaseTest() {
    @Autowired private lateinit var testService: TestService

    @Test
    fun test() {

        val mono =
            Flux.fromIterable(1..1000)
                .flatMap {
                    testService.parallelQuery()
                }
                .then()

        StepVerifier.create(mono)
            .expectError(MongoTransactionException::class.java)
            .verify()
    }
}

Conclusion: Ensure that first request to mongodb in transaction is not done in parallel with any other request in that transaction.

A: A little disclaimer: this is not a proper answer as I'm not sure that it could help the original poster; also, I have no proper explanation for this effect. I just wanted to let people know about this effect; usually I would use a comment for this, but it's too long for a comment. I post this in a hope that it could help someone to solve their problem.
We saw a similar exception recently:
Caused by: com.mongodb.MongoQueryException: Query failed with error code 251 and error message 'Given transaction number 198 does not match any in-progress transactions. The active transaction number is 197' on server aaa.bbb.ccc:27017
    at com.mongodb.operation.FindOperation$3.onResult(FindOperation.java:822)

I cannot show the code, so I will try to explain what it does.
In a non-reactive setting, it would be like this:
X = getX()
Y = saveAndReturnY()
pair = (X, Y)
processPair(pair)

This logic was implemented, and it worked fine (I do not show the working code version, it's not relevant). This code was running under transaction.
Then, I refactored this code to simplify it. It ended up looking like this:
getX() // Mono<X>
    .zipWith(saveAndReturnY()) // Mono<Tuple<X, Y>>
    .flatMap(this::processPair)

And with this code we observed the exception above. It did not happen 100% of times, something like 50/50: sometimes it did, sometimes it did not. This was only happening on MongoDB Atlas. Our integration tests using a MongoDB of the same version (4.2.9) working in a Docker container (via testcontainers) worked fine and we never managed to reproduce the problem there.
Long story short: it turned out that if we replace zipWith() with zipWhen(), the problem goes away:
getX() // Mono<X>
    .zipWhen(x -> saveAndReturnY()) // Mono<Tuple<X, Y>>
    .flatMap(this::processPair)

The difference is that with zipWith(), subscriptions happen at the same time to both Monos zipped together, that is to Mono<X> and Mono<Y>, so they execute "in parallel". But for zipWhen(), they execute strictly sequentially: you first get X out of Mono<X>, then you subscribe to Mono<Y>. In the original code (before refactoring), it worked in the same (sequential, or, probably, it's better to say, causal) way.
I'm not sure why this happened for us, we are still investigating. Maybe there is some problem that was just surfaced by this parallelism. Or there is something in MongoDB transactions that I do not understand (yet) that makes such exceptions happen when parallelism kicks off.
Anyway, in our case, getting rid of the parallelism solved the problem. Try analyzing your code and see whether there are some operators like Mono.zipWith() or Flux.flatMap() that subscribe to more than one Publisher eagerly causing such a "parallelism" effect.

A: My answer might be useful for someone using mongoose for nodejs.
I ran into the same error. After research I found out, that issue was caused by write conflicts. You could run db.currentOp() in mongosh to check.
Docs on this command:
https://docs.mongodb.com/manual/faq/concurrency/#how-do-i-see-the-status-of-locks-on-my--instances-
If there are some write conflicts, mongo retries operation in the transaction until conflicts are resolved, in my case it took more than 60 seconds (default max time for the transaction to complete), so it was aborted.
Good article about write conflicts:
https://blog.clairvoyantsoft.com/mongodb-transaction-management-884f82f62767


text:
Q: fundamentals of networking and digital communication Suppose that a group of computers is connected to an Ethernet LAN. If the computers communicate only with each other, does it make sense to use IP protocol in the computers? Should the computers run TCP directly over Ethernet? How is addressing handled?

A:
If the computers communicate only with each other, does it make sense to use IP protocol in the computers?

So much software assumes the ubiquity of IP, but if you are not using any such software, there's no need for IP.  You could not have any devices that expect anything but Ethernet frames between you and the computers.  You may run into problems with firewalls, managed switches, etc.

Should the computers run TCP directly over Ethernet?

You can't run standards-based TCP without IP, as TCP utilizes IP addresses.  You would have to use your own custom streaming protocol that's based on Ethernet or other link layer as a lower layer.
One thing IP does is abstract the link layer from upper levels of the stack - there was a time where it was possible you could have Ethernet or token ring, and there are things like PPP and HDLC, and also the loopback interface.
If you want to experiment with something similar without developing your own protocols, you could try to run IPX/SPX or AppleTalk over a small network.

How is addressing handled?

This is something you get to decide when you create your custom protocol above.  An option if you don't want to support routing at all is just using the MAC address.  Non-IP protocols like IPX/SPX and AppleTalk had their own address schemes and methods to obtain host addresses.

A: There are actually multiple questions here.
The first talks about using IP in a man. Yes, this is a good idea because the protocol is ubiquitous. In the distant past before the internet was a thing there were mtiple competing protocols, but for the general case that's fallen by the way as IP is well understood, standardised, easy to code for and extensible
TCP sits on top of IP, rather then replacing it - you require IPs ability to recognise and route packets. TCP adds a layer on top of this to provide reliable sessions.
With respect of IP addressing there are options. Using a DHCP server centralised control, but using static IPs can be easier to configure. You don't need a router for either method. As I understand it If you use IPv6 you don't need to specify an IP address at all as it can autoconfig a working IP address based on your MAC address.

A: As you describe, the PCs wouldn't have access to the internet. If this is true, you wouldn't have access to a DHCP server. You would then need to create your own subnet and configure your own IP address's on your own PCs, and since you arent communicating with a server, TCP should be irrelevant.


text:
Q: URL alias based on language in PHP I created a multilingual hotel site. The URLs look like the following:

www.blahblah.com/apartments.php?lang=en

What I want now is for a different language, say German, to have the following URL.:

www.blahblah.com/somethingElseHere.php?lang=de

I want that, in order to help my SEO for the website.
I think I have to use a URL alias, but I am not sure how to start.
Any ideas?

A: You'll have to write a piece of code like this:
session_start();
if (!isset($_SESSION['lang'])){
    $_SESSION['lang'] = "de";
    header("location:index.php?lang=de");
}

if (isset ($_GET["lang"]) && ($_GET["lang"]=="de" || $_GET["lang"]=="en"))
{
    $_SESSION["lang"]=$_GET["lang"];
}

function ln () {
    if ($_SESSION["lang"]=="de"){return false;};
    if ($_SESSION["lang"]=="en"){return true;};
}

function lang(){
    return $_SESSION["lang"];
}

function mk_link(){
    $return='';
    $except=func_get_args();
    foreach ($_GET as $key=>$value) if (!in_array($key,$except) && $value!='') $return.='&'.$key.'='.$value;
    return $return;
}

And then in your website you will have to use it like this:
<?php echo ln()?"Home":"Nach Haus;";?>

Nevertheless this is a rough method to do it and you will also have to filter your GET variables in order to make them safe.
However I strongly recommend a framework like cake, codeigniter or what else comes handy to you.

A: You could use mod_rewrite in a .htaccess file to make a URL like "www.yourdomain.com/german.html" lead to the appropriate index.php?lang=de.
Something like:
RewriteEngine on
RewriteRule ^german\.html$ /index.php?lang=de

There's a lot what you could do with mod_rewrite. Look at some more info here http://httpd.apache.org/docs/current/mod/mod_rewrite.html.


text:
Q: Is anything known about the number of a set partitions of a given type? As an example, suppose we have the set $\{1,2,3,4,5\}$ and say I want a partition with one singleton and two two-element sets. I could then have $1|23|45$, $2|13|45$, etc. Also, $1|23|54|$ or $1|45|23|$ are not counted as separate from $1|23|45|$. I would like to count the number of these.
I know that in general, if we are looking at a partition $P$ of $n$, where $P=(a_1,b_1),(a_2,b_2),...,(a_k,b_k)$ (is this the right notation?) where $a_1b_1+a_2b_2+\cdots+a_kb_k=n$ (so $b_i$ is the number of times $a_i$ shows up in the partition), then the number I am looking for is
$$\frac{1}{b_1!b_2!\cdots b_k!}\binom{n}{a_1}\binom{n-a_1}{a_1}\cdots\binom{n-a_1(b_1-1)}{a_1}\binom{n-a_1b_1}{a_2}\cdots \binom{n-a_1b_1-a_2b_2-\cdots-a_k(b_k-1)}{a_k}$$
Is there anything more known about such numbers, or an easier way to write this expression? Any reference would be super helpful. Thanks!


text:
Q: Play framework, Akka: actor communication with controller In short - I'm building a Scala/Play application which will monitor certain files/folders for changes and use Server Sent Events to push data to the browser.
I'm using Swatch library to do the monitoring which launches with application. This is my Global object. It starts the monitoring by launching a worker actor (as far as I understand) and reports if there are any changes - it's working just fine:
import akka.actor.{Props, ActorSystem}
import play.api._
import play.api.libs.concurrent.Akka
import play.api.Play.current
import include.Swatch._
import include.SwatchActor

object Global extends GlobalSettings {

    override def onStart(app: Application) {
        Logger.info("Application has started")
        val swatch = Akka.system.actorOf(Props[SwatchActor])
        swatch ! Watch("/folder/path", Seq(Create, Modify, Delete), true)
    }

}

At the moment whenever a change happens the swatch actor just outputs this to the console:
[INFO] [02/14/2014 11:45:04.377] [application-akka.actor.default-dispatcher-3] [akka://application/deadLetters] Message [include.Swatch$Create] from Actor[akka://application/deadLetters] to Actor[akka://application/deadLetters] was not delivered. [1] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'.

This is my controller (so far it's not doing much):
package controllers

import play.api._
import play.api.mvc._

object Application extends Controller {

    def index = Action {
        Ok("index")
    }

}

The browser should establish a connection with the controller and then whenever my worker actor detects a change, server push to the browser happens. My problem so far is: how do I get my worker actor to send messages to my index action in the controller? Would the approach I've described above work at all?
UPDATE: I'll be using websockets to communicate with the browser. Another important thing - the worker actor must be running all the time despite of if there is an established communication with the browser or not.
UPDATE2: Thanks to drexin and others I've managed to scrape together a solution.

A: What do you use for the communication between your app and the browser? Long polling, websockets?
In general I expect the SwatchActor to notify the sender of the Watch message when a change happens. As you send the message from outside of an actor, the sender will be noSender and thus the notifications will end up in the deadLetters. What you have to do is create an actor that receives the notifications and pushes them to the users either through a websocket or something similar.


text:
Q: Ensuring "pointer consistency" after compacting garbage collection I want to implement a compacting garbage collector for a runtime system that supports multiple threads running in parallel, with no global interpreter lock. My main goal is implementation simplicity. Portability isn't a big priority - I'd be happy with something that only works on x86-64 Linux systems.
Ideally, I'd like my memory barriers to be as simple as mprotect()ing the pages whose contents are being collected or moved elsewhere. If this causes a page fault in a mutator, the mutator has to wait until the garbage collection cycle completes - I'll set up a SIGSEGV handler that does just this.
However, because it's a compacting collector, when the garbage collection cycle finishes, the object that the mutator was trying to manipulate might have been moved elsewhere. I need some way to ensure that, when the mutator re-attempts to manipulate the object, it will use the object's new memory address, rather than the old one. How do I do this?

If it helps, here's a description of my object model. This design isn't set in stone, but it's a good reference point.
Memory is divided in properly aligned 64-bit words. Every object consists of a fixed-length header (1 word), followed by a variable-length body. Objects can be either scalars or arrays.
The header word of a scalar contains the following information:

*

*Object size: The number of words in the object's body. Must not exceed 48. (6 bits)

*Array flag: Always 0. (1 bit)

*Alive flag: Determines whether the object shall survive the next garbage collection cycle. (1 bit)

*Constructor tag: Unused by the garbage collector. Can be used to identify the constructor of an algebraic data type, hence the name. (8 bits)

*Pointer flags: The i-th pointer flag determines whether the i-th body word is a pointer to another object. (48 bits)

The header word of an array contains the following information:

*

*Element size: The number of words in a single element's body. Must not exceed 48. (6 bits)

*Array flag: Always 1. (1 bit)

*Alive flag: Determines whether some slice (see below) of the array shall survive the next garbage collection cycle. (1 bit)

*Array length: The number of elements in the array. (56 bits)

The elements of an array are themselves scalars, and must have their own header words. The object size of an array element must agree with the array's element size.
An array slice, or just slice, is a contiguous element range within an array object. A pointer into a slice consists of three words:

*

*A pointer into an array object proper.

*The endpoints of the half-open element range [from,to).

Pointers into arrays can't exist in isolation - they must always be a part of a pointer into a slice. This design has some practical consequences:

*

*Multiple slices can have elements with the same physical identity.

*Taking a subslice of a slice is an O(1) operation.

*Arrays can be truncated or split by the garbage collector, if no contiguous reference to them exists.


text:
Q: Stacked Sparse Autoencoder parameters I work on Stacked Sparse Autoencoders using MATLAB.
Can anyone please suggest what values should be taken for
    Stacked Sparse Autoencoder parameters:
                 L2 Weight Regularization ( Lambda)
                 Sparsity Regularization (Beta)
                 Sparsity proportion (Rho).

A: It is important to realise that there are NO OBVIOUS VALUES for the hyperparameters. The optimal value will vary, depending on the data you're modeling: you'll have to try them on your data.
From sparseAutoencoder Lambda (λ) is coefficient of weight decay term which discourage weights to reach big values since it may overfit. Weight decay term (or weight regularization term) is a part of the cost function like sparsity term explained below.
Rho (ρ) is sparsity constraint which controls average number of activation on hidden layer. It is included to make autoencoder work even with relatively big number of hidden units with respect to input units. For example, if input size is 100 and hidden size is 100 or larger (even smaller but close to 100), the output can be constructed without any lost, since hidden units can learn identity function. Beta (β) is coeffecient of sparsity term which is a part of the cost function. It controls relative importance of sparsity term. Lambda and Beta specify the relative importance of their terms in cost function.
Example: You can take a loot at this example where parameter values are selected as follows.
sparsityParam = 0.1;   % desired average activation of the hidden units.
                       % (This was denoted by the Greek alphabet rho, which looks like a lower-case "p",
                       %  in the lecture notes).
lambda = 3e-3;         % weight decay parameter
beta = 3;              % weight of sparsity penalty term

But once again, i want to make you remember that there are NO OBVIOUS VALUES for the hyperparameters.


text:
Q: What is the fastest way to get the last elements of a list by ID with Datetime? I have a huge List<MyObject>. MyObject had a property named Timestamp (DateTime?) and a Code (string).
I need to get the lasts Objects by timestamp for each code.
For example with this following input :
Code| A   | B   | Timestamp
A1  | ABC | DEF | Fri 7 Mar 2014
B2  | ABC | GHI | Thu 6 Mar 2014
A1  | DEF | GHI | Mon 10 Mar 2014
B2  | DEF | GHI | Fri 7 Mar 2014
C3  | GHI | JKL | Fri 7 Mar 2014

I need to get this :
Code| A   | B   | Timestamp
A1  | DEF | GHI | Mon 10 Mar 2014
B2  | DEF | GHI | Fri 7 Mar 2014
C3  | GHI | JKL | Fri 7 Mar 2014

In order to do this I did the following function :
private List<MyObject> GetLastsObjects(List<MyObject> input)
{
    var output = input.Where(x => x.Timestamp == x.Where(y => y.Code == y.Code)
                                                               .Max(tmp => tmp.Timestamp))
                      .ToList();
    return output;
}

It works but I have really bad performance with a huge input...
Do you know how can I optimized this function ? What is the fastest way to get the last elements by timestamp for each Code ?

A: I suggest using a MaxBy extension method. It will save you having to perform a complete sort only to select the top item, so will consequently have much more favourable memory characteristics and most likely be somewhat quicker. There's one in the morelinq package.
So...
input.GroupBy(x => x.Code).Select(g => g.MaxBy(x => x.TimeStamp))

A: One way would be to group the objects by code, reverse sort each group by timestamp and get the first result of each group:
var output = input
    .GroupBy(o => o.Code)
    .Select(g1 => g1.OrderByDescending(g2 => g2.Timestamp).First())
    .ToList();


text:
Q: parseDOM error in Firefox 45.0 I use the folowing code to convert HTML page into DOM object
var htmlPage = '<img id="img1" src="myImage.jpg" /> ';
var doc = parser.parseFromString(htmlPage, "text/html");

and then I can use the doc object to access any html component like this
doc.img1

This morning I upgraded my firefox to version 45.0 (latest version), but suddenly the above code stopped working!!
and I start to get the error
doc.img1 is undefined

is there anything wrong? or did mozilla changed the way the parse the HTML into DOM... or is it a bug?


text:
Q: Put request failing with Alamofire 2.0 I have recently upgraded to Alamofire 2.0, and now my Put request is failing with a 400 error, when it was previously working properly. I perform the call with the code:
Alamofire.request(Router.Put(query: url, params: params, encoding: .JSON))
    .validate()
    .responseJSON() {
        (request, response, result) in

        print("request: \(request)")
        print("response: \(response)")
        print("result: \(result)")

        switch result {
        case .Success(_):
            // success
        case .Failure(let data, _):
            // error occured
        }
}

and my custom Router class:
enum Router: URLRequestConvertible {

    case Get(query: String, params: [String: AnyObject]?)
    case Post(query: String, params: [String: AnyObject]?)
    case Put(query: String, params: [String: AnyObject]?, encoding: ParameterEncoding)
    case Delete(query: String, params: [String: AnyObject]?)

    var URLRequest: NSMutableURLRequest {
        var encodeMethod: Alamofire.ParameterEncoding = Alamofire.ParameterEncoding.URL

        // Default to GET
        var httpMethod: String = Alamofire.Method.GET.rawValue

        let (path, parameters): (String, [String: AnyObject]?) = {
            switch self {
            case .Get(let query, let params):
                // Set the request call
                httpMethod = Alamofire.Method.GET.rawValue
                // Return the query
                return (query, params)
            case .Post(let query, let params):
                // Set the request call
                httpMethod = Alamofire.Method.POST.rawValue
                // Return the query
                return (query, params)
            case .Put(let query, let params, let encoding):
                // Set the request call
                httpMethod = Alamofire.Method.PUT.rawValue
                // Set the encoding
                encodeMethod = encoding
                // Return the query
                return (query, params)
            case .Delete(let query, let params):
                // Set the request call
                httpMethod = Alamofire.Method.DELETE.rawValue
                // Return the query
                return (query, params)
            }
        }()

        // Create the URL Request
        let URLRequest = NSMutableURLRequest(URL: NSURL(string: Globals.BASE_URL + path)!)
        // set header fields
        if let key = NSUserDefaults.standardUserDefaults().stringForKey(Globals.NS_KEY_SESSION) {
            URLRequest.setValue(key, forHTTPHeaderField: "X-XX-API")
        }
        // Add user agent
        if let userAgent = NSUserDefaults.standardUserDefaults().stringForKey(Globals.NS_KEY_USER_AGENT) {
        URLRequest.setValue(userAgent, forHTTPHeaderField: "User-Agent")
        }

        // Set the HTTP method
        URLRequest.HTTPMethod = httpMethod

        URLRequest.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData

        return encodeMethod.encode(URLRequest, parameters: parameters).0
    }
}

Instead of the call being a success, the response is:
response: Optional(<NSHTTPURLResponse: 0x7fcee15b34d0> { URL: https://apiurl } { status code: 400, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 26;
"Content-Type" = "application/json; charset=utf-8";
Date = "Tue, 15 Sep 2015 15:33:50 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/8.5";
} })

I looked into the problem and on the server side, Content-Type is coming in as blank for the request, when it should be coming in as application/json. The Content-Type should automatically get added when there is body data in the request. I have the params set:
// Save the profile
var params: [String: AnyObject] = ["indexPhoto": userProfile.indexPhoto,
    "dob": df.stringFromDate(userProfile.dob) as NSString,
    "identAs": userProfile.identAs]
// Add manually since creating the dictionary all at once is too much for swift to handle
params.updateValue(String(format:"%.2f", userProfile.heightIn), forKey: "heightIn")
params.updateValue(String(format:"%.2f", userProfile.weightLbs), forKey: "weightLbs")
params.updateValue(userProfile.eyes, forKey: "eyes")
params.updateValue(userProfile.hair, forKey: "hair")
...

Is there something I could be missing with this? Before I upgraded to Alamofire 2.0 this call was working just fine.

A: Maybe there is a different way but I fixed the same issue by sending empty params instead of nil. I don't use any parameters when using .PUT and because of that server doesn't know how to encode request and response (even if I explicitly set content type inside header, I receive blank content type on the server) so my solution was sending empty params like in the code below. Hope it helps someone.
var url = https://api.mysite.com/v1/issue/369613/delete

let params = ["":""]

let headers = NetworkConnection.addAuthorizationHeader(token, tokenType: tokenType)
manager.request(.PUT, url, parameters: params, encoding: .JSON, headers: headers)
        .responseJSON { response in
            if let JSONdata = response.result.value {
                print("JSONdata: \(JSONdata)")
            }
}


text:
Q: Google Foobar escape-pods Test Case N. 4 fails I am solving the Google Foobar - Escape pods problem on level 4, and I faced a problem on test case N.4 which never passes!
I've got only two days till the deadline and cannot figure out what is the problem with my code on that case. Is there anyone who can take a look or can provide me with some test cases in which my code fails?
Here is the question:
Escape Pods
You've blown up the LAMBCHOP doomsday device and broken the bunnies out of Lambda's prison - and now you need to escape from the space station as quickly and as orderly as possible! The bunnies have all gathered in various locations throughout the station, and need to make their way towards the seemingly endless amount of escape pods positioned in other parts of the station. You need to get the numerous bunnies through the various rooms to the escape pods. Unfortunately, the corridors between the rooms can only fit so many bunnies at a time. What's more, many of the corridors were resized to accommodate the LAMBCHOP, so they vary in how many bunnies can move through them at a time.
Given the starting room numbers of the groups of bunnies, the room numbers of the escape pods, and how many bunnies can fit through at a time in each direction of every corridor in between, figure out how many bunnies can safely make it to the escape pods at a time at peak.
Write a function solution(entrances, exits, path) that takes an array of integers denoting where the groups of gathered bunnies are, an array of integers denoting where the escape pods are located, and an array of an array of integers of the corridors, returning the total number of bunnies that can get through at each time step as an int. The entrances and exits are disjoint and thus will never overlap. The path element path[A][B] = C describes that the corridor going from A to B can fit C bunnies at each time step.  There are at most 50 rooms connected by the corridors and at most 2000000 bunnies that will fit at a time.
For example, if you have:
entrances = [0, 1]
exits = [4, 5]
path = [
  [0, 0, 4, 6, 0, 0],  # Room 0: Bunnies
  [0, 0, 5, 2, 0, 0],  # Room 1: Bunnies
  [0, 0, 0, 0, 4, 4],  # Room 2: Intermediate room
  [0, 0, 0, 0, 6, 6],  # Room 3: Intermediate room
  [0, 0, 0, 0, 0, 0],  # Room 4: Escape pods
  [0, 0, 0, 0, 0, 0],  # Room 5: Escape pods
]

Then in each time step, the following might happen:
0 sends 4/4 bunnies to 2 and 6/6 bunnies to 3
1 sends 4/5 bunnies to 2 and 2/2 bunnies to 3
2 sends 4/4 bunnies to 4 and 4/4 bunnies to 5
3 sends 4/6 bunnies to 4 and 4/6 bunnies to 5
So, in total, 16 bunnies could make it to the escape pods at 4 and 5 at each time step.  (Note that in this example, room 3 could have sent any variation of 8 bunnies to 4 and 5, such as 2/6 and 6/6, but the final solution remains the same.)
here is my code:
class Edge:
    def __init__(self, destination, capacity):
        self.destination = destination
        self.capacity = capacity
        self.remaining = capacity

class Node:

    def __init__(self, name, level=0, edges=None):
        self.name = name
        self.level = level
        if edges is None:
            self.edges = []

    def add_edge(self, destination, weight):
        self.edges.append(Edge(destination, weight))

    def get_children(self):
        res = []
        for edge in self.edges:
            res.append(edge.destination)
        return res

    def __str__(self):
        res = str(self.name) + " ({})".format(str(self.level))
        for edge in self.edges:
            res = res + " --> {} ({})".format(str(edge.destination), str(edge.remaining))
        return res

class Graph:
    nodes = []
    flow = []
    permanent_dead_ends = []
    levels = []

    def __init__(self, entrances, exits, matrix):
        self.entrances = entrances
        self.exits = exits
        self.matrix = matrix
        for i in range(0, len(self.matrix)):
            self.nodes.append(Node(i))

    def create(self):
        for i in range(0, len(self.matrix)):
            if self.nodes[i].name in self.exits:
                continue
            for j in range(0, len(self.matrix[i])):
                if self.matrix[i][j] != 0:
                    self.nodes[i].add_edge(j, self.matrix[i][j])

    def bfs(self):
        queue = self.entrances[:]
        seen = self.entrances[:]
        level = 0
        self.levels = [-1] * len(self.matrix)
        for entrance in self.entrances:
            self.nodes[entrance].level = level
            self.levels[entrance] = level
        while len(queue) > 0:
            to_remove = []
            i = queue.pop(0)
            level = self.nodes[i].level + 1
            for edge in self.nodes[i].edges:
                if edge.destination in self.permanent_dead_ends:
                    to_remove.append(edge)   # pruning permanent dead ends
                elif edge.remaining > 0:
                    if edge.destination not in seen:
                        self.nodes[edge.destination].level = self.levels[edge.destination] = level
                        queue.append(edge.destination)
                        seen.append(edge.destination)
                else:
                    to_remove.append(edge)
            for edge in to_remove:
                self.nodes[i].edges.remove(edge)

        #for node in self.nodes:
            #print(node)

        if self.is_finished():
            return False

        return True

    def is_finished(self):
        for ex in self.exits:
            if self.levels[ex] != -1:
                return False
        return True

    def choose_next_node(self, candidates, dead_ends):
        for i in candidates:
            previous_level = self.nodes[i].level
            for edge in self.nodes[i].edges:
                if (edge.remaining > 0) \
                        and (previous_level < self.nodes[edge.destination].level)\
                        and (edge.destination not in dead_ends):
                    return i, edge, edge.remaining
        return None, None, None

    def dfs(self):
        path = []
        capacities = []
        edges = []
        dead_ends = self.permanent_dead_ends[:]
        entr = self.entrances[:]
        current_node, edge, capacity = self.choose_next_node(entr, dead_ends)
        next_node = None
        if edge is not None:
            next_node = edge.destination
            edges.append(edge)
            path.append(current_node)
            if next_node in self.exits:
                path.append(next_node)
                capacities.append(capacity)
        else:
            return

        while next_node not in self.exits and len(path) > 0:
            if next_node != path[-1]:
                path.append(next_node)
                capacities.append(capacity)
            current_node, edge, capacity = self.choose_next_node([next_node], dead_ends)
            if edge is not None:
                next_node = edge.destination
                edges.append(edge)
                if next_node in self.exits:
                    path.append(next_node)
                    capacities.append(capacity)
            else:
                #print("dead-end reached: {}".format(path))
                if len(path) > 1:
                    dead_ends.append(path[-1])
                    path = path[:-1]
                    edges = edges[:-1]
                    next_node = path[-1]
                    capacities = capacities[:-1]
                else:
                    entr.remove(path[0])
                    path = []
                    capacities = []
                    current_node, edge, capacity = self.choose_next_node(entr, dead_ends)
                    next_node = None
                    if edge is not None:
                        next_node = edge.destination
                        edges.append(edge)
                        path.append(current_node)
                        if next_node in self.exits:
                            path.append(next_node)
                            capacities.append(capacity)
                    else:
                        return

        if len(path) < 1:
            #print("no path found!")
            return False

        capacity = min(capacities)
        #print("capacity: {}".format(capacity))
        self.flow.append(capacity)
        #print("path: {}".format(path))
        i = 0
        for edge in edges:
            edge.remaining -= capacity
            if edge.remaining == 0:
                self.nodes[path[i]].edges.remove(edge)
                if len(self.nodes[path[i]].edges) < 1:
                    self.permanent_dead_ends.append(self.nodes[path[i]].name)
                    #print("added permanent dead end: {}".format(self.nodes[path[i]].name))
            i += 1
        #for node in self.nodes:
            #print(node)

        return False

def solution(entrances, exits, matrix):
    graph = Graph(entrances,  exits, matrix)
    graph.create()
    while graph.bfs():
        #print("another BFS!")
        graph.dfs()
    #print("flow is: {}".format(graph.flow))
    return sum(graph.flow)

A: Hopefully you can use this code to help trace what is wrong with your code.
Disclaimer: I did not write the solution (only the unittests) and only used it to complete the challenge to see what happened at the end.
Good luck!
import unittest

def solution(entrances, exits, path):
# First, it's important to realize that this is a multiple sources, multiple
    # sinks problem where we have to find the max flow. This problem builds off
    # of the single source, single sink problem. To get the max flow for the
    # latter problem, you create a residual graph and then find an augmenting
    # path through the residual graph using DFS, updating the residual graph
    # based on the augmenting path found. So long as there is an augmenting path
    # through the residual graph, you can increase the flow.
    #
    # We can extend this solution to multiple sources and multiple sinks. If
    # an augmenting path can be found starting at ***any*** source and ending
    # at ***any*** sink, you can increase the flow.

    # The residual graph starts out being the same as the graph given to us.
    residual = path[:]

    # How many bunnies can make it to the escape pods at each time step?
    numBunnies = 0

    # To determine whether the number of bunnies we found is the max flow, we
    # have to have a tracker that would determine whether we were able to find
    # an augmented path
    prevNumBunnies = -1
    while prevNumBunnies != numBunnies:

        # Set the tracker here. If an augmented path is found, numBunnies will
        # change.
        prevNumBunnies = numBunnies

        # Check all paths starting at each available entrance
        for j in entrances:

            # Visited graph - which nodes have been visited?
            visited = []

            # The augmented path, implemented as a stack. The stack will add a
            # node if the node is connected to at least one other unvisited
            # node. The node on the top of the stack will be popped otherwise.
            path = []

            # Start the path at an entrance
            node = j
            while 1:

                # Keep track of whether or not we have found an unvisited node
                # connected to our current node of interest
                findUnvisited = False

                # Also keep track of visited nodes
                visited.append(node)

                # To speed up program, use a greedy algorithm. At each node,
                # only travel to a connected unvisited node that would allow
                # the maximum number of bunnies to travel through.
                maximum = 0
                index = 0

                # Check all adjacent nodes for the one that would allow the
                # maximum number of bunnies to travel through
                for i in range(len(residual[node])):
                    if residual[node][i] > maximum and i not in visited:
                        maximum = residual[node][i]
                        index = i
                        findUnvisited = True

                # Go to the node that would allow the most number of bunnies
                # in the corridor
                if findUnvisited:
                    path.append(node)
                    node = index

                # If there are no unvisited nodes connected to this entrance,
                # check the paths connecting to another entrance.
                elif not path:
                    break

                # If there are no unvisited nodes connected, backtrace in the
                # augmented path.
                else:
                    node = path.pop()

                # If we find an end node, update the residual graph depending
                # on the augmented path. To speed up the program, get the
                # maximum number of bunnies that could go through the corridor
                # by finding the bottleneck corridor in the augmenting path
                # (the corridor that would allow the least number of bunnies to
                # go through. Use that to update numBunnies
                if node in exits:
                    path.append(node)
                    minimum = 2000000
                    for j in range(len(path) - 1):
                        if residual[path[j]][path[j + 1]] < minimum:
                            minimum = residual[path[j]][path[j + 1]]
                    numBunnies += minimum
                    for j in range(len(path) - 2):
                        residual[path[j]][path[j + 1]] -= minimum
                        residual[path[j + 1]][path[j]] += minimum
                    residual[path[len(path) - 2]][path[len(path) - 1]] -= minimum
                    break

    # Return number of bunnies
    return numBunnies

ents = [0, 1]
exts = [4, 5]
pth = [
  [0, 0, 4, 6, 0, 0],  # Room 0: Bunnies
  [0, 0, 5, 2, 0, 0],  # Room 1: Bunnies
  [0, 0, 0, 0, 4, 4],  # Room 2: Intermediate room
  [0, 0, 0, 0, 6, 6],  # Room 3: Intermediate room
  [0, 0, 0, 0, 0, 0],  # Room 4: Escape pods
  [0, 0, 0, 0, 0, 0],  # Room 5: Escape pods
]
ans = 16

ents2 = [0]
exts2 = [3]
pth2 = [
    [0, 7, 0, 0],
    [0, 0, 6, 0],
    [0, 0, 0, 8],
    [9, 0, 0, 0]
]
ans2 = 6

print(solution(ents2, exts2, pth2))

class TestEscapePods(unittest.TestCase):
    def test1(self):
        self.assertEqual(solution(ents, exts, pth), ans)

    def test2(self):
        self.assertEqual(solution(ents2, exts2, pth2), ans2)

unittest.main()


text:
Q: Install-Package LibUsbDotNet -Version 2.2.18 Attempting to resolve dependency 'LibUsb.Common (≥ 2.2.18)'. I
Install-Package : 'LibUsbDotNet' already has a dependency defined for 'LibUsb.Common'.
  At line:1 char:16
  + Install-Package <<<<  LibUsbDotNet -Version 2.2.18
      + CategoryInfo          : NotSpecified: (:) [Install-Package], InvalidOperationException
      + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

I got this error when installing the latest LibUsbDotNet version. How can i solve this?


text:
Q: Http.Context with FakeApplication and illusive mock method In my tests I create a fake application per test method:
@Before
public void startFakeApplication() {
    this.fakeApplication = fakeApplication();
    start(this.fakeApplication);
}

@After
public void killFakeApplication() {
    stop(this.fakeApplication);
    this.fakeApplication = null;
}

Some of the tests use functionality that checks if the request is secure or not:
public boolean isHttps() {
    Http.Request req = Controller.request();
    return req.getHeader("x-forwarded-proto") != null
            && req.getHeader("x-forwarded-proto").contains("https");
}

That fails saying:

There is no HTTP Context available from here

Which is pretty strange, since it's running on a fake app, why can't it know that and create a fake request?
Oh well, I found this: Play framework 2.2.1: Create Http.Context for tests which introduced me to the mocking approach, so I was eager to give it a go and try to mock the Http.Context in the same way, the problem is that I can't seem to find the mock method...
In that thread he's using import static org.mockito.Mockito.* (which is where I assume the mock method is located) but I don't have that package, org.mockito only has one sub package named internal and I can't find any mock method there.
In the official documentation of Play! the only place talking about it is the Scala Test section and they use: import org.specs2.mock._ but there too I wasn't able to locate this mock method.
I'm using Play 2.2.2 (java).
Any ideas? Thanks.

A: I solved the same problem adding to my build.sbt the library dependency of Mockito:
libraryDependencies += "org.mockito" % "mockito-core" % "1.10.19"

Then I run play compile and play eclipse and magically the mockito library became available after refreshing the whole project in Eclipse.
And yes, mock() is a method of org.mockito.Mockito.

A: I had the same problem of Play not locating the mock function, and eventually realised that I hadn't extended my test class with Mockito;
import org.specs2.mock._

class TestClass extends Specification with Mockito

Just thought I'd add this as it has taken me ages to resolve and the above solution didn't work for me ......may save someone some time :)


text:
Q: Ubuntu 20.* как получить адреса которые получали через DNS как логировать dns запросы?
если компьютер через браузер или через скрипты обращается к стронним сервисам, то логировать куда именно он обращался, желательно через DNS

A: Установи локально dnsmasq  и настрой его как nameserver sudo nano /etc/NetworkManager/conf.d/use-dnsmasq.conf
[main]
dns=dnsmasq

Добавь log-queries sudo nano /etc/NetworkManager/dnsmasq.d/log.conf
log-queries
log-facility=/var/log/nm-dnsmasq.log

Лог запросов смотри tail -f /var/log/nm-dnsmasq.log | grep 'query\[A'


text:
Q: Outer Measure: Theorem) for an interval $I$, $|I|_e=v(I)$? I do not understand a theorem. So can someone explain for me?

Definition

*

*closed n-dimensional intervals are $$I=\{\mathbf{x}:a_j\le x_j\le b_j,~~j=1, \cdots, n\}$$

*their volumes are $$v(I)=\prod_{j=1}^n(b_j-a_j)$$

*A countable collection $S$ of intervals $I_k$ is $$S=\{I_1, I_2, I_3, \cdots\}$$

*Then, $S$ is called a covering of $E$ if $$\cup_{I_j\in S}\supset E$$

*If $\sigma(S)=\sum_{I_k\in S} v(I_k)$, then the Lebesgue outer measure of $E$ is$$
|E|_e=\inf\sigma(S)$$

Theorem
For an interval $I$, $|I|_e=v(I)$.

Proof

*

*Since $I$ covers itself, $|I|_e \le v(I)$.

*Let $I_k^*$ be an interval containing $I_k$ in its interior such that $$v(I_k^*)\le(1+\varepsilon)v(I_k)$$

*Then, $$I \subset \cup_k(I_k^*)$$

*Since $I$ is compact, there exists $N$ such that $$I\subset \cup_{k=1}^N I_k^*$$ by the Heine-Borel theorem.

*Clearly, $$v(I)\le \sum_{k=1}^N v(I_k^*)$$

*Hence, $$v(I)\le (1+\varepsilon)\sum_{k=1}^Nv(I_k)\le(1+\varepsilon)\sigma(S)$$

*Since $\varepsilon$ can be chosen arbitrarily small, it follows $$v(I)\le\sigma(S) \quad \text{ and } \quad v(I)\le|I|_e$$

*By step 1 and 7, $$v(I)\le|I|_e\le v(I)\\\therefore v(I)=|I|_e$$

My problem
I do not understand step 1 and step 4.
Can someone explain about why $|I|_e \le v(I)$ and why $I$ is compact

A: $I$ is compact since it is a $k$-cell in $R^n$. This result is often called the Heine-Borel theorem (as mentioned in your post); you may find a proof of this in many online lecture notes or textbooks.
The definition of outer measure says this: if you can find a covering of the set $E$ with some measure $m$, the outer measure of $E$ is necessarily $\leq m$. This is because it is defined as the infimum of all the measures of the coverings.


text:
Q: Why do factory functions with keys that have same name values only change the value when given a parameter In:
function f(sex) {
return : {
sex: sex,
}
}
if I do:
const Leopard = f(blue)
Leopard will be an object that has {sex: blue,}, my question is why does sex (the key) not change, and is it not encombering to not be able to change the key.

A: In the object literal {sex: sex}, the property key (name) is hardcoded to be sex. The value comes from the parameter sex, but the name is hardcoded.
If you wanted to change both, you could use the value from the parameter as the property name by using computed property name syntax:
return {[sex]: sex};
//      ^^^^^−−−−−−−−−−−−−−−− computed property name syntax uses
//                            the value from the `sex` parameter

Example:

function f(sex) {
    return { [sex]: sex, };
}

const leopard = f("blue");
console.log(leopard);


text:
Q: Stringing together multiples of the same string (an asterisk) determined by an input file. C++ Essentially, the objective is to read an input file (hence inFile and inFileName) and output a population growth with asterisks representing each 1000 people using an ID (ex. 1375892), going from the year 1900 to 2020 in 20-year increments.
So, 1 asterisk for 1000 people, 3 asterisks for 3000 people, etc. The input file has numbers like 5000 and 7000 that I need to use to calculate the number of asterisks I need (by dividing by 1000). Even with that, I'm trying to figure out the final step in converting asteriskNum (the number of asterisks I need to use) and have it output the string of asterisks, not an integer of how many asterisks I need.
I definitely know I'm missing SOMETHING, but even after asking my teacher and scouring through my textbook and notes, I can't figure out how to solve this specific issue.
#include<iostream>

#include<iomanip>

#include<string>

#include<fstream>

using namespace std;

int main(){
   string asterisk = "*";
   string firstName;
   int PopNum{0};
   int year{1900};
   int asteriskNum{};
   const string INTROLINE{"POPULATION GROWTH \n(each * represents 1000 people)"};
   cout << INTROLINE << "\n";

   string inFileName="DL8_L5_Morrison.txt";
   ifstream inFile{inFileName};

if (inFile){

   cout << inFileName << " opened for reading. \n";

   inFile >> firstName;

   while (not inFile.eof()){
     inFile >> PopNum;
     asteriskNum = PopNum/1000;
     cout << year << " " << asteriskNum << " " <<  << "\n";
     year+=20;

   inFile.close();
}
else {
   cout << inFileName << " did not open for reading. \n";}
   cout<<"Goodbye!\n";
   return EXIT_SUCCESS;
}
}

A: You can use a std::string object and use the constructor that takes a count and character as arguments (constructor version #2 here). This will work with an int for the count argument, but it is better to cast it to a size_t type (or just have the calculated value as a size_t in the first place):
//...
  asteriskNum = PopNum/1000;
  cout << year << " " << std::string(static_cast<size_t>(asteriskNum), '*') << std::endl;
//...


text:
Q: SQL statement for querying with multiple conditions including 3 most recent dates I need help in finding the rows that correspond to the most recent date, the next most recent and the one after that, where some condition ABC is "Y" and group it by a column name XYZ ASC but XYZ can appear multiple times. So, say XYZ is 50, then for the rows in the three years, the XYZ will be 50. I have the following code that executes but returns only two rows out of thousands which is impossible. I tried executing just the date condition but it returned dates that were less than or equal to MAX(DATE)-3 as well. Don't know where I am going wrong.
select * from money.cash where DATE =(
  select
  MAX(DATE)
  from
  money.cash
  where
  DATE > (select MAX(DATE)-3 from money.cash)
)
GROUP BY XYZ ASC
having ABC = "Y";

The structure of the table is as follows (only a schematic, not the real thing).
Comp_ID   DATE   XYZ   ABC  $$$$ ....
1     2012-1-1    10    Y   SOME-AMOUNT
2     2011-1-1    10    Y
3     2006-1-1    10    Y
4     2011-1-1    20    Y
5     2002-1-1    20    Y
6     2000-1-1    20    Y
7     1998-1-1    20    Y

The desired o/p would be the first three rows for XYZ=10 in ascending order and the most recent 3 dates for XYZ=20.
LAST AND IMPORTANT-This table's values keeps changing as new data comes in. So, the o/p(which will be in a new table) must reflect the dynamics in the 1st/original/above TABLE.

A: MySQL doesn't have functionallity that is friendly to greatest-n-per-group queries.
One option would be...
- Find the MAX(Date) per group (XYZ)
- Then use that result to find the MAX(Date) of all records before that date
- Then do it again for all records before that date
It's really innefficient, but MySQL hasn't got the functionality required to do this efficiently.  Sorry...
CREATE TABLE yourTable
     (
      comp_id                          INT,
      myDate                           DATE,
      xyz                              INT,
      abc                              VARCHAR(1)
)
;

INSERT INTO yourTable SELECT 1, '2012-01-01', 10, 'Y';
INSERT INTO yourTable SELECT 2, '2011-01-01', 10, 'Y';
INSERT INTO yourTable SELECT 3, '2006-01-01', 10, 'Y';
INSERT INTO yourTable SELECT 4, '2011-01-01', 20, 'Y';
INSERT INTO yourTable SELECT 5, '2002-01-01', 20, 'Y';
INSERT INTO yourTable SELECT 6, '2000-01-01', 20, 'Y';
INSERT INTO yourTable SELECT 7, '1998-01-01', 20, 'Y';

SELECT
  yourTable.*
FROM
(
  SELECT
    lookup.XYZ,
    COALESCE(MAX(yourTable.myDate), lookup.MaxDate)  AS MaxDate
  FROM
  (
    SELECT
      lookup.XYZ,
      COALESCE(MAX(yourTable.myDate), lookup.MaxDate)  AS MaxDate
    FROM
    (
      SELECT
        yourTable.XYZ,
        MAX(yourTable.myDate)  AS MaxDate
      FROM
        yourTable
      WHERE
        yourTable.ABC = 'Y'
      GROUP BY
        yourTable.XYZ
    )
      AS lookup
    LEFT JOIN
      yourTable
        ON  yourTable.XYZ    = lookup.XYZ
        AND yourTable.myDate < lookup.MaxDate
        AND yourTable.ABC    = 'Y'
    GROUP BY
      lookup.XYZ,
      lookup.MaxDate
  )
    AS lookup
  LEFT JOIN
    yourTable
      ON  yourTable.XYZ    = lookup.XYZ
      AND yourTable.myDate < lookup.MaxDate
      AND yourTable.ABC    = 'Y'
  GROUP BY
    lookup.XYZ,
    lookup.MaxDate
)
  AS lookup
INNER JOIN
  yourTable
    ON  yourTable.XYZ     = lookup.XYZ
    AND yourTable.myDate >= lookup.MaxDate
WHERE
  yourTable.ABC = 'Y'
ORDER BY
  yourTable.comp_id
;

DROP TABLE yourTable;

There are other options, but they're all a bit hacky.  Search SO for greatest-n-per-group mysql.
My results using your example data:
Comp_ID | DATE     | XYZ | ABC
------------------------------
   1    | 2012-1-1 | 10  |  Y
   2    | 2011-1-1 | 10  |  Y
   3    | 2006-1-1 | 10  |  Y
   4    | 2011-1-1 | 20  |  Y
   5    | 2002-1-1 | 20  |  Y
   6    | 2000-1-1 | 20  |  Y

A: Here's another way, hopefully more efficient than Dems' answer.
Test it with an index on (abc, xyz, date):
SELECT m.xyz, m.date                --- for all columns:    SELECT m.*
FROM
    ( SELECT DISTINCT xyz
      FROM  money.cash
      WHERE abc = 'Y'
    ) AS dm
  JOIN
    money.cash AS m
      ON  m.abc = 'Y'
      AND m.xyz = dm.xyz
      AND m.date >= COALESCE(
            ( SELECT im.date
              FROM  money.cash AS im
              WHERE im.abc = 'Y'
                AND im.xyz = dm.xyz
              ORDER BY im.date DESC
                LIMIT 1
                OFFSET 2                --- to get 3 latest rows per xyz
            ), DATE('1000-01-01') ) ;

If you have more than rows with same (abc, xyz, date), the query may return more than 3 rows per xyz (all tied in 3rd place will all be shown).


text:
Q: Set Variable Based on Formula Error/Value in VBA I am trying to calculate a sheet (set on manual calcs) continuously until there are no more errors. I have the following code below, but it appears that it does not recognize the variables I set, as the values for those variables are the result of a formula and not actually what is in the cell as a value. I saw another question on a somewhat related topic that used a worksheet function, but have been unable to see how I can fit it into my code. Usually if I run this process without VBA code, I do the manual calcs 5-6 times, but for the code I would like to be more accomodating. The rest of my code works, it is just this part that is messing up the process. I suppose I could just calc the sheet like I normally would on a loop for some arbitrary number of calcs, but if possible I would like it to calc only if the two errors below are present. See below for piece of code.
  Dim n As Variant
  Dim na As Variant
  n = "#N/A Requesting Data..."
  na = "#N/A Invalid Override"

  Application.ScreenUpdating = False
  Application.Calculation = xlCalculationManual

  For Each Cell In Range("AZ13:BQ82")
      If Cell.Value = n Then
          Sheet1.Calculate
      End If
  Next

  For Each Cell In Range("AZ13:BQ82")
      If Cell.Value = na Then
          Sheet1.Calculate
      End If
  Next

A: IsError is your friend
  Application.ScreenUpdating = False
  Application.Calculation = xlCalculationManual

  For Each Cell In Range("AZ13:BQ82")
      If IsError(Cell.Value) Then
          Sheet1.Calculate
      End If
  Next