text:
Q: JQuery Mobile: modifying  button data-inline="true" using CSS @media query I'd like for my buttons to only be inline in certain browser widths.
Can this be done with CSS?
Failing that, can this be done with Javascript (fire a function when screen layout changes)?

A: Yes. You can use CSS resposive design techniques with attribute selectors to affect these elements.
@media only screen and (min-width : 320px) {
    a[data-inline=true] {
        display:inline;
    }
}

A: Simply using display: inline-block actually works for me right now.


text:
Q: R function efficiency Any idea for a more efficient implementation of the following function?
prod_A_B <- function(A, B, i = NULL, j = NULL) {

  if (is.null(i) & is.null(j)) {
    A * B
  } else if (!is.null(i) & is.null(j)) {
    A[i, ] * B[i, ]
  } else if (!is.null(i) & !is.null(j)) {
    A[i, j] * B[i, j]
  }

}

In particular, would it be possible to have a cleaner implementation of the condition statements that would result in a reduced runtime?
Here are some benchmarks:
n <- 1e5
d <- 200
A <- matrix(rnorm(n*d), nrow = n, ncol = d)
B <- matrix(rnorm(n*d), nrow = n, ncol = d)

pr1 <- pr2 <- matrix(0, nrow=n, ncol =d)

tm <- microbenchmark(
  {for(i in 1:n) pr1[i,] <- prod_A_B(A, B, i)},
  {for(i in 1:n) pr2[i, ] <- A[i,] * B[i,]},
  times=100L)

print(tm)

Unit: milliseconds
       min       lq     mean   median       uq      max neval
 1164.4078 1208.348 1234.607 1224.097 1254.059 1370.098   100
  969.9961 1004.821 1036.738 1021.025 1056.182 1278.767   100

The difference is not large given the matrix sizes, but I was still wondering whether I could improve the performance a bit...
Thanks!

A: You could save some time by simplifying the logical predicates and also getting rid of multiple function calls as follows:
prod2_A_B <- function(A, B, i = NULL, j = NULL) {

  ni <- is.null(i)
  nj <- is.null(j)

  if (ni & nj) {
    A * B
  } else if (nj) { # must be !ni
    A[i, ] * B[i, ]
  } else {         # must be !ni & !nj
    A[i, j] * B[i, j]
  }

}

n <- 1e5
d <- 200
pr1 <- pr2 <- pr <- matrix(0, nrow=n, ncol =d)
A <- matrix(rnorm(n*d), nrow = n, ncol = d)
B <- matrix(rnorm(n*d), nrow = n, ncol = d)
library(microbenchmark)
tm <- microbenchmark(
  {for(i in 1:n) pr1[i,] <- prod_A_B(A, B, i)},
  {for(i in 1:n) pr2[i,] <- prod2_A_B(A, B, i)},
  {for(i in 1:n) pr[i,] <- A[i,] * B[i,]},
  times=100L)

print(tm)

Unit: milliseconds
                                           expr      min       lq     mean   median       uq      max neval cld
  {for (i in 1:n) pr1[i, ] <- prod_A_B(A, B, i)}  937.9470 944.6690 969.7894 952.2308 964.4701 1390.467   100   c
  {for (i in 1:n) pr2[i, ] <- prod2_A_B(A, B, i)} 898.6802 908.3323 929.7343 914.6826 929.4356 1211.623   100  b
  {for (i in 1:n) pr[i, ] <- A[i, ] * B[i, ]}     661.2350 666.7071 688.8127 672.6218 679.9028 1005.342   100 a

redpajama_set_name: RedPajamaStackExchange


text:
Q: Time changing potential gives rise to "force"? Imagine a charged particle inside a Faraday cage (i.e. charge on outside, zero electric field inside, but non-zero electric potential on the inside). Suppose the charge distributed on the outside of this Faraday cage is changing as a function of time. Now you have a potential on the inside of the conductor that is varying with time, but still no field.
The travelling particle will only "feel" the potential once the new information about the potential gets to the particle from the edges of the Faraday cage (I believe the electromagnetic force/interaction travels at the speed of light if I'm not mistaken). Thus, if we imagine this change in the charge distributed on the outside of the Faraday cage to be smooth, the charge will see an electric potential gradient (the potential on one side of the particle will be 'updated' to a certain value while on the other side it will not be 'updated' yet, and so will be at a different value). This potential gradient will then give rise to a force on the particle.
My question is as follows: Is this idea covered by Maxwell's equations? When I imagine this all playing out with an electron travelling straight through a spherical Faraday cage (with a changing charge amount, neglecting the time it takes for the charges to distribute themselves so as to cancel all internal fields), I imagine the electron behaving wildly, moving every which way in accordance to the changing potentials around it. However, I feel like if I this was dealt with strictly classically, the answer would be no - the electron won't feel a thing.
Also, I have thought about not neglecting the finite time it takes for the charges introduced to the outside of the cage to distribute themselves so as to cancel the field, but I don't see how that could rule out the wild behavior of the electron.

A: You should understand how potentials work and how they relate to forces. It is not as simple as saying that information travels at the speed of light. As I will show below, potential can change instantaneously everywhere (but that doesn't mean that information is traveling faster than light.
Lets begin with the Maxwell's equations:
$$
\nabla \cdot \mathbf{E} = \frac{\rho(\mathbf{x},t)}{\epsilon_o} \\
\nabla \cdot \mathbf{B} = 0 \\
\nabla \times \mathbf{E} = -\frac{\partial \mathbf{B}}{\partial t} \\
\nabla \times \mathbf{B} = \mu_o \mathbf{J} + \mu_o \epsilon_o
\frac{\partial \mathbf{E}}{\partial t}$$
Since $\nabla \cdot \mathbf{B} = 0$ we can write $\mathbf{B} = \nabla \times \mathbf{A}$ where $\mathbf{A}$ is a vector field that we name the vector potential. Using this in the third Maxwell equation we can write:
$$\nabla \times \left(\mathbf{E} +\frac{\partial \mathbf{A}}{\partial t}\right)=0$$
since we can freely exchange the curl and the partial derivative over time as they are independent. Then using the fact that the curl of a gradient is 0 we define the scalar potential V as:
$$\mathbf{E} +\frac{\partial \mathbf{A}}{\partial t} = -\nabla V \\
or\\
\mathbf{E} =-\frac{\partial \mathbf{A}}{\partial t}  -\nabla V
$$
You will notice that so far we have only used the second and third Maxwell's equations. And we have the scalar and vector potential that can give the electric and magnetic field. But the expressions for the potentials that we have obtained need prior knowledge of the fields to be evaluated. To get around this we will now use the remaining first and fourth of the Max's equations.
By doing the substitutions for $\mathbf{E}$ and $\mathbf{B}$ in terms of $\mathbf{A}$ and V in these equations we get:
$$-\nabla^2 V -\frac{\partial}{\partial t} (\nabla \cdot \mathbf{A}) = \frac{\rho}{\epsilon_o}\\
and\\
\left(\nabla^2 \mathbf{A} - \mu_o \epsilon_o \frac{\partial^2 \mathbf{A}}{\partial t^2}\right)-\nabla\left(\nabla \cdot \mathbf{A} + \mu_o \epsilon_o \frac{\partial V}{\partial t}\right) = -\mu_o \mathbf{J}
$$
So we have these two PDE's that contain all the information of Max's equations. I guess you could say that they are the integral form of Max's equations. You might be getting tired now. But don't worry, we are getting there. To solve these nasty PDE's we need to make some gauge choices.
So, before I can show you how you should think about potential due to changing charge distributions, I must talk about gauges. There is something called the gauge freedom which basically means that these PDE's don't uniquely specify the potentials. In fact you can add the gradient of any scalar valued function to the vector potential and subtract its partial time derivative from the scalar potential without changing the fields. What this entails is that you can choose the value of $\nabla \cdot \mathbf{A}$ to be equal to 0(Coulomb gauge) or $-\mu_o\epsilon_o \frac{\partial V}{\partial t}$ (Lorentz gauge) among other things(other gauges).
So lets work with Coulomb gauge because it will illustrate my point. Setting the $\nabla \cdot \mathbf{A} = 0$ in the first PDE we get:
$$\nabla^2 V = -\frac{\rho(\mathbf{x}', t)}{\epsilon_o}$$
which you can solve using Green's functions to get:
$$V(\mathbf{x},t) = \frac{1}{4 \pi \epsilon_o} \int \frac{\rho(\mathbf{x}', t)}{|\mathbf{x}'-\mathbf{x}|} d^3 \mathbf{x}'$$
So you see that the potential at $\mathbf{x}$ at time $t$ depends on the charge density at $\mathbf{x}'$ at time $t$. So, a change in the charge distribution will update the scalar potential immediately everywhere. Now, you may be worried that this will break causality. But that won't happen because the vector potential is time dependent unlike the scalar one and to calculate the field (which is the only measurable quantity) you need the vector potential. So, even though a changing charge density on the surface may affect a moving charged particle in  a Faraday cage(it doesn't block magnetic fields), one cannot really talk about gradients in the scalar potential due to time dependence as you are implying (at least in Coulomb gauge).


text:
Q: How struct variable is initialised in this code snippet of I2C controller? I'm going through the following code snippet from i2c-mpc.c I2C controller.
https://github.com/torvalds/linux/blob/master/drivers/i2c/busses/i2c-mpc.c#L144
result = wait_event_timeout(i2c->queue,(i2c->interrupt & CSR_MIF), timeout);

I wanted to know how i2c->interrupt is initialised ?
I could see
    i2c->interrupt = readb(i2c->base + MPC_I2C_SR);

Reading the status register will initialise i2c->interrupt and inside
static void mpc_i2c_start(struct mpc_i2c *i2c)
{
 /* Clear arbitration */
  writeb(0, i2c->base + MPC_I2C_SR);
/* Start with MEN */
   writeccr(i2c, CCR_MEN);
}

Zero has been written to status register and i2c->interrupt should have initialised with 0's.
But When I check the dmesg logs and could see i2c->interrupt has initialised to value 0xa2 for write operation.
Can any one point me out how 0xa2 is initialised to i2c->interrupt/how i2c->interrupt is reading the latest update value after write operation ?


text:
Q: Is it possible to underclock ram There is an application called granola for windows that can be used to underclock the cpu to consume less power.
Is there also an application that can be used to underclock the ram to consume less power when you are just using the computer to download?

A: If you have an OEM motherboard, you can underclock RAM by putting slower RAM in, in place of your standard RAM. Your motherboard will read the SPD and use the timings there.
If you have an aftermarket motherboard (such as Asus or Gigabyte), it may come with an overclocker's utility (Windows application) that allows you to change settings such as the FSB multiplier (or HT or QPI). This would allow you to run the RAM slower. There will be a small but measurable performance hit. Usually these utilities overvolt automatically for overclocking, I don't think they undervolt automatically though.
For true flexibility in undervolting/underclocking, any motherboard oriented towards overclockers should give you the functionality you need to do what you want, but you will probably find it in the BIOS setup, not in an application.

A: Yes you can underclock RAM.  The best way to do so is to use any utility that will allow you to read the SPD entries.  Look for the lowest frequency spec common to all DIMMs.  Then enter those settings manually into your BIOS.  If you're BIOS doesn't have advanced config options you can use SetFSB, FreeSFB, or a proprietary utility provided by your motherboard manufacturer.  There are probably other software packages as well.
Suggestions:

*

*you should read up about what all the timings do.  Generally timings are measured in clock cycles so increasing their value reduces energy use/performance.  There are optimum clocks, however, and going too slow will cause corruption of data so once again start with the slowest figures common to the SPD of all DIMMs.

*You can also undervolt your RAM if you're wanting to reduce energy use.  It's entirely viable, but will take some trial and error.  Not to sound like a broken record, but start with the lowest figures common to the SPD of all DIMMs.

*RAM doesn't use much energy so if energy reduction is your objective look to other parts of your system first.

A: To answer your question, no you can't underclock the RAM in realtime, RAM is constantly used and the moment you boot up it stores all information for you to use your system, if anything like the speed is changed then it'll crash the system.
Do underclock you have to tdo this through the BIOS.


text:
Q: Invalid JSON response datatable using AJAX This is my Json file:
{
"status":"success",
"offer_count":605,
"page":1,
"page_size":2000,
"offers":[ {
    "offer_id":1123125,
    "package_name":"",
    "name":"[PIN] DE Game of Thrones 3",
    "category":"mobile content",
    "description":"Flow: 3/4G: 2-click + PIN\r\nWIFI: MSISDN Input + PIN",

}
,
{
    "offer_id":1123543,
    "package_name":"",
    "name":"[PIN] DE iPhone X v2",
    "category":"mobile content",
    "description":"3/4G: 2-click + PIN\r\nWIFI: MSISDN Input + PIN",

}
}

This is my script:
$(document).ready(function() {

$('#example').DataTable( {
    dom: "Bfrtip",

    ajax: {
        url: "myurl goes here",
        type: 'GET',
        dataType: 'jsonp'
    },
    columns: [
        { data: "offers.name" },
        { data: "offers.offer_id" }

    ]

} );
} );

I am trying to populate the datatable using ajax but i am getting error of invalid JSON response. I have tried to check my json in chrome debugger but the request has no response data available. I am getting the data in console.log. How to populate the datatable with specific columns.

A: you need to wrap your JSON in an array.
you can google "json validator" and play with the file till it's correct json.

A: change datatype to JSON  dataType: 'json' and you have an error in your JSON file please check  [ ]  { }
$.get('/path/to/file', function(data) {
   var my_json = data
},'json');

A: You can try to initialize according to showing an example and define column.

*

*Make sure you have return response from backend is correct according
to DataTable

 $('#datatable').DataTable({
                proccessing: true,
                serverSide: true,
                responsive: true,
                fixedHeader: {
                    header: true,
                    headerOffset: $('.header-navbar').outerHeight()
                },
                language: {
                    search: "",
                    searchPlaceholder: "Search..."
                },
                ajax: {
                    url: "Enter Url",
                    type: 'GET'
                },
                columns: [
                    { data: "Name", title: "Name" },
                    { data: "Email", title: "Email" },
                    {
                        data: "Message", title: "Message"
                    },
                ]
            });


text:
Q: socketIO - Mapping a socket to a connection This question title was really worded incorrectly, but I have no idea how to word it. If anyone wants to edit it, please feel free.
Basically I'm trying to figure out how to get a specific instance of a player via the socket that the data came from, this is going to be used to relay movements through my server for my small 2d project. Currently I have an object that's storing all of the players by the identification number, some  people say it's an object, some say it's a hashmap implementation, some say it's an array, whatever the hell it is, I'm using it.
var connectedPlayers = {};

When a connection is created I create a new player like so:
var playerId = Math.floor(Math.random()*(50000-1+1)+1);
var userId = Math.floor(Math.random()*(50000-1+1)+1);
var player = new Player(playerId, "Guest"+userId, socket);
connectedPlayers[playerId] = player;

Obviously this is just generating random names/identification numbers for now, but that's perfectly fine, this is executed  on the socket.on('connection', function() call.
If you need to see the Player.js script it's just a basic prototype script which sends information to all players about the player logging in, this all works properly.
var playerId;

var playerName;

var socket;

var positionX, positionY;

function Player(playerId, playerName, socket) {
    this.playerId = playerId;
    this.playerName = playerName;
    this.socket = socket;
    this.positionX = 250;
    this.positionY = 250;
    socket.emit('login', { playerID: playerId, playerX: this.positionX, playerY: this.positionY, playerName: playerName});
    socket.broadcast.emit('player-connected',{ playerID: playerId, playerX: this.positionX, playerY: this.positionY, playerName: playerName} )
}

Player.prototype.getId = function() {
    return this.playerId;
};

Player.prototype.getName = function() {
    return this.playerName;
};

Player.prototype.getSocket = function() {
    return this.socket;
};

Player.prototype.getX = function() {
    return this.positionX;
};

Player.prototype.getY = function() {
    return this.positionY;
};

My problem is, I need to be able to find out which Player belongs to a socket when the data comes in, because I want to authoritatively send movements to the clients. To do this I need to not give the client any control when it comes to which playerId it contains, because if I let the client tell the server, we could have other players moving at random.
The only way I've thought of is something like this, but it doesn't seem very efficient.
for(var i in connectedPlayers) {
     if(conntectedPlayers[i].getSocket() == socket) {
          // do stuff
     }
}

EDIT: Adding the entire sockets.on('connection') due to a request from comments.
socketIO.sockets.on('connection', function(socket) {
    console.log("Connection maid.");
    socket.on('login', function(json) {
        sqlConnection.query('select * FROM Accounts', function(err, rows, fields) {
            if(err) throw err;
            for(var row in rows) {
                if(rows[row].Username == json.username) {
                    var playerId = Math.floor(Math.random()*(50000-1+1)+1);
                    var player = new Player(playerId, "Guest"+playerId, socket);
                    connectedPlayers[playerId] = player;
                }
            }
        });
    });
    socket.on('move-request', function(json) {
        socket.emit('move-request', {x: json.x, y: json.y, valid: true});
    });

});

A: You can just add one or more properties to the socket object upon connection:
socketIO.sockets.on('connection', function(socket) {
    console.log("Connection maid.");
    socket.on('login', function(json) {
        sqlConnection.query('select * FROM Accounts', function(err, rows, fields) {
            if(err) throw err;
            for(var row in rows) {
                if(rows[row].Username == json.username) {
                    var playerId = Math.floor(Math.random()*(50000-1+1)+1);
                    var player = new Player(playerId, "Guest"+playerId, socket);
                    connectedPlayers[playerId] = player;
                    // add custom properties to the socket object
                    socket.player = player;
                    socket.playerId = playerId;
                }
            }
        });
    });
    socket.on('move-request', function(json) {
        // you can access socket.playerId and socket.player here
        socket.emit('move-request', {x: json.x, y: json.y, valid: true});
    });
});

So, now anytime you get an incoming message on a socket, you then have access to the playerId and player.  In your code, when a message arrives, the socket variable for this message is in your parent scope and accessible so you can then get the player and playerId.

A: I've run into this situation a few times when storing "objects" in a C hash.  I use a 32 bit hash function specifically tailed for pointers.
I'm not sure what you could use to uniquely identify the socket instance and suggest you see what underlying fields exist for that purpose.  If you do find something that uniquely identifies the socket, you can feed that into a hash algorithm to generate a key.  Of course, you would need a hash implementation (most likely in JavaSCript from the looks of it).  I found this: http://www.timdown.co.uk/jshashtable/.
Good luck!


text:
Q: Adjoint matrix symmetric The matrix
$$
A=\left ( \begin{matrix}
1 &1  &0 \\
 0&0  &0 \\
 0&0  &0
\end{matrix} \right )$$ has
$$
\text{adj } A=\left ( \begin{matrix}
0 &0  &0 \\
 0&0  &0 \\
 0&0  &0
\end{matrix} \right ),
$$
which is symmetric. Please show an example of a non-symmetric matrix, but its adjoint is symmetric.

A: Let
$$
A = \begin{pmatrix}
1 &1  &1 \\
 0&0  &0 \\
 0&0  &0 \\
\end{pmatrix}.
$$
Then the adjugate (adjunct) of $A$ is
$$
\text{adj}(A)=
\begin{pmatrix}
0 &0  &0 \\
 0&0  &0 \\
 0&0  &0 \\
\end{pmatrix}.
$$
Thus $A$ is nonsymmetric but $\text{adj}(A)$ is symmetric.
Here is another example:
$$
B=
\begin{pmatrix}
1 &1  &0 \\
 0&0  &0 \\
 1&1  &0 \\
\end{pmatrix}
$$
 is nonsymmetric while
$$
\text{adj}(B) =
\begin{pmatrix}
0 &0  &0 \\
 0&0  &0 \\
 0&0  &0 \\
\end{pmatrix}
$$
is symmetric.


text:
Q: How to multiply matrix and vector using class Task c# How to multiply matrix by vector using class Task?
I don't understand where exactly I can use tasks in my code. Any ideas?
 public static int[] matxvecTask(int[,] mat, int[] vec) //функция умножения матрицы на вектор Task
{
    Task[] tasks = new Task[4]
    {
        new Task(() => Console.WriteLine("1")),
        new Task(() => Console.WriteLine("2")),
        new Task(() => Console.WriteLine("3")),
        new Task(() => Console.WriteLine("4"))
    };
    foreach(var t in tasks)
    {
        t.Start();
    }
    Task.WaitAll(tasks);
     int[] res = new int[mat.GetLength(0)] ;

         for (int i = 0; i < mat.GetLength(0); i++)
         {
             for (int j = 0; j < mat.GetLength(1); j++)
             {
                 res[i] += mat[i, j] * vec[j];
             }
         }

     return res;
}

A: Honestly your question is quite unclear. Anyway this code now uses a task. Make sure you use at least C# 7.1 as the used signature of the Main() method is not a valid entrypoint in previous language specifications.
internal class Program
{
    private static async Task Main(string[] args)
    {
        int[,] mat = new int[3, 3];
        int[] vec = new int[3];

        int[] result = await Task.Run(() => matxvecAsync(mat, vec));

        Console.WriteLine($"Execution of '{nameof(matxvecAsync)}()' finished");

        Console.ReadLine();
    }

    private static int[] matxvecAsync(int[,] mat, int[] vec)
    {
        int[] res = new int[mat.GetLength(0)];

        for (int i = 0; i < mat.GetLength(0); i++)
        {
            for (int j = 0; j < mat.GetLength(1); j++)
            {
                res[i] += mat[i, j] * vec[j];
            }
        }

        return res;
    }

}

If you want an answer of better quality you need to provide more information about your problem.

*

*Why do you want to use tasks?

*Do you think you would solve your actual problem with it?

*What are your requirements for this piece of code?

*Are you just curious about the TAP (Task-based asynchronous pattern)?


text:
Q: Почему скорость передвижения разная по X и Y , хотя задал одну скорость . Unity public float speedX = 10.0f, speedY = 10.0f;
public static bool triggerEnter;
float _x, _y;
Rigidbody rb;

// Start is called before the first frame update
void Start()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{

    _x = Input.GetAxis("Horizontal") * Time.fixedDeltaTime * speedX;
    _y = Input.GetAxis("Vertical") * Time.fixedDeltaTime * speedY;
    Vector3 v = new Vector3(_x, _y);

    rb.AddForce(v, ForceMode.Impulse);
    if (!Input.GetKeyUp(KeyCode.UpArrow) || !Input.GetKeyUp(KeyCode.DownArrow))
    {
        rb.velocity = new Vector3(_x, 0, 0);

    }
    if (!Input.GetKeyUp(KeyCode.LeftArrow) || !Input.GetKeyUp(KeyCode.RightArrow))
    {
        rb.velocity = new Vector3(0, _y, 0);
    }

}

A: в вашем коде каждый кадр выполняются условия:
if (!Input.GetKeyUp(KeyCode.UpArrow) || !Input.GetKeyUp(KeyCode.DownArrow))
{
    rb.velocity = new Vector3(_x, 0, 0);
}

потому, что кнопка всегда отжата (если на нее не нажимают)
таким образом, почему по оси Y скорость в 2 раза больше? просто потому, что в FixedUpdate условия "сброса" скорости стоит в конце блока.. если поменять местами условия для оси X вместо Y, то ось икс станет в 2 раза быстрее по скорости
по этому нужно быть, всегда внимательнее в по кадровом выполнении кода, если вы уж решили сбрасывать скорость до нуля таким образом, то в методе FixedUpdate лучше сделать вот так :
void FixedUpdate()
{
    _x = Input.GetAxis("Horizontal") * Time.fixedDeltaTime * speedX;
    _y = Input.GetAxis("Vertical") * Time.fixedDeltaTime * speedY;
    Vector3 v = new Vector3(_x, _y);

    rb.AddForce(v, ForceMode.Impulse);

    if (_x == 0 || _y == 0)
    {
        rb.velocity = Vector3.zero;
    }
    else
    {
        rb.velocity = Vector2.ClampMagnitude(v, 0);
    }
}

есть более рациональные способы, контролировать скорость, почитайте побольше о Rigidbody
вам так же тут понадобиться адекватно ограничить нарастающую скорость по диагонали, я просто привел very simple пример


text:
Q: auto generating images in ASP.NET MVC 3 I'm using ASP.Net with MVC 3 and trying to auto generate images. In my view I am probably going to generate anything from 1 to a 50 images (maybe more eventually) which are currently one shot throw away images. This is because they show the current results of my data, which gets updated fairly frequently and so the generated images can't be relied on for very long.
Currently I am graphing results on the fly. Users can select which results to view and how then I get the results, write the graphs to file then pick up the filenames and display them in my view, but this is not working out so well and as I do not re-use the images I would just prefer to not bother storing them at all.
So far my solution is based on the following idea Can an ASP.NET MVC controller return an Image?.
In my controller I have:
public ActionResult GetImage(GraphData GraphData)
    {
        Response.ContentType = "image/png";
        using (var ms = new MemoryStream())
        {
            var chart = GraphService.GetChart(GraphData.ResponseItems,GraphData.QuestionDisplaySetup,GraphData.QuestionCutOffs,250,250);
            chart.SaveImage(ms, ChartImageFormat.Png);
            ms.Seek(0, SeekOrigin.Begin);

            return File(ms.ToArray(), "image/png");
        }

    }

and then in the .cshtml file:
foreach (var item in @Model.GraphDataList)
{
    <img src="@Url.Action("GetImage", "Download", new { GraphData = item})" alt="" />
}

and a model:
public class GraphData
{
    public IEnumerable<ResultItem> ResultItems { get; set; }
    public ResultDisplaySetup ResultDisplaySetup { get; set; }
    public IEnumerable<ResultCutOff> ResultCutOffs { get; set; }
}

but as you probably have guessed by the question this does not work.
If I do the following in my .cshtml/view:
Html.RenderAction("GetImage", "Download", new { GraphData = filename });

Then I pickup the object in my controller action without any problems, however I can't use that in the img tag and ASP.NET MVC null model passed to controller action tells me @Url.Action can't send a complex objects.
I fell down a rabbit whole of trying to generate the serialized objects myself and write my own url builder using RouteValueDictionary and tagbuilder, which is probably possible. An example is:
Passing an object to HTML attributes
but this example is just too simple and obviously so I am as I couldn't quite get the thing working.
I have the added complication that likely the Html.RenderAction will not work on the published website because it is not at the root of the website (e.g. /whatever/MyWebSite) this is for security purposes and would be too difficult to change right now.
Anyway it seems like I am working against the framework instead of with it. Any ideas anyone?
Thanks!

A: It is not a good idea to pass complex objects in a URL.
Instead, store them in the session, pass an identifier for the object in the session in the URL, and read it from the session in the action.


text:
Q: Cache file not found in UBUNTU first time trying out ubuntu and I tried copying this tutorial on ani-cli and at the last steps it errored and showed this:
nex@LAPTOP-6CV71UKV:~/ani-cli$ ./ani-cli
./ani-cli: 145: cannot create /home/nex/.cache/ani-hsts: Directory nonexistent
nex@LAPTOP-6CV71UKV:~/ani-cli$ ```

what should I do?

A: Solved it! just needed to do:
mkdir/home/nex/.cache/


text:
Q: A non parametric clustering algorithm suitable for high dimensional data What are suitable clustering algorithms for high dimensional data, where I do not have to input a predetermined number of clusters?

A: The most common clustering technique that meets your requirements would be DBSCAN.  This finds points that are continuous by virtue of having shared nearest neighbors.  There can be any number of clusters, and they can be of any shape.  There are only two parameters to choose / enter: epsilon, a 'reachability' distance, and minpoints, the minimum number of points for the resulting set to be considered a cluster.
The problem (potentially) in high-dimensional space is the curse of dimensionality.  That is, all points can become equidistant from all other points.  Since DBSCAN uses distance directly, this could become a problem and require you to explore distances other than Euclidean or other remedies.  Note that high dimensionality does not necessitate this problem, however.  For more, see this excellent CV answer: Euclidean distance is usually not good for sparse data?


text:
Q: Apply filter to ActiveModel Serializer attributes to change the key I have a serializer for my rest API. Currently, it looks like:
class TestSerializer < ActiveModel::Serializer
    attributes :id, :name, :field_one__c, :field_two__c
end

I'm wondering if there are any ways to filter all the fields to have the __c removed when serializing, if there is a way to apply logic to ALL fields.
The case is I have a lot of fields with __c on the end, and I'd like to remove them all with a minimal amount of code on the serializer level.

A: Yes you can customize an attribute name in the serializer using the :key option:
attribute :field_one__c, key: :field_one
attribute :field_two__c, key: :field_two

You can also make any attribute conditional using :if or :unless options.
Doc: https://github.com/rails-api/active_model_serializers/blob/v0.10.6/docs/general/serializers.md#attribute

Update:
For your special case, you can hack this by defining the attributes class method before the attributes list:
class TestSerializer < ActiveModel::Serializer
  class << self
    def attributes(*attrs)
      attrs.each do |attr|
        options = {}
        options[:key] = attr.to_s[0..-4].to_sym if attr.to_s.end_with?('__c')

        attribute(attr, options)
      end
    end
  end

  attributes :id, :name, :field_one__c, :field_two__c
end

If you have multiple serializer classes with the same requirement of filtering lots of attributes, you can apply the DRY principle in your solution by creating another serializer class which will inherit from ActiveModel::Serializer. Put the above class method definition inside this new serializer and inherit all the serializers from this new one which have list of attributes with __c.
class KeyFilterSerializer < ActiveModel::Serializer
  class << self
    def attributes(*attrs)
      attrs.each do |attr|
        options = {}
        options[:key] = attr.to_s[0..-4].to_sym if attr.to_s.end_with?('__c')

        attribute(attr, options)
      end
    end
  end
end

class TestSerializer < KeyFilterSerializer
  attributes :id, :name, :field_one__c, :field_two__c
end

class AnotherTestSerializer < KeyFilterSerializer
  attributes :id, :name, :field_one__c, :field_two__c
end


text:
Q: REST API: What HTTP return code for no data found? If someone could please help settle this argument we might actually get this system finished LOL :^)
So, if you have a REST API.. for.. say.. returning patient details...
And you send in a request with a patient id...
But no patient with that patient id actually exists in the database..
What response should your API return?
 1. a 404  ?
 2. a 204  ?
 3. a 200 with something in the body to indicate no patient found..

Thanks

A: Use a 404:

404 Not Found
The server can not find the requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean
that the endpoint is valid but the resource itself does not exist.
Servers may also send this response instead of 403 to hide the
existence of a resource from an unauthorized client. This response
code is probably the most famous one due to its frequent occurrence on
the web.

From MDN Web docs https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

A:
What response should your API return?

It Depends.
Status codes are metadata in the transfer of documents over a network domain.  The status code communicates the semantics of the HTTP response to general purpose components.  For instance, it's the status code that announces to a cache whether the message body of the response is a "representation of the resource" or instead a representation of an error situation.
Rows in your database are an implementation detail; as far as REST is concerned, there doesn't have to be a database.
What REST cares about is resources, and in this case whether or not the resource has a current representation.  REST doesn't tell you what the resource model should be, or how it is implemented.  What REST does tell you (via it's standardized messages constraint, which in this case means the HTTP standard) is how to describe what's happening in the resource model.
For example, if my resource is "things to do", and everything is done, then I would normally expect a GET request for "things to do" to return a 2xx status code with a representation announcing there is nothing to do (which could be a completely empty document, or it could be a web page with an empty list of items, or a JSON document.... you get the idea).
If instead the empty result set from the database indicates that there was a spelling error in the URI, then a 404 is appropriate.
It might help to consider a boring web server, and how retrieving an empty file differs from retrieving a file that doesn't exist.
But, as before, in some resource models it might make sense to return a "default" representation in the case where there is no file.

if you have a REST API.. for.. say.. returning patient details...

Is it reasonable in the resource model to have a document that says "we have no records for this patient"?
I'm not a specialist in the domain of medical documents, but it sounds pretty reasonable to me that we might get back a document with no information.  "Here's a list of everything we've been told about this patient" and a blank list.

What response should your API return?

If you are returning a representation of an error - ie, a document that explains that the document someone asked for is missing, then you should use a 404 Not Found status code (along with other metadata indicating how long that response can be cached, etc).
If you are returning a document, you should use a 200 OK with a Content-Length header.
204 is specialized, and should not be used here.  The key distinction between 204 and 200 with Content-Length 0 is the implications for navigation.


text:
Q: Show a polyline made of Track-Coordinates by Pressing a Button in Map View | SwiftUI I want to show different tracks by pressing different buttons. I started off with trying to show the polyline for the first track by pressing a button.
If I put the "construction" of the polyline in the makeUIView function of my UI Wrapper, I can see it in the map.
However I only want to show it after pressing a button. So I put the polyline-related code in the updateUIView-function and designed the button with the help of an Observable Object class. Unfortunately it doesn't work.
Here's what I got so far (The lat1 and long1 Array are actually much longer):
import SwiftUI
import MapKit
import CoreLocation

//    MARK: ObservableObject
class MapViewModel: ObservableObject {
    @Published var didPressTrack01 = false
}

struct MapView: UIViewRepresentable {

    //    MARK: UIViewRepresentable

    @ObservedObject var viewModel: MapViewModel
    @Binding var region: MKCoordinateRegion

    let track01_lat = "49.0228176937071,49.022820134536,49.0228225788423"

    let track01_long = "8.43144629937264,8.43144455316597,8.43144281824249"

    var lat1 : [Double] {
    return track01_lat.components(separatedBy: ",").compactMap(CLLocationDegrees.init)
}

    var lon1 : [Double] {
    return track01_long.components(separatedBy: ",").compactMap(CLLocationDegrees.init)
}
    var trackCoordinates1 : [CLLocationCoordinate2D] {

    var LocationsArray = [CLLocationCoordinate2D]()
    for i in 0..<lat1.count {
        LocationsArray.append(CLLocationCoordinate2D(latitude: lat1[i], longitude: lon1[i]))
       }
    return LocationsArray
    }

    let map = MKMapView()

    ///Creating map view at startup
    func makeUIView(context: Context) -> MKMapView {
        let map = context.coordinator.mapView
        map.setRegion(region, animated: false)
        map.showsUserLocation = true

        map.delegate = context.coordinator

        return map
    }

    func updateUIView(_ view: MKMapView, context: Context) {

        if viewModel.didPressTrack01 == true {

            let polyline = MKPolyline(coordinates: trackCoordinates1, count: trackCoordinates1.count)
            map.addOverlay(polyline)
        }
    }

    ///Use class Coordinator method
    func makeCoordinator() -> Coordinator {
        return Coordinator(self)
    }

//MARK: - Core Location manager delegate
class Coordinator: NSObject, MKMapViewDelegate, CLLocationManagerDelegate {

    var parent: MapView

    init(_  parent: MapView) {
        self.parent = parent
    }

    var mapView = MKMapView()

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        if let routePolyline = overlay as? MKPolyline {
            let renderer = MKPolylineRenderer(polyline: routePolyline)
            renderer.strokeColor = UIColor.systemRed
            renderer.lineWidth = 2
            return renderer
        }
        return MKOverlayRenderer()
    }
}

// MARK: View that shows map to users
struct Tap_Map_View: View {

    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude:20.02281, longitude: 8.43188), latitudinalMeters: 180, longitudinalMeters: 180)
    @StateObject var viewModel = MapViewModel()

    var body: some View {

        ZStack(alignment: .bottom){
            MapView(viewModel: viewModel, region: $region)

                Button {

                    viewModel.didPressTrack01.toggle()

                } label: {
                    Label("", systemImage: "point.topleft.down.curvedto.point.bottomright.up")

                    }
            }
      }
}


text:
Q: Mutable wrapper of value types to pass into iterators I'm writing an iterator that needs to pass around a mutable integer.
public IEnumerable<T> Foo(ref int valueThatMeansSomething)
{
    // Stuff

    yield return ...;
}

This nets me "Error 476  Iterators cannot have ref or out parameters".
What I need is this integer value to be modified in the iterator and usable by the caller of the iterator.  In other words, whatever calls Foo() above wants to know the end value of valueThatMeansSomething and Foo() may use it itself.  Really, I want an integer that is a reference type not a value type.
Only thing I can think of is to write a class that encapsulates my integer and permits me to modify it.
public class ValueWrapper<T>
    where T : struct
{
    public ValueWrapper(T item)
    {
        this.Item = item;
    }

    public T Item { get; set; }
}

So:
ValueWrapper<int> w = new ValueWrapper<int>(0);
foreach(T item in Foo(w))
{
    // Do stuff
}

if (w.Item < 0) { /* Do stuff */ }

Is there any class or mechanism to handle this already in the BCL? Any flaws with ValueWrapper<T> proposed above?
(My actual use is more complicated than the example above so handling the variable inside my foreach loop that calls Foo() is not an option.  Period.)

A: If you only need to write the value then another technique would be:
public IEnumerable<whatever> Foo(Action<int> setter) { ... }

int value = 0;
foreach(var x in Foo(x => {value=x;}) { ... }

Coincidentally, I'll be doing a series on the reasons why there are so many goofy restrictions on iterator blocks in my blog in July. "Why no ref parameters?" will be early in the series.
http://blogs.msdn.com/ericlippert/archive/tags/Iterators/default.aspx

A: Nope, I'm pretty confident there's nothing existing in the BCL that can do this. Your best option is precisely what you have proposed I think. The implementation of ValueWrapper really need not be any more complicated than what you have proposed.
Of course, it's not guaranteed to be thread-safe, but if you need that you can simply convert the automatic property into a standard one with a backing variable and mark the field as volatile (to insure the value is up-to-date at all times).

A: I have long thought that the BCL really should have a class and interface something like the following:

public delegate void ActByRef<T1,T2>(ref T1 p1);
public delegate void ActByRefRef<T1,T2>(ref T1 p1, ref T2 p2);
public interface IReadWriteActUpon<T>
{
  T Value {get; set;}
  void ActUpon(ActByRef<T> proc);
  void ActUpon<TExtraParam>(ActByRefRef<T, TExtraParam> proc,
                           ref TExtraparam ExtraParam);
}

public sealed class MutableWrapper<T> : IReadWrite<T>
{
  public T Value;
  public MutableWrapper(T value) { this.Value = value; }
  T IReadWriteActUpon<T>.Value {get {return this.Value;} set {this.Value = value;} }
  public void ActUpon(ActByRef<T> proc)
  {
    proc(ref Value);
  }
  public void ActUpon<TExtraParam>(ActByRefRef<T, TExtraParam> proc,
                           ref TExtraparam ExtraParam)
  {
    proc(ref Value, ref ExtraParam);
  }
}

Although many people instinctively wrap fields in auto-properties, fields often allow cleaner and more efficient code especially when using value types.  In many situations, the increased encapsulation one can gain by using properties may be worth the cost in efficient and semantics, but when the whole purpose of a type is to be a class object whose state is completely exposed and mutable, such encapsulation is counterproductive.
The interface is included not because many users of a MutableWrapper<T> would want to use the interface instead, but rather because an IReadWriteActUpon<T> could be useful in a variety of situations, some of which would entail encapsulation, and someone who has an instance of MutableWrapper<T> might wish to pass it to code which is designed to work with data encapsulated in an IReadWriteActUpon<T> interface.


text:
Q: Create-react-app ServiceWorker broken in Chrome Create-react-app ServiceWorker does not work in Chrome. White page with source code is shown when refreshing the browser. See screenshot below. This problem does not exist in Safari and Firefox.
Steps to reproduce:

*

*create-react-app foo

*cd foo

*npm install

*change serviceWorker.unregister() to serviceWorker.register() in index.js

*npm run build

*serve -s build

*open http://localhost:5000 (or whatever port number is shown) in Chrome.

*refresh browser after you see spinning react logo

*now white page with source code is shown instead (see screenshot below)

Do you get the same or is it just my Chrome? Any idea what causes this problem?


text:
Q: Hosted Exchange 2010 Send As I have a hosted exchange 2010 and I am trying to setup the Send-As permission.
I am following the Manage Send As Permissions for a Mailbox Technet article, which basically describes the commands for achieving this.
I have user accounts aaa and bbb
[PS] C:\Windows\system32>get-mailbox -organization myorg -identity "aaa"
Name                      Alias                ServerName       ProhibitSendQuota
----                      -----                ----------       -----------------
aaa                       aaa                  mx1  4.95 GB (5,315,022,848 bytes)

[PS] C:\Windows\system32>get-mailbox -organization myorg-identity "bbb"
Name                      Alias                ServerName       ProhibitSendQuota
----                      -----                ----------       -----------------
bbb                       bbb                  mx1  4.95 GB (5,315,022,848 bytes)

Now, when I use the command below to give bbb permission to send-as aaa, I get the following error:
[PS] C:\Windows\system32>get-mailbox -organization myorg -identity "aaa" | Add-ADPermission -Extended Rights "Send As" -user "bbb"

mx1/Microsoft Exchange Hosted Organizations/myorg/aaa wasn't found.
Please make sure you've typed it correctly.
    + CategoryInfo          : InvalidArgument: (:) [Add-ADPermission], ManagementObjectNotFoundException
    + FullyQualifiedErrorId : D2FD338,Microsoft.Exchange.Management.RecipientTasks.AddADPermission

The error message that aaa was not found does not make sense, because I just retrieved the mailbox in the previous commands.
I have tried using email addresses instead of alias as well, but that does not work either.

A: Reading further I found the answer to be partially from
http://technet.microsoft.com/en-us/library/ff935839.aspx
It appears that I have to use a different command which does the same thing:
Add-RecipientPermission "Help Desk" -AccessRights SendAs -Trustee "Ayla Kol"
but in my case, I had to specify the whole organisation etc
Add-RecipientPermission "domain/Microsof Exchange Hosted Organizations/myOrHelp Desk" -AccessRights SendAs -Trustee "Ayla Kol"


text:
Q: Run time error using cv::imwrite in OpenCV I am using OpenCV 2.3.1.  My language is C++.
cv::imwrite works fine if I hard code the name of the output file like this.
cv::imwrite("/home/peter/BlendedInterpolatedPlane.jpg", srcnorm);

However, I get a run time error when I try to pass the output file name as a string like this.
cv::imwrite(outputFileName.c_str(), srcnorm);

or like this
cv::imwrite(outputFileName, srcnorm);

although there is no compiler error.
outputFileName is declared as std::string and contains the output file name.
The stack trace is as follows.
org.netbeans.modules.viewmodel.TreeModelNode@1999add[Name=, displayName=__kernel_vsyscall()]
org.netbeans.modules.viewmodel.TreeModelNode@186304c[Name=, displayName=raise()]
org.netbeans.modules.viewmodel.TreeModelNode@cce801[Name=, displayName=abort()]
org.netbeans.modules.viewmodel.TreeModelNode@93b1a8[Name=, displayName=__gnu_cxx::__verbose_terminate_handler()()]
org.netbeans.modules.viewmodel.TreeModelNode@749412[Name=, displayName=Address: [@0x00554fa5]]
org.netbeans.modules.viewmodel.TreeModelNode@1a52b00[Name=, displayName=std::terminate()()]
org.netbeans.modules.viewmodel.TreeModelNode@aa277d[Name=, displayName=__cxa_throw()]
org.netbeans.modules.viewmodel.TreeModelNode@106904c[Name=, displayName=cv::error(cv::Exception const&)()]
org.netbeans.modules.viewmodel.TreeModelNode@1eb6f21[Name=, displayName=cv::imwrite_(std::basic_string<char, std::char_traits<char>,   std::allocator<char> > const&, cv::Mat const&, std::vector<int, std::allocator<int> > const&, bool)()]
org.netbeans.modules.viewmodel.TreeModelNode@1ccf1f3[Name=, displayName=cv::imwrite(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, cv::_InputArray const&, std::vector<int, std::allocator<int> > const&)()]
org.netbeans.modules.viewmodel.TreeModelNode@20a41d[Name=, displayName=main(argc=9,argv=0xbffff564) at main.cpp:259]

Any assistance would be greatly appreciated,
Peter

A: I found the problem.  The output file name had an invalid suffix.  Once I fixed that problem, it worked with
cv::imwrite(outputFileName, srcnorm);

where outputFileName is of type std::string.


text:
Q: how to implement zmsg_recv_nowait? CZMQ library provide nowait option for zstr and zframe classes(zstr_recv_nowait() and zframe_recv_nowait()), but there is nothing like zmsg_recv_nowait(). Is there any solution? Instead of using zmq_msg_recv with ZMQ_DONTWAIT flag. My code is:
zmq_pollitem_t items[] = { {sock, 0, ZMQ_POLLIN, 0} };
zmq_poll(items, 1, 10);
/* now receive all pending messages */
while (1) {
    zmsg_t *msg = zmsg_recv(sock); /* this will block after the last message received */
    /* consume message here */
}
/* sending bunch of messages */

I'm doing asynchronous REQ/REP. Sending multiple requests then receive replies when they are ready. This code will block my application. Also it seems ugly to me to do one zmq_poll, receive one message and so on... because by the time zmq_poll returns, other replies had been arrived.

A: Put the poll codes into the loop. Using poll for one socket is fine.
an example may help:
while (1) {
    /* now receive all pending messages */
    zmq_pollitem_t items[] = { {sock, 0, ZMQ_POLLIN, 0} };

    /* this will block for 10msec, ZMQ_POLL_MSEC is for compatibility for v2.2 */
    int rc = zmq_poll(items, 1, 10 * ZMQ_POLL_MSEC );
    if (rc == -1)
      break; // some error occured, check errno...

    if (items [0].revents & ZMQ_POLLIN) {
      /* there's something to receive */
      zmsg_t *msg = zmsg_recv(sock);
    }

    /* sending bunch of messages */
}


text:
Q: Git reverting back git log says
commit 2bf345e15dadba9f2e01ef2e0c3890d6cbab1153
Merge: d3b6ba8 aa94bf7
Author: Stack Overflow User <user@stackoverflow.com>
Date:   Tue Feb 14 01:00:48 2012 -0500

    Merge branch 'master' of bitbucket.org:hobbes3/scoutmob

commit d3b6ba8f1d57c530c2d8ab9bb879fcac67d3de35
Author: Stack Overflow User <user@stackoverflow.com>
Date:   Tue Feb 14 00:59:37 2012 -0500

    Revert "Added image info window"

    This reverts commit fad04be93334647d1b1e3b4d454a70819213ecac.

commit d119c3961da515c0cb2c6c9154003e52846cf848
Author: Stack Overflow User <user@stackoverflow.com>
Date:   Tue Feb 14 00:22:56 2012 -0500

    Revert "Moved some files around to combine the common folder between scoutmob and ajax-example"

    This reverts commit 845f8d52c3655f3cf6b03da057281e5fb303721c.

commit aa94bf75fb064c6fe521501765d86c894aa5b436
Author: Another user <user_two@stackoverflow.com>
Date:   Sat Feb 11 10:42:03 2012 -0500

    removing .txt

commit b633d23a5b10ad7531855905d6f41897ce6726ad
Author: Another user <user_two@stackoverflow.com>
Date:   Sat Feb 11 10:40:04 2012 -0500

    testing data import

commit fad04be93334647d1b1e3b4d454a70819213ecac
Author: Stack Overflow User <user@stackoverflow.com>
Date:   Sat Feb 11 03:55:54 2012 -0500

    Added image info window

commit 51f9cc7cd19f15540ac2631168a0a91c03a30139
Author: Stack Overflow User <user@stackoverflow.com>
Date:   Tue Feb 7 22:29:58 2012 -0500

    Added deal info to the info window of the marker.

....

commit 845f8d52c3655f3cf6b03da057281e5fb303721c
Author: Stack Overflow User <user@stackoverflow.com>
Date:   Tue Jan 31 10:42:21 2012 -0500

    Moved some files around to combine the common folder between scoutmob and ajax-example

'git status' says
# On branch master
# Your branch is ahead of 'origin/master' by 3 commits.
#
nothing to commit (working directory clean)

git branch -rv says
origin/HEAD    -> origin/master
origin/master  aa94bf7 removing .txt
origin/working cb65aef My location now works. Will work on the graphics next.

A couple of days ago my master branch was at the most current commit at fad04be. Then I decided that I wanted to temporary look at my old code. So I reverted back by using git revert 845f8d5.
In hindsight, I realized I should have checked out a new branch first. Then I tried to go back by using git revert 'fad04be. When I ran git status it said something like Your branch is ahead of 'origin/master' by 1 commit.
So next I tried to git pull from the remote repository to revert my current code back, and now I'm all confused.
I just want both my local and remote repository to be on commit fad04be. What did I do wrong and what can I do?

A: NOTE: before you follow any of my advice, make a full copy of your directory. That way you can always get back to the current situation
As ouah mentions indeed, your master should now be exactly what you want it to be, with two extra commits, namely the reverts of 845f8d5 and fad04be.
You can do 2 things now. If you didn't push anything to the remote yet, you can put the master pointer back to fad04be by
git reset --HARD fad04be

Alternatively if you already pushed something to the remote or someone else, you can revert the reverts. If you do a git log, you will see the two most recent commits being the reverts of 845f8d5 and fad04be. You can revert those reverts, by doing
git revert <commit-id-of-revert>

Next time you want to see an old revision, indeed use:
git checkout <revision-id>

Don't forget to do a
git checkout master

when you're done. If you change and commit stuff without doing this, your commits will go somewhere but not in the master branch (git will complain about being in a detached head state, but this warning is easy to miss -- trust me, I've been there :))
Too see an old revision, there is no need to create another branch first.

A: A git revert is actually a commit that just undoes the prior commit. I take it the pull didn't do anything? You should only need to push the revert.

A: Use git checkout <commit-id> to take a quick look to a commit. git revert <commit-id> will revert the single commit <commit-id> by adding a new commit.


text:
Q: Is there a direct way of addressing a 2D char array and store strings on them in C I want to know whether is there a direct way of addressing a 2D char array and store strings on it.
And I know that by using malloc, I could dynamically allocate memory to strings for example for   char * names[number] I can malloc (char *)malloc(50*sizeof(char)) and get it done.
And also I know that by using a for loop and assigning each and every element you can achieve the same.
I found it through this similar question here .
but my case is ,Is there a way to use array name and indexes to store strings directly.It should look something like this. down here is not a popper code and I just wanted to show how it should look like  (from the link I mentioned above)
char arrayOfWords[NUMBER_OF_WORDS][MAX_SIZE_OF_WORD];

int i;`
for (i=0; i<NUMBER_OF_WORDS; i++) {
    arrayOfWords[i] = "laksith"; //here I need to use a way like arrayOfWords+1 etc.
}

I think you may have got the idea of what I'm saying.

A: Sure you can. But in this case you need to use strcpy instead of the assignment operator:
for (i=0; i<NUMBER_OF_WORDS; i++) {
    strcpy(arrayOfWords[i], "laksith"); //here I need to use a way like arrayOfWords+1 etc.
}

UPD: As @PaulR noted in the comment above, strncpy is a way better option. But first you need to read notes in this link (how to properly handle the missing null byte).


text:
Q: User to input an hour time period with an option of 24 hour or 12 hour type representation I am trying to think of the best way for a user to input a start hour an end hour but I need to be able to support both AM/PM and 24 hour time representation. Currently I was thinking of a drop down list with AM, PM, and Military to distinguish each time but since this is a page for time sheets that would mean 56 drop down lists and that sounds TERRIBLE
Do you have suggestions on how to do this ? Is there a javascript time picker that already does this ?

A: There's a box where you can type the hour and grayed-out AM/PM dropdown/radio button set. If the user types in a number less than 13 in both boxes, the AM/PM chooser activates and is required. If they enter a number greater than 12 in either box, it doesn't.


text:
Q: Azure App Service authorization/easy auth is conflicting ASP.NET Forms auth I want to enable App Service Authentication to protect development environment from public access.
The App Service authentication itself is working fine, only people from our company Azure AD are allowed, all good.
But it is conflicting with the authentication of the website itself, after authenticating through Azure AD the website sees you as you are already logged in.
And I don't understand how exactly it ends up conflicting, we are using Forms authentication, I've tried explicitly naming the cookie that forms auth should look for, and setting it to always use cookies for authentication, yet it's still conflicting.
 <authentication mode="Forms">
      <forms name=".ASPXAUTH" loginUrl="~/sign-in" timeout="2880" requireSSL="true" cookieless="UseCookies" />
 </authentication>

After logging in through microsoft, I see there's no .ASPXAUTH cookie, only AppServiceAuthSession, yet Forms auth sees me as logged in.

A: I think you can solve this by removing the auth setting in web.config and use OWIN to inject a middleware (CustomMiddleware) before Authentication of the website itself. If user is authenticated by your CustomMiddleware, you carry on with your regular flow otherwise short circuit the request flow. In CustomMiddleware you can inspect the request headers, body etc to have authenticated cookie etc. I guess you have MVC style pipeline in your application. There are number of resources on internet which you can explore. One example is below.
https://www.tutorialsteacher.com/core/how-to-add-custom-middleware-aspnet-core


text:
Q: Is it possible to create an audio recorder in Javascript? I would like to create a javascript app that record the microphone input and saves it to a file, in javascript, without flash and without java
is it possible ?

A: Yes, it is definitely possible, although if you want to save the file to the client's local file system it will only work in Chromium/Chrome (you will need to use the File System API, which has since been abandoned by other browser vendors).
You'll need to leverage the Web Audio and WebRTC APIs. Here's a tutorial that shows the basics: http://www.html5rocks.com/en/tutorials/getusermedia/intro/


text:
Q: Set MasSessions to SSH does not take effect I got a server with enabled ssh. To prevent attacks and to fit to my needs, I just need one connection at the same time to my server. So, I tried to set MaxSessions paramater to 1 in /etc/ssh/sshd_config, restartet the daemon and it does not take effect. My server uses openSUSE 13.2

A: The MaxSessions parameter limits the number of multiplexed sessions you have on a single ssh session.
Session multiplexing allows to setup a single Master connection which all other connections to the same host can then reuse. This has no effect on the ability to connect again to the same host via a new network connection.
SSH has no way to limit or control multiple connections coming from different IP addresses.
You will need to use /etc/security/limits.conf so each user is limited to 1 session. Something like this:
userid  - maxlogins  1


text:
Q: How can I create a 'generic' control in Asp.Net MVC Razor? I'm trying to write a generic (meaning useful in many places) control that I can reuse throughout my company.
I'm having problems with actual C# generics in my view and viewmodel.
Here is an example of what I'm trying to do:
Generic partial view: (_Control.cshtml)
@model SimpleExample<dynamic>

@Model.HtmlTemplate(Model.Data)

ViewData: (SimpleExample.cs)
public class SimpleExample<T>
{
    public T Data;
    public Func<T, System.Web.WebPages.HelperResult> HtmlTemplate;
}

Example usage: (FullView.cshtml)
@model Foo.MyViewData

@Html.Partial("_Control", new SimpleExample<MyViewData>
{
    Data = Model,
    HtmlTemplate = @<div>@item.SomeProperty</div>
})

The important part of the functionality I'm looking for is that consumers get a typed object when writing their Html inline so they can use Intellisense (as in FullView.cshtml).
Everything compiles fine and the intellisense is working, but I'm getting the error an runtime:
The model item passed into the dictionary is of type
'AnytimeHealth.Web.ViewData.SimpleExample`1[Foo.MyViewData]',
but this dictionary requires a model item of type
'AnytimeHealth.Web.ViewData.SimpleExample`1[System.Object]'.

I've read that I might be able to use covarience on my generic type to get this to work, but I'm not sure how to do that.
Could you please instruct me how I can get this working?

A: Change the define in _Control.cshtml:
@model SimpleExample<dynamic> to @model dynamic.
It will work, but will lose the intellisense of SimpleExample, the intellisense of MyViewData will still work.
I think it's because the dynamic type will be known in runtime, but the type of generics
require an early time(maybe is compile time), at that point, only object is be known.

A: You could use a generic Object and then, using reflection, render the properties of this object (using an helper to list the properties). This is the same approach used by Twitter Bootstrap for MVC 4 (from wich part of this code has been copied, for convenience) : http://nuget.org/packages/twitter.bootstrap.mvc4
_Control.cshtml
@model Object
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>@Model.GetLabel()</legend>
        @foreach (var property in Model.VisibleProperties())
        {
            using(Html.ControlGroupFor(property.Name)){
                @Html.Label(property.Name)
                @Html.Editor(property.Name)
                @Html.ValidationMessage(property.Name, null)
            }
        }
        <button type="submit">Submit</button>
    </fieldset>
}

Helper.cs
public static string GetLabel(this PropertyInfo propertyInfo)
{
    var meta = ModelMetadataProviders.Current.GetMetadataForProperty(null, propertyInfo.DeclaringType, propertyInfo.Name);
    return meta.GetDisplayName();
}

public static PropertyInfo[] VisibleProperties(this IEnumerable Model)
{
    var elementType = Model.GetType().GetElementType();
    if (elementType == null)
    {
        elementType = Model.GetType().GetGenericArguments()[0];
    }
    return elementType.GetProperties().Where(info => info.Name != elementType.IdentifierPropertyName()).ToArray();
}

public static PropertyInfo[] VisibleProperties(this Object model)
{
    return model.GetType().GetProperties().Where(info => info.Name != model.IdentifierPropertyName()).ToArray();
}


text:
Q: how to package only default language with android gradle resConfigs I know how to restrict language support using resConfigs :
defaultConfig {
    ...
    resConfig "en"
}

But how to restrict language to support only the default one (in values/ folder) ? Is there a way to avoid packaging any language resources stored in values-xx/ folders ?
Thanks

A: The configuration probably should rather be (tested with Gradle 6.1.1):
android {
    sourceSets {
        main {
            res {
                exclude "**/values-de/*.xml"
                exclude "**/values-he/*.xml"
            }
        }
    }
}

One needs one line per language tag, because of all the other directories matching values-*.
And to check which resources are actually being packaged:
sourceSets.main.res.getExcludes().each { println "Found exclude: $it" }
sourceSets.main.res.sourceFiles.each { println "File in source set: " + it }

For regular Java projects, this would be directory resources instead of the Android-specific res.

A: You can do this by  specifying the exclude on the filter field:
android {
    sourceSets.main.res.filter.exclude '**/values/whatever.xml'
}

A: You can do this.
sourceSets.getByName("main") {
    res.exclude("**/values-**/*.xml")
}


text:
Q: How to check status of one port on remote host using NSClient++? I know I could check for telnet on a known IP using other programs like:
nmap -A 192.168.0.1/32 -p 23

Or, look for open ports from 20 to 30 on host.example.com:
nc -z host.example.com 20-30

I need to create a batch file, since I think that is how NSClient++ works on Windows Server being monitored by Nagios. Currently I have CPU, Disk, Memory, NSClient, and PING being monitored but I need a Specific port that I can also Monitor.

A: Assuming you have a monitored Windows server, and you want to check to see if it has connectivity to a remote machine, I would recommend the following:
Use this PowerShell code (or one much like it) to write a script that checks a remote port.
Then set up the CheckExternalScripts module to run and interpret the output of the PowerShell script.


text:
Q: How to change part of function inside a class in python? I would like to change a class sklearn.mixture.GaussianMixture to compute GMM with fixed means. In this github repository the function is stored, I assume it would be enough to change that means_ will not be computed in _m_step function within the class sklearn.mixture.GaussianMixture , but instead the values provided as initial values for means, i.e. mean_init parameter of the class would be used as fixed means. How to achieve this? I have tried changing it by heart by copy-paste the class and changing the part inside the function, but I can not overcome that there are dependencies which I can not load... Is it possible to change it from outside somehow?
So this is what I have tried, but I am not able to make it running:
import sklearn
def new_m_step(self, X, log_resp):
    sklearn.mixture.GaussianMixture._m_step(self, X, log_resp)
    self.means_ = self.means_init

my_gmm = sklearn.mixture.gaussian_mixture.GaussianMixture()
#my_gmm._m_step =  types.MethodType(new_m_step, my_gmm) # alternative which has the same error
my_gmm._m_step = new_m_step.__get__(my_gmm, sklearn.mixture.gaussian_mixture.GaussianMixture)

and I get this error:
TypeError: 'GaussianMixture' object is not callable

A: Ok, so I finally solved it in this way:
from skleran.mixture import GaussianMixture
class My_GMM(GaussianMixture):
    def _m_step(self, X, log_resp):
        GaussianMixture._m_step(self, X, log_resp)
        self.means_ = self.means_init

and the original class is not overwritten within the script. If anyone has any better solution feel free to add it. If you feel the question is duplicate, vote for closing, however I did not understand from the post mentioned in comments how to add something to function inside a class, so maybe I am not alone and will leave it here.


text:
Q: Getting a response from a php script call I have an app that sends some information via POST to a php script in a server. It uses Asynchttpclient. How can I also receive a reply back from the server (via json?)? Please help.
This is my php script
if($_POST["mode"]=="newuser"){
            //$gcmRegID  = $_GET["shareRegId"];
            $gcmRegID  = $_POST["regID"];
            $gcmUserName  = $_POST["userName"];
            $gcmFolderName = $_POST["folderName"];

            $gcmDate = date("d/m/y");

            $conn = new mysqli($servername, $username, $password, $dbname);
            if($conn->connect_error){
                die("Connection failed: " . $conn->connect_error);
            }
            $in_user = "user";
            $in_password = "NULL";
            $in_email = "NULL";
            $in_dob = "NULL";
            $in_role = "user";
            $in_datejoined = "0000-00-00";
            $foldername = "NULL";

            $sql = "INSERT INTO user(password,regid,name,email,phone,dob,role,datejoined,foldername) VALUES('$in_password','$gcmRegID','$gcmUserName','$in_email','$in_phone','$in_dob','$in_role','$gcmDate','$foldername')";

            $substringtitle = substr($gcmRegID,-7);
            $combined = $gcmUserName."_".$substringtitle;
            if($conn->query($sql)===TRUE){
                    mkdir("./users/".$gcmFolderName);
                    $newfoldername = "./users/".$gcmFolderName;
                    $updatequery = "UPDATE user SET foldername='$newfoldername' WHERE name='$gcmUserName'";

                     $returnfield = array(
                        'foldername' => $newfoldername
                    );
                    header('Content-type: application/json');
                    echo json_encode(array('returnfield'=>$returnfield));

                    if($conn->query($updatequery)===TRUE){
                        echo "folder updated";
                    }
                    //echo "Folder created!";
                //}
                echo "New record created successfully";

            }else{
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
            $conn->close();

            echo "Done!";
            exit;
        }

Android code
 //store in the file server (PHP)
private void storeREG(final String registerID,String userName,String folderName){

    pg.show();
    params.put("regID", registerID);
    params.put("userName",userName);
    params.put("folderName", folderName);
    params.put("mode","newuser");
    Log.d("STORE","STORE");
    //Make RESTful webservice call

    AsyncHttpClient client = new AsyncHttpClient();
    client.post(AppConstants.SERVER_URL, params, new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(String content) {
            pg.hide();
            if (pg != null) {
                pg.dismiss();
            }

            Toast.makeText(applicationCtx, "ID sharing successful", Toast.LENGTH_LONG).show();
            Intent home = new Intent(applicationCtx, HomeActivity.class);
            home.putExtra("regID", registerID);
            Log.d("REGID", registerID);
            startActivity(home);
            finish();
        }

        @Override
        public void onFailure(int statusCode, Throwable error, String content) {
            pg.hide();
            if (pg != null) {
                pg.dismiss();
            }
            Log.d("ERRORTHROW", error.toString());
            if (statusCode == 404) {
                Toast.makeText(applicationCtx, "Requested resource not found", Toast.LENGTH_LONG).show();
            } else if (statusCode == 500) {
                Toast.makeText(applicationCtx, "Something went wrong at the server", Toast.LENGTH_LONG).show();
            } else {
                Log.d("SHOWME", String.valueOf(statusCode));
                Toast.makeText(applicationCtx, "Unexpected error occurred", Toast.LENGTH_LONG).show();
            }
        }

    });

}

Hopefully I can get help with this.

A: I can't test the code right now (sorry), but I think it should be something like this:
try {
    RequestParams rParams = new RequestParams();
    rParams.put("example", "example"); // POST
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(pageURL, rParams, new JsonHttpResponseHandler() {

        @Override
        public void onSuccess(JSONArray jsonArray) {
            super.onSuccess(jsonArray);

            //process JSON Array

        }

        @Override
        public void onFailure(Throwable throwable, JSONArray jsonArray) {
            super.onFailure(throwable, jsonArray);
            Log.d(TAG, "error", throwable);
        }

    });
} catch (Exception e) {
    Log.d(TAG, "exception", e);
}

Otherwise I made a very light WebClient, you may want to give it a shot:
https://github.com/omaflak/WebClient
This is a short sample:
WebClient client = new WebClient();
client.setOnRequestListener(new OnRequestListener() {
        @Override
        public void onRequest(String response, int requestID) {
            Log.e(TAG, response);
        }

        @Override
        public void onError(int error_code, String message) {
            Log.e(TAG, message);
        }
});

Pair p = new Pair("field1", "value1");
Pair p2 = new Pair("field2", "value2");
client.requestAsync("http://your-api.com", WebClient.POST, Arrays.asList(p, p2), 1);

//  requestAsync(String url, String method, List<Pair<String, String>> postData, int requestID)

To use it, simply add to your dependencies:
compile 'me.aflak.libraries:webclient:1.0'

A: You may try to revise your PHP Code. Below is a well-commented sample code to get you started:
    <?php
        // EXPLICITLY INSTRUCT THE HEADER ABOUT THE CONTENT TYPE. HERE - JSON
        header('Content-type: application/json');

        if($_POST["mode"]=="newuser"){
            $gcmRegID       = htmlspecialchars(trim($_POST["regID"]));
            $gcmUserName    = htmlspecialchars(trim($_POST["userName"]));
            $gcmFolderName  = htmlspecialchars(trim($_POST["folderName"]));
            $gcmDate        = date("d/m/y");

            // I WOULD STRONGLY SUGGEST YOU USE PDO FOR YOUR DATABASE TRANSACTIONS:
            // HERE'S HOW:

            //DATABASE CONNECTION CONFIGURATION:
            defined("HOST")     or define("HOST",   "localhost");           //REPLACE WITH YOUR DB-HOST
            defined("DBASE")    or define("DBASE",  "database");            //REPLACE WITH YOUR DB NAME
            defined("USER")     or define("USER",   "root");                //REPLACE WITH YOUR DB-USER
            defined("PASS")     or define("PASS",   "root");                //REPLACE WITH YOUR DB-PASS

            // ESTABLISH A CONNECTION AND DO YOUR WORK WITHIN A TRY-CATCH BLOCK...
            try {
                $dbh        = new PDO('mysql:host='.HOST.';dbname='. DBASE,USER,PASS);
                $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                // HERE: ALL YOUR BUSINESS LOGIC...
                $in_user        = "user";
                $in_password    = "NULL";
                $in_email       = "NULL";
                $in_phone       = "NULL";
                $in_dob         = "NULL";
                $in_role        = "user";
                $in_dateJoined  = "0000-00-00";
                $folderName     = "NULL";

                $insertSQL      = "INSERT INTO user(`password`, `regid`, `name`, `email`, `phone`, `dob`, `role`, `datejoined`, `foldername`) ";
                $insertSQL     .= " VALUES(:inPassword, :gcmRegID, :gcmUserName, :inEmail, :inPhone, :inDOB, :inRole, :gcmDate, :folderName)";

                $arrInsertData  = array(
                    'inPassword'    => $in_password,
                    'gcmRegID'      => $gcmRegID,
                    'gcmUserName'   => $gcmUserName,
                    'inEmail'       => $in_email,
                    'inPhone'       => $in_phone,
                    'inDOB'         => $in_dob,
                    'inRole'        => $in_role,
                    'gcmDate'       => $gcmDate,
                    'folderName'    => $folderName
                );

                // PREPARE THE INSERT QUERY:
                $insertStmt = $dbh->prepare($insertSQL);

                // INSERT THE NEW ROW:
                $insertStmt->execute($arrInsertData);

                // OBTAIN THE ID OF THE INSERTED ROW TO BE USED AS SUFFIX FOR YOUR USER FOLDER
                $id         = $dbh->lastInsertId();

                // WHAT HAPPENS WHEN 2 USERS HAVE THE SAME USERNAME??? DID YOU THINK ABOUT THAT?
                // TO CIRCUMVENT THIS ISSUE; I WOULD SUGGEST FIRST TO INSERT THE DATA TO THE DATABASE...
                // THEN USE THE ID AS A SUFFIX TO MAKE EACH USER DIRECTORY UNIQUE & THAT IS THE APPROACH TAKEN HERE THOUGH...

                // NOW YOU CAN CREATE YOUR FOLDER USING THIS ID: $id
                // LIKE THIS; 2 USERS WITH USERNAME "android_user" CAN HAVE 2 DIFFERENT FOLDERS LIKE SO: "android_user_97" & "android_user_102"
                $userDirectory  = "./users/" . $gcmFolderName . "_" . $id;
                mkdir($userDirectory);

                // DID IT OCCUR TO YOU THAT 2 USERS MIGHT HAVE THE SAME USERNAME IN WHICH CASE MYSQL (INSTEAD OF YOU) HAS TO DECIDE WHICH USER TO UPDATE?
                // THAT IS WHY DATABASE TABLES ARE DESIGNED TO HAVE UNIQUE IDENTIFIERS LIKE UUID OR ID OR UID OR ANY TOKEN TO MAKE EACH ROW UNIQUE...
                // WE ARE ADOPTING THIS APPROACH IN THE UPDATE QUERY... THAT IS: WE UPDATE THE ROW USING THE ID ABOVE... ASSUMING THAT IS A UNIQUE COLUMN THOUGH.
                $updateSQL      = "UPDATE user SET foldername=:newDirName WHERE id=:ID";

                // NOW UPDATE THE ROW TO TAKE INTO ACCOUNT THE UNIQUE USER-DIRECTORY (USING THE ID AS THE KEY)
                $arrUpdateData  = array(
                    'newDirName'    => $userDirectory,
                    'ID'            => $id      // THIS ASSUMES THAT THE PRIMARY KEY OF YOUR TABLE IS CALLED id OTHERWISE USE THE APPROPRIATE KEY NAME: EG: reg_id OR WHATEVER
                );

                // PREPARE THE UPDATE QUERY:
                $insertStmt = $dbh->prepare($updateSQL);

                // UPDATE THE NEWLY CREATED ROW:
                $insertStmt->execute($arrUpdateData);

                // BUILD THE RESPONSE JSON DATA
                $arrResponse    = array(
                    'folderName'    => $userDirectory,
                    'id'            => $id,
                );

                // SEND THE RESPONSE AS JSON IF ALL WORKS FINE TILL HERE...
                // THAT MEANS: SEND THE DATA IN $arrResponse AND TERMINATE THE SCRIPT - THE JOB IS DONE.
                // NO NEED FOR ALL THOSE ECHO STATEMENTS AS THE YOU ARE EXPLICITLY SENDING BACK JSON DATA.
                die( json_encode($arrResponse) );

            }catch(PDOException $e){
                // IF THERE WAS ANY KIND OF PDO ERROR, SEND IT BACK ANYWAYS - BUT ALSO AS JSON:
                $arrResponse    = array(
                    'error'     => $e->getMessage()
                );
                die( json_encode($arrResponse) );
            }
        }


text:
Q: Anylogic: Understanding the difference between shapes, walls and visibility I am trying to understand how shapes, walls and visibility in annylogic work. I am designing a store with various different work stations. I use 3d shapes to denote these work stations. I then put rectangular walls around these stations to prevent agents(workers) from walking through the 3d shapes representing the stations. I want to know if the additional rectangular walls are needed or if the 3d shapes on their own can prevent agents passing through the stations. Also how does visibility work. Suppose I have a shape in the presentation layer but it is set to false in terms of visibility. Does this mean the shape has no effect on the simulation or is it still having an effect and the only thing that has changed is that we can't see it in the 3d visualisation. Same with the rectangular walls. If I build a wall around a shape and set the walls visibility to false, does that mean the walls are no longer there and are no effect on the simulation?

A: *

*Regular agents do not avoid any type of elements (not walls, not shapes)

*Pedestrian and Transporter type agents avoid walls.

*Pedestrian and Transporter type agents do not avoid shapes.

*Visibility only affects visibility and not function. So if you have a wall set to not visible, Pedestrians/transporters would still avoid it.


text:
Q: Store "templates" of children I am new to JavaScript so forgive me if the question comes around as dumb.
I know that appendChild() allows me to add a child element to an existing element. However, the problem is that I want to add an element which has an image on the left and a series of text boxes on the right and I need to add it over and over again on button click.
Adding simple elements like p, a , etc can be done by a single call to appendChild(), however for the above scenario, it will be a little messy.
Is there some way that I can define the custom element that I want to append and then just add it with a single call to appendChild()

A: Are you using jQuery? If it is a really complicated template, you could use .load() to ajax in an template and populate it with whatever you have to. You wouldn't need to dynamically create all of the elements using javascript, only populate it. This would would also allow you to change your template if need be very easily.

A: It seems you need cloneNode:
target.appendChild(template.cloneNode(true));  // If you want to clone template
                                               // with all its descendants

target.appendChild(template.cloneNode(false)); // If you want to clone template
                                               // without its descendants

A: I do this quite a bit. My code generally looks like this:

stuff

then:
$('.template').clone(true).removeClass('template').show().appendTo(someElement);

Since you're not using jQuery, have a look at the clone function here:
http://code.jquery.com/jquery-1.11.0.js
(search for "clone: function" to find it)
You can steal the relevant bits if you can't actually use jQuery itself.


text:
Q: In this code what does resolve and reject do? I'm learning about promises, I asked the question just to clear my mind. I think I understand what it does but can't put it into words.
I would really appreciate if someone explained the first 2 lines of this code. Lets says we called the function with a list of car models.
       function superSecretOrder(items) {
      return new Promise(function (resolve, reject) {
       const random = Math.random() * 1000
       setTimeout(function () {
       resolve([...items].sort())
       }, random)
        })
         }

A: Resolve is the callback for a promise's return type. You can then access the value using .then(...), example:
function superSecretOrder(items) {
  return new Promise(function (resolve, reject) {
    const random = Math.random() * 1000
    setTimeout(function () {
      resolve([...items].sort())
    }, random)
  })
}

const orderedCardsPromise = superSecretOrder(['b', 'a']);
orderedCardsPromise.then(orderedCards => {
  // After a random amount of time set by `const random = Math.random() * 1000`
  console.log(orderedCards); // ['a', 'b']
});


text:
Q: How to call a created function in PgAdmin I created a dynamic SQL function for the first time and wondering what is the correct way to call the function? Here's the code
CREATE OR REPLACE FUNCTION functions.search_function(_columns text)
    RETURNS TABLE(student text,
    student_id text,
    professor_name text,
    subject text,
    subject_time text,
    room_number text,
    building text)
  LANGUAGE plpgsql AS
$func$
DECLARE
   _columns text := 'student_id::text, subject_timetime::text, building::text';
BEGIN
   RETURN QUERY EXECUTE '
    SELECT
    student,
    professor_name,
    subject,
    room_number,
    ' || _columns || '
    FROM "school_records_table"  '
   USING  _columns;
END
$func$;

I have been receiving an error when I try this
SELECT functions.searchandfilter2_function(
    ('students') )


text:
Q: TeamCity: Customize build failed error message (include it in email) We are using TeamCity to process hundreds of builds. We added a custom command line script which prints an error to console, and if the enviroment variable TEAMCITY_VERSION is set, then we print the error message in the format TeamCity understands:
Console.Out.WriteLine(
    "##teamcity[message text='Custom Script failed.' errorDetails='" +
    ex.Message + "' status='ERROR']");

Now, I see that the error is displayed in the build log, however, under the build details, we only see [13:00:25]Process exited with code 1, and in the email notification sent to developers that included changes in that build, only that line is sent.
Is it possible to send in the email, and include in the build details the error we actually print to the console?

A: There is some build script interaction available:
Console.Out.WriteLine(
    "##teamcity[buildProblem text='Custom Script failed.' errorDetails='" +
    ex.Message + "']");

And complete it with a buildStatus:
Console.Out.WriteLine(
    "##teamcity[buildStatus text='{build.status.text} : Environment variable issue.' status='FAILURE']");

You can get more information about building script interaction on the official website:
When you will send the mail, if you have a specific routine which watch the build, you can get information easily using the available api.


text:
Q: Android SQLite limit 0,60 than 60,120... i get more? i want to get the first 60 rows, than the next 60....
This is my Cursor
final Cursor cursor = myDbSales.searchNamemagic(name, startLong, endLong,  limita,  limitb);

public  Cursor searchNamemagic(String search_str, String startdate, String enddate, String limita , String limitb) {

    try {

        int firstSpace = search_str.indexOf(" "); // detect the first space character
        firstName = search_str.substring(0, firstSpace);  // get everything upto the first space character
        lastName = search_str.substring(firstSpace).trim(); // get everything after the first space, trimming the spaces off
        }catch (Exception c){}

    String query = "SELECT * ,  strftime('%d.%m.%Y %H:%M', datetime(timeStamp, 'unixepoch', 'localtime')) as timecrazy   , tastepreis/(tax+100.0)*tax as'"+TAXSUMSEARCHNAME+"',    '"+currency+"' as '"+ DOLLA_SIGN+"' FROM salesTable where timeStamp BETWEEN '"+startdate+"' AND '"+enddate+"' AND (sellid LIKE '%"+search_str+"%'  OR tastemodel LIKE '%"+search_str+"%'  OR bezeichnung LIKE '%"+search_str+"%' OR sellid LIKE '%"+lastName+" "+firstName +"%'       )  ORDER BY timeStamp DESC limit '"+limita+"', '"+limitb+"'   " ;

    Cursor mCursor = dbSales.rawQuery(query, null);

    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

And this is my method
method(name,imyourlist1,"0","60" );
            method(name,imyourlist2, "60","120" );
            method(name,imyourlist3, "120","180");
            method(name,imyourlist4, "180","240");
            method(name,imyourlist5, "240","300");
            v(name,imyourlist6, "300","360");
            method(name,imyourlist7, "360","420");
            method(name,imyourlist8, "420","480");
            method(name,imyourlist9 ,"480","540");
            method(name,imyourlist10 ,"540","600" );

private void method (String name ,ListView imyourlist2, String limita, String limitb){

        final Cursor cursor = myDbSales.searchNamemagic(name, startLong, endLong,  limita,  limitb)

imyourlist1 is correct with 60 Rows but the next ones get more.
For example first one = 0-60 next one 60-more than 120
Is maybe my limit wrong?

A: You can use this script
SELECT * FROM tableName LIMIT 60 OFFSET 0

Next 60
SELECT * FROM tableName LIMIT 60 OFFSET 1

Page Number is int
SELECT * FROM tableName LIMIT 60 OFFSET Number


text:
Q: Why does my use of zlib decompress incorrectly? Please explain if this is a Zlib bug or I misunderstand the use of Zlib.
I am trying to do the following:
-I have two strings - data from which I need to compress: string_data_1 and string_data_2 and which I compress with Zlib as raw data.
-Next, I create a third string and copy the already compressed data into this single row.
-Now I'm decompressing this combined compressed data and there is a problem.
Zlib decompressed only the "first" part of the compressed data, did not decompress the second part. Is that how it should be?
For an example in the facebook/zstd:Zstandard library - exactly the same action - leads to unpacking - all compressed data and the first and second parts.
Here is a simple code:
#include <iostream>
#include <string>
#include <zlib.h>

int my_Zlib__compress__RAW(std::string& string_data_to_be_compressed, std::string& string_compressed_result, int level_compressed)
{

    //-------------------------------------------------------------------------
    uLong zlib_uLong = compressBound(string_data_to_be_compressed.size());

    string_compressed_result.resize(zlib_uLong);
    //-------------------------------------------------------------------------

     //this is the standard Zlib compress2 function - with one exception: the deflateInit2 function is used instead of the deflateInit function and the windowBits parameter is set to "-15" so that Zlib compresses the data as raw data:
    int status = my_compress2((Bytef*)&string_compressed_result[0], &zlib_uLong, (const Bytef*)&string_data_to_be_compressed[0], string_data_to_be_compressed.size(), level_compressed);

    if (status == Z_OK)
    {
        string_compressed_result.resize(zlib_uLong);

        return 0;
    }
        else
        {
        return 1;
        }

}

int my_Zlib__uncompress__RAW(std::string& string_data_to_be_uncompressed, std::string& string_compressed_data, size_t size_uncompressed_data)
{

    //-------------------------------------------------------------------------
    string_data_to_be_uncompressed.resize(size_uncompressed_data);
    //-------------------------------------------------------------------------

    //this is the standard Zlib uncompress function - with one exception: the inflateInit2 function is used instead of the inflateInit function and the windowBits parameter is set to "-15" so that Zlib uncompresses the data as raw data:
    int status = my_uncompress((Bytef*)&string_data_to_be_uncompressed[0], (uLongf*)&size_uncompressed_data, (const Bytef*)&string_compressed_data[0], string_compressed_data.size());

    if (status == Z_OK)
    {
        return 0;
    }
}

int main()
{

int level_compressed = 9;

//------------------------------------------Compress_1-------------------------------------------
std::string string_data_1 = "Hello12_Hello12_Hello125";              //The data to be compressed.

std::string string_compressed_result_RAW_1;                             //Compressed data will be written here

int status = my_Zlib__compress__RAW(string_data_1 , string_compressed_result_RAW_1, level_compressed);
//----------------------------------------------------------------------------------------------

//--------------------------------------Compress_2----------------------------------------------
std::string string_data_2= "BUY22_BUY22_BUY223";              //The data to be compressed.

std::string string_compressed_result_RAW_2;                         //Compressed data will be written here

status = my_Zlib__compress__RAW(string_data_2 , string_compressed_result_RAW_2, level_compressed);
//----------------------------------------------------------------------------------------------

std::string Total_compressed_data = string_compressed_result_RAW_1 + string_compressed_result_RAW_2; //Combine two compressed data into one string

//Now I want to uncompress the data in a string - "Total_compressed_data"

//--------------------------------------Uncompress--------------------------------
std::string string_uncompressed_result_RAW;                         //Uncompressed data will be written here

int size_that_should_be_when_unpacking = string_data_1.size() + string_data_2.size();

status = my_Zlib__uncompress__RAW(string_uncompressed_result_RAW, Total_compressed_data, size_that_should_be_when_unpacking , level_compressed);
//--------------------------------------------------------------------------------

std::cout<<string_uncompressed_result_RAW<<std::endl;  //Hello12_Hello12_Hello125

}

Zlib decompressed only the "first" part of the compressed data, did not decompress the "second" part.
Is that how it should be?

A: As noted in the comments, a concatenation of zlib streams is not a zlib stream. You need to uncompress again for the second zlib stream. Or compress the whole thing as one zlib stream in the first place.
You would need to use a variant of uncompress2(), not uncompress(), since the former will return the size of the first decompressed zlib stream in the last parameter, so that you know where to start decompressing the second one.
Better yet, you should use the inflate() functions instead for your application. The retention of the uncompressed size for use in decompression means that you'd need that on the other end. How do you get that? Are you transmitting it separately? You do not need that. You should use inflate() to decompress a chunk at a time, and then you don't need to know the uncompressed size ahead of time.
You should also use the deflate() functions for compression. Then you can keep the stream open, and keep compressing until you're done. Then you will have a single zlib stream.


text:
Q: Target-dependent macros with cljx Problem Description
I have a project that targets both Clojure (JVM) and ClojureScript via CLJX.
I have a macro that takes a thunk and creates an IDeref instance to execute that thunk every time it is dereferenced (with deref or @).
Since it's a macro, it has to go in a .clj file. The problem is that the IDeref interface is different for Clojure and ClojureScript. In Clojure I need to generate this:
(reify clojure.lang.IDeref
  (deref [_] thunk))

In ClojureScript I need to generate this:
(reify IDeref
  (-deref [_] thunk))

Since this a macro I can't use the featuer-expression-like syntax from cljx (e.g. #+cljs -deref) to reconcile the code for my two target platforms. Here's what I ended up doing:
(defmacro make-thunk [exp]
  `(reify ~params/IDeref-interface
     (~params/IDeref-method [_#] ~exp)))

I then have a separate params.clj in both the clj and cljs source trees, each of which has a def for each needed symbol.
This works, but it's really ugly, and it feels like a dirty hack.
My Question
I'd really like to keep all of my macros in the same namespace. I'd rather not have to define every platform-dependent symbol for my macros in a separate file. I already have platform-dependent compat.clj and compat.cljs files in the two source trees. Having to add more files to support platform-dependent macros is starting to make things feel cluttered.
Is there a cleaner solution to this problem?

A: Inside the body of a macro, (:ns &env) will be truthy when expanding in ClojureScript but not in Clojure.
This is currently the "best practice" for writing platform-specific macros:
(defmacro platform []
  (if (:ns &env)
    :CLJS
    :CLJ))

A: This should do the trick:
(defn compiling-cljs?
  "Returns true if we seem to be compiling ClojureScript, false otherwise.

  This is a Clojure function, meant to be called by macros targeting both
  Clojure and ClojureScript."
  []
  (if-let [cljs-ns-var (resolve 'cljs.analyzer/*cljs-ns*)]
    (some? @cljs-ns-var)
    false))

Use like so:
(defmacro foo []
  (if (compiling-cljs?)
    1
    2))

(I have a feeling this problem has been solved before, but can't seem to find a reference.)


text:
Q: Xfce4 menu is not showing all applications In my Whiskermenu pre-installed applications are not shown. After a reinstall of for example Gimp Whisker could not find it either. The xfce4-popup-applicationswindow too did not show them.
I tried resetting by pkill xconfd and deleting xfce4 in ~/.config/ and a restart.
I use UbuntuStudio 16.04 which is like Xubuntu but with a custom theme and some software for music and art creation.

A: Delete the file /home/username/.config/menus/xfce-applications.menu. This file is created when you use the menu-editor. After deleting the file all applications will show up in the menu, but Favorites will be empty, you can easily repopulate by adding favorites. Don't use the menu-editor, it always leads to loss of menu-entries.
If you can't open Thunar from the menu, open terminal with Ctrl+Alt+T and use command rm ~/.config/menus/xfce-applications.menu


text:
Q: Issue converting date format from a data frame to timeserie I found this code online:
#Integration and co-integration analysis of equity indexes.
library(urca)
library(vars)
## Loading data set and converting to zoo
data(EuStockMarkets)

Assets=as.zoo(EuStockMarkets)

## Aggregating as month's−enddput series

AssetsM=aggregate(Assets , as.yearmon ,  tail , 1)
head(AssetsM)

## Applying unit root tests for sub−sample

AssetsMsub=window( AssetsM,start =start( AssetsM ), end = "Jun 1996")

# class = "yearmon"), class = c("zooreg", "zoo"), frequency = 12)

## Levels

ADF=lapply(AssetsMsub,ur.df,type = "drift",selectlags = "AIC")

With the EuStockMarkets data details here:

Description
Contains the daily closing prices of major European stock indices:
  Germany DAX (Ibis), Switzerland SMI, France CAC, and UK FTSE. The data
  are sampled in business time, i.e., weekends and holidays are omitted.
  Usage
EuStockMarkets
Format
A multivariate time series with 1860 observations on 4 variables. The
  object is of class "mts".

I try to use my own data which are in a data.frame format. As the first column is a date vector with mixed format I use a standard format.
dput datetest2 = ow.names = c(NA, 6L), class = "data.frame")

But I have an issue with the last line of the code:
#Integration and co-integration analysis of equity indexes.
library(urca)
library(vars)

## Loading data set and converting to zoo
rm(list = setdiff(ls(), lsf.str()))

datetest2 <- read.csv("~/Desktop/datetest2.csv")

## As date aren't in uniformised format we create a date vector and replace the old one

DateTS <-as.Date(as.Date("2017/10/02"):as.Date("2018/05/22"), origin="1970/01/01")
datetest2[,1]=DateTS

## Convert data frame to c("mts", "ts", "matrix"))

data <- ts(datetest2[,-1],start=datetest2[1,1],end=datetest2[NROW(datetest2),1],frequency = 1 )

Assets=as.zoo(data)

## Aggregating as month's−end series

AssetsM=Assets
AssetsM=aggregate(Assets , as.yearmon ,  tail , 1)
head(AssetsM)

## Applying unit root tests for sub−sample

AssetsMsub=window(AssetsM,start =start( AssetsM ), end = end(AssetsM))

## Levels

ADF=lapply(AssetsMsub,ur.df,type = "drift",selectlags = "AIC")

this error: Error in charToDate(x) : character string is not in a standard unambiguous format
But it's not clear to me as the Date are already in an unambiguous format, any idea?
> dput(head(datetest2,10))
structure(list(X = structure(c(17441, 17442, 17443, 17444, 17445,
17446, 17447, 17448, 17449, 17450), class = "Date"),X1 = c(0.001266303,
-0.021048584, -0.020621217, 0.023149588, 0.009748078, 0.012748959,
0.040634667, 0.034437722, 0.002087083, 0.009260646), X2 = c(0.037842672,
-0.219755806, 0.052179239, -0.020359985, -0.147664555, 0.121832339,
-0.022406655, 0.076908587, -0.026717135, 0.044910046), X3 = c(-0.022771565,
-0.0411676, 0.030648901, -0.000196444, 0.004834399, 0.011694903,
-0.026136535, -0.064203569, 0.026439081, 0.024184196), X4 = c(-0.016205216,
-0.017019091, 0.00068362, 0.010874844, 0.042127166, 0.008165155,
-0.008100346, -0.037033935, 0.008304639, 0.011900759), X5 = c(-0.058696937,
-0.024072712, -0.026573368, -0.011153745, -0.07178172, 0.067360919,
-0.074169252, -0.063135862, 0.017187075, 0.008108153), X6 = c(-0.021498233,
-0.019484207, -0.018313765, 0.00523917, 0.00867141, 0.008787067,
0.010594121, -0.057712044, 0.011102414, 0.00334613), X7 = c(-0.018186256,
0.015393258, -0.027814412, 0.015910798, -0.007320437, 0.005577137,
-0.021271535, -0.048851434, 0.0154376, 0.00688708), X8= c(-0.061737994,
-0.038319809, -0.019420551, -0.034385314, 0.001193193, 0.004084886,
-0.085468062, 0.000636325, 0.074028454, 0.023084468), X9= c(0.028155324,
-0.089042438, -0.075688421, 0.035312622, 0.037694432, 0.07525801,
-0.119479271, -0.09718284, 0.007190581, 0.021934404), X10 = c(-0.054497537,
-0.044083621, -0.045526127, 0.206964088, 0.233137354, 0.130054454,
-0.1195141, -0.055098329, 0.074006512, 0.02588484)), row.names = c(NA,
10L), class = "data.frame")