text:
Q: MATLAB solve Ordinary Differential Equations How can I use matlab to solve the following Ordinary Differential Equations?
x''/y = y''/x = -( x''y + 2x'y' + xy'')
with two known points, such as t=0: x(0)= x0, y(0) = y0; t=1: x(1) = x1, y(1) = y1 ?
It doesn't need to be a complete formula if it is difficult. A numerical solution is ok, which means, given a specific t, I can get the value of x(t) and y(t).
If matlab is hard to do this, mathematica is also OK. But as I am not familiar with mathematica, so I would prefer matlab if possible.
Looking forward to help, thanks!
I asked the same question on stackexchange, but haven't get good answer yet.
https://math.stackexchange.com/questions/812985/matlab-or-mathematica-solve-ordinary-differential-equations
Hope I can get problem solved here!
What I have tried is:
---------MATLAB

syms t

>> [x, y] = dsolve('(D2x)/y = -(y*D2x + 2Dx*Dy + x*D2y)', '(D2y)/x = -(y*D2x + 2Dx*Dy + x*D2y)','t')

Error using sym>convertExpression (line 2246)
Conversion to 'sym' returned the MuPAD error: Error: Unexpected 'identifier'.
[line 1, col 31]

Error in sym>convertChar (line 2157)
s = convertExpression(x);

Error in sym>convertCharWithOption (line 2140)
    s = convertChar(x);

Error in sym>tomupad (line 1871)
    S = convertCharWithOption(x,a);

Error in sym (line 104)
        S.s = tomupad(x,'');

Error in dsolve>mupadDsolve (line 324)
sys = [sys_sym sym(sys_str)];

Error in dsolve (line 186)
sol = mupadDsolve(args, options);

--------MATLAB
Also, I tried to add conditions, such as x(0) = 2, y(0)=8, x(1) = 7, y(1) = 18, and the errors are still similar. So what I think is that this cannot be solve by dsolve function.
So, again, the key problem is, given two known points, such as when t=0: x(0)= x0, y(0) = y0; t=1: x(1) = x1, y(1) = y1 , how I get the value of x(t) and y(t)?
Update:
I tried ode45 functions. First, in order to turn the 2-order equations into 1-order, I set x1 = x, x2=y, x3=x', x4=y'. After some calculation, the equation becomes:
x(1)' = x(3)                                                (1)

x(2)' = x(4)                                                (2)

x(3)' = x(2)/x(1)*(-2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2))     (3)

x(4)' = -2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2)                 (4)

So the matlab code I wrote is:
myOdes.m

function xdot = myOdes(t,x)

xdot = [x(3); x(4); x(2)/x(1)*(-2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2)); -2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2)]

end

main.m
t0 = 0;
tf = 1;
x0 = [2 3 5 7]';
[t,x] = ode45('myOdes',[t0,tf],x0);
plot(t,x)

It can work. However, actually this is not right. Because, what I know is that when t=0, the value of x and y, which is x(1) and x(2); and when t=1, the value of x and y. But the ode functions need the initial value: x0, I just wrote the condition x0 = [2 3 5 7]' randomly to help this code work. So how to solve this problem?
UPDATE:
I tried to use the function bvp4c after I realized that it is a boundary value problem and the following is my code (Suppose the two boundry value conditions are: when t=0: x=1, y=3; when t=1, x=6, y=9. x is x(1), y is x(2) ):
1. bc.m
function res = bc(ya,yb)
res = [ ya(1)-1; ya(2)-3; yb(1) - 6; yb(2)-9];
end
2. ode.m
function dydx = ode(t,x)
dydx = [x(3); x(4); x(2)/x(1)*(-2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2)); -2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2)];
end
3. mainBVP.m
solinit = bvpinit(linspace(0,6,10),[1 0 -1 0]);
sol = bvp4c(@ode,@bc,solinit);
t = linspace(0,6);
x = deval(sol,t);
plot(t,x(1,:));
hold on
plot(t,x(2,:));

plot(t,x(3,:));

plot(t,x(4,:));
x(1,:)
x(2,:)

It can work, but I don't know whether it is right. I will check it again to make sure it is the right code.

A: EDIT:
This is how I would solve the problem. Note: I don't really like the matlabFunction creator but this is simply a personal preference for various reasons I won't go into.
% Seperate function of the first order state equations
function dz = firstOrderEqns(t,z)
    dz(4,1) = 0;
    dz(1) = -2.*z(3).*z(1).*z(4)./(1 + z(4).^2 + z(2).^2);
    dz(2) = z(1);
    dz(3) = -2.*z(2).*z(3).*z(1)./(1 + z(4).^2 + z(2).^2);
    dz(4) = z(3);
end

% runfirstOrderEqns
%% Initial conditions i.e. @ t=0
z1 = 5; % dy/dt = 5 (you didn't specify these initial conditions,
%  these will depend on the system which you didn't really specify
z2 = 0; % y = 0
z3 = 5; % dx/dt = 5 (The same as for z1)
z4 = 0; % x = 0
IC = [z1, z2, z3, z4];
%% Run simulation
% Time vector: i.e closed interval [0,20]
t = [0,20]; % This is where you have to know about your system
           % i.e what is it's time domain.
           % Note: when a system has unstable poles at
           % certain places the solver can crash you need
           % to understand these.
% using default settings (See documentation ode45 for 'options')
[T,Y] = ode45(@firstOrderEqns,t,IC);

%% Plot function
plot(T,Y(:,1),'-',T,Y(:,2),'-.',T,Y(:,3),':',T,Y(:,4),'.');
legend('dy/dt','y','dx/dt','x')

As in my comments I have made a lot of assumtions that you need to fix for example, you didn't specify what the initial conditions for the first derivatives of the states are i.e. (z1, z3) which is important for the response of the system. Also you didn't specify the time interval your interested for the simulation etc.
Note: The second m file can be used with any state function in the correct format

A: As mentioned, this isn't a math site, so try to give code or something showing some effort.
However, the first step you need to do is turn the DE into normal form (i.e., no 2nd derivatives). You do this by making a separate variable equal to the derivative. Then, you use
syms x y % or any variable instead of x or y

to define variables as symbolic. Use matlabfunction to create a symbolic function based on these variables. Finally, you can use the ode45 function to solve the symbolic function while passing variable values. I recommend you look up the full documentation in matlab in order to understand it better, but here is a very basic syntax:
MyFun= matlabFunction(eq,'vars',{x,y});
[xout,yout]=ode45(@(x,Y) MyFun(variables),[variable values],Options);

Hopefully this puts you in the right direction, so try messing around with it and provide code if you need more help.

A: The following is the answer we finally get @Chriso: use matlab bvp4c function to solve this boundary value problem (Suppose the two boundry value conditions are: when t=0: x=1, y=3; when t=1, x=6, y=9. x is x(1), y is x(2) ):
1. bc.m
function res = bc(ya,yb)
res = [ ya(1)-1; ya(2)-3; yb(1) - 6; yb(2)-9];
end
2. ode.m
function dydx = ode(t,x)
dydx = [x(3); x(4); x(2)/x(1)*(-2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2)); -2*x(1)*x(3)*x(4)/(1+x(1)^2+x(2)^2)];
end
3. mainBVP.m
solinit = bvpinit(linspace(0,6,10),[1 0 -1 0]);
sol = bvp4c(@ode,@bc,solinit);
t = linspace(0,6);
x = deval(sol,t);
plot(t,x(1,:));
hold on
plot(t,x(2,:));

plot(t,x(3,:));

plot(t,x(4,:));
x(1,:)
x(2,:)


text:
Q: Pushing changes to a certain branch created with Jira I cloned a GitLab project in Python that has usually 2 branches: main and develop. Every time someone adds a new feature, they create a new branch from a ticket in Jira, work on it, and this gets eventually merged to develop.
I made some changes in the project, locally on my computer using PyCharm. I created a new branch using Jira, let's call it ticket-11, it is momentarily identical to develop. I want the changes to appear in ticket-11. If I use the drop-down menu in PyCharm and select Git->Push..., this branch doesn't appear there. And I got an email saying that pipeline failed (I saw that the same thing appears for other branches with other tickets too).
How can I simply push the changes from command line, to that specific branch?

A: If you create a branch on Jira (or any other git-tool, like GitHub, GitLab, BitBucket, Azure…) you must first announce your local repository that there is a new branch. And you can do this with git fetch. This command you must also execute if another team member create a branch and you want this branch locally on your computer.
But you can also create a branch locally with git checkout -b <branch-name> on the command line or in PyCharm as described here. And after this, you can push this new branch to the remote (Jira or whatever). This way, one step can be saved!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Making something move in an array I have to make this program that will make a 12 by 12 array filled with different letters, then make something like a disease that spreads to the nearby cells of the same letter (it'll be randomly placed in the array). I've managed so far to make a class for the array and for the disease (to select a random char to be diseased) but I don't understand how I can make it see the nearby cells. In addition in the Disease the user can choose how many different letters(2-4). So far i've done:
import java.util.Random;
public class Disease {
public char D ;
Random r = new Random();
public void forTwo() {
    Random r = new Random();
    D = (char)(r.nextInt(2) + 'E');
}
public void forThree() {
    Random r = new Random();
    D = (char)(r.nextInt(3) + 'E');
}
public void forFour() {
    Random r = new Random();
    D = (char)(r.nextInt(4) + 'E');
}
}

AND THE ARRAY:
import java.util.Arrays;
import java.util.Random;
public class PlayingArea {
private String letters;
public char[][] grid;
public PlayingArea(String letters) {
    this.letters = letters;
}
public void populate() {
    int n = letters.length();
    grid = new char[12][12];

    Random r = new Random();
    for (int j = 0; j < grid.length; j++) {
        for (int i = 0; i < grid.length; i++) {
            grid[i][j] = letters.charAt(r.nextInt(n));
        }
    }
}
public String gridAsString() {
    StringBuilder sb = new StringBuilder();
    for (char[] letterRow : grid) {
        sb.append(Arrays.toString(letterRow)).append('\n');
    }
    return sb.toString();
}
}

A: If you work with arrays the neighbors of an example cell a[1][1] can be
a[0][1], a[2][1], a[1][0] and a[1][2] if you only work in 4 directions.
You can also create a class for the cells, which knows its direct neighbor cells,
so you can get the left neighbor like cell.getLeftNeighbor().
Edit:
Ok, so now that you have your code so far we can help a bit more specific. :)
The way you implemented it, you would have to access the disease logic in your class PlayingArea. I do not quite understand what your methods in the class Disease do, forTwo() will assign 'E' or 'F' to the char D for example.
You need to determine on which coordinates the disease is, you can do it on different ways:

*

*Specify the coordinates in PlayingArea, like 5 and 4 = grid[5][4].The direct neighbors are now grid[x-1][x], grid[x+1][x], grid[x][x-1] and grid[x][x+1].

*Replace the char[][] with a Cell[][]. You would have to create a class Cell, which only needs to know with a boolean, which letter is in it and if it is diseased. Additionally you can give it other Cells as attributes, this way you can access a cells neighbors directly.
public class Cell{
    public char letter;
    public boolean diseased;
    public Cell leftCell, rightCell, topCell, bottomCell;

    public Cell(char newLetter){
        letter = newLetter;
    }
 }

This example is without setter/getter methods, you can create cells in the PlayingArea, set the state of disease of each cell and assign/access neighbor cells.

A: Start by drawing out your array on paper as a grid...like a checkers board. Select any space in that grid and figure out the indexes of the adjacent spaces relative to the one you've selected.
Write a method to do what you just did mentally.
It sounds like this is an iterative question. "How many iterations will it take for the array to be completely infected?"

A: Given the limited information, I think recursive way would be more natural, but you can as easily implement it with iteration(it would require you to store deceased cells and where to go next).
Since it is a 2D array, once you have the infected cell, you can check if the character on the left and right are "infectable" (same letter).
To check up and down, you would need to go adjacent subarrays.
For example:
Your infected cell is [3,4].  To check left and right, you need to go to [3,3] and [3,5] entries.
To check up and down , you need to go to [2,4] and [4,4].
If you need to check cells diagonally, then check [2,3],[2,5], [4,3] and [4,5].
Then if you are able to "infect" another cell - call your function on that cell again.
This should give you an idea where to start.
If you get stuck with some errors - post your code and specify where you are stuck ( if you are allowed to do so).

A: Store the current position of the disease object as variables in your disease object so each disease has a current location/coordinates ie x,y
Using x and y as the current location of your disease(which you don't know):

*

*To look at the cells adjacent you can use

         array[x+1][y] // Right
         array[x-1][y] // Left
         array[x][y+1] // Down
         array[x][y-1] // Up

*

*if you wanted to look at diagonals as well, use the same method. (array[x-1][y-1] = top left)

You wouldn't be able to do it from the disease unless you passed your disease object the array or a subset of the array.


text:
Q: jQuery Datatable not working in symfony I have done all required steps but I don't know why my datatable is not showed. I have included jquery.dataTables.css and jquery.dataTables.js.
**view.html.twig**

{% extends 'base.html.twig' %}

{% block stylesheets %}
   <link rel="stylesheet" href="{{ asset('bundles/app/css/style.css') }}" >
   <link rel="stylesheet" href="{{ asset('bundles/app/css/bootstrap.css') }}" >
   <link rel="stylesheet" href="{{ asset('bundles/app/css/bootstrap-grid.css') }}" >
   <link rel="stylesheet" href="{{ asset('bundles/app/css/bootstrap-theme.css') }}" >
   <link rel="stylesheet" href="{{ asset('bundles/js/media/css/dataTables.bootstrap.css') }}" >
   <link rel="stylesheet" href="{{ asset('bundles/js/media/css/jquery.dataTables.css') }}" >
{% endblock %}

{% block javascripts %}

{% endblock %}

{% block body %}

STUDENT INFORMATION FORM

                USER NAME
                FIRST NAME
                LAST NAME
                EMAIL ID
                PASSWORD
                EDIT
                DELETE

        {% for key in view %}

                {{  key.UserName }}
                {{  key.FirstName }}
                {{  key.LastName }}
                {{  key.EmailId }}
                {{  key.Password }}
                Edit
                Delete

        {% endfor %}

{% endblock %}

        **demo.js**

This is my demo.js file i am using Ajax:
    $(document).ready(function(){
    $("#create").click(function(){
    alert('You Can See Student Information Form');

        //var formURL = "{{ path('form') }}";
        //var formData = new FormData(this);

            $.ajax({
            type: "POST",
            url: formURL,
            dataType: "json",
            data: $("#form_person_edit").serialize(),
            success: function(res){
            $(".ajax_response").html();

            if(res.status == 'success'){
            window.location.href = viewURL;
            }
            }
    });
    });
    });

I don't know where I did a mistake.

A: By default block javascripts gets rendered at the end of the html. So in your case you are calling $('#table_view').DataTable(); too early.
Move:

at the end of block javascripts. And in your base.html.twig make sure block javascripts is defined after block body.


text:
Q: What does the adjoint representation of $\operatorname{SL}(2, \mathbb{R})$ look like in terms of the irreducible representation? Let $G$ be a Lie group, and $H < G$ be isomorphic to $\operatorname{SL}(2, \mathbb{R})$. Now, each $h \in H$ acts on $G$ by conjugation $\phi_g : h \mapsto ghg^{-1}$, and this induces the adjoint representation $\operatorname{Ad}_h$ on $\mathfrak{g}$.
Now, any representation of $\operatorname{SL}(2, \mathbb{R})$ can be written as a the symmetric tensor product $\operatorname{Sym}^n(\mathbb{R}^2)$. Any element of this space can be written as a homogeneous polynomial $$p(A, B) = \sum_{i + j = n} c_i A^i B^j,$$ where $A = \pmatrix{1 \\ 0}$, and $B = \pmatrix{0 \\ 1}$. Left multiplication by elements of $H$ act on $p(A, B)$ through applying their $SL(2, R)$ counterpart as follows $h \cdot p(A, B) = p(h \cdot A, h \cdot B)$.
Now, what about the adjoint operator? How does it look like in terms of this irreducible representation?


text:
Q: Replacing specific spaces with colons in a text file I have a report that outputs to a text file in linux and I need it modified a bit.
The file starts out like this if you cat it:
  6 E8 B7 48 36 8C AE
  8 00 0C 85 F2 F9 07
  8 44 03 A7 C0 0D 26
  8 C8 4C 75 5C B1 55
 10 00 05 00 E7 5B 9F
 10 00 17 C5 69 49 A1
 10 00 1D A2 E7 BC F1
 12 00 16 9C 6C 53 C0
 14 00 0C 85 F2 F9 08
 26 00 05 00 E7 5B B7

Some random text will be down here also...
I'm wanting it to look like this:
  6 E8:B7:48:36:8C:AE
  8 00:0C:85:F2:F9:07
  8 44:03:A7:C0:0D:26
  8 C8:4C:75:5C:B1:55
 10 00:05:00:E7:5B:9F
 10 00:17:C5:69:49:A1
 10 00:1D:A2:E7:BC:F1
 12 00:16:9C:6C:53:C0
 14 00:0C:85:F2:F9:08
 26 00:05:00:E7:5B:B7

Some random text will be down here also...
I was hoping to use sed to accomplish this.

A: I think this would be easier with awk:
awk '{ printf("%2.2s %s:%s:%s:%s:%s:%s\n", $1, $2, $3, $4, $5, $6, $7); }' file

A: Following the answer of @Guru, you can try this one with sed:
sed -r 's/(\w) +/\1:/2g' file

You have to catch one letter before as sed does not support lookbehind.

A: Using Perl, this will work with any number of alignment spaces:
perl -lane '($p,$m)=/^(\s*\d+\s*)(.*)$/; $m =~ s/ /:/g; print $p,$m' input

A: One way using sed:
sed 's/  */:/3g'  file

A: sed "
: doublept
   s/^\( *[[:digit:]]\{1,\}\)\( \{1,\}\)\(.*\) \([[:alnum:]]\{1,\}\)/\1\2\3:\4/
   t doublept
"

work also for bigger "mac address" if any (i think mainly same kind of problem for IP adress and IPv6)

A: If you always know the line range for the numbers, you can use:-
sed 1,10s'/ /:/'g

The single quotes are important.


text:
Q: How to remove Non-English characters in Trino I am trying to remove non-english characters using Trino. As I am new to this, I am not sure what operator to use as ~ unusable . This is my current code:
Select
translationid,
medium
from translation
where medium ~ '[^A-Za-z_]'

A: Select
translationid,
medium
from translation
where not regexp_like(medium, '[^A-Za-z_]')


text:
Q: Passing an array of models to route to display in view from controller So I have a view that would show all of the rows available and display them.
A route calls the controller to fetch the data:
Route::get('/list', array('as' => 'index', [ContactListController::class, 'getContacts']));

I assign my controller to grab all of the rows using:
class ContactListController extends Controller
{
    public function getContacts()
    {
        $list = Contact::all();

        return view('list')->with($list);
    }
}

Then I display them in my view:

  @foreach ($list as $contact)

      <form action="" method="post">
        <input type="hidden" name="id" value="{{ $contact->id }}">
        {{ $contact->fname }}
        {{ $contact->lname }}
        {{ $contact->number }}
      </form>

  @endforeach

But the page says:

I would just like to display these data as a clickable table.
Please be easy on me since this is my first week of using Laravel ;)

A: At the first change your route to this:
Route::get('/list', [YourController::class, 'yourMethod'])->name('index');

and then in the controller:
class ContactListController extends Controller
{
    public function getContacts()
    {
        $list = Contact::all();

        return view('list')->with('list', $list);
    }
}

A: I think you are using older route declaration with Laravel 8. The syntax of fromAction method in the screenshot of the error is Laravel 8 implementation.
Use either of this solutions:
// Using PHP callable syntax...
Route::get('/list', [ContactListController::class, 'getContacts'])->name('index');

// Using string syntax...
Route::get('/list', 'ContactListController@getContacts')->name('index');

More info on this is on Laravel 8.x Upgrade Guide


text:
Q: Why the script show the object content incorrectly? Here is my client side code:
import {useEffect,useState} from 'react';
import io from 'socket.io-client';
import Peer from './Peer';
export default function TestMeeting(){
    let peerName;
    const [peerList,setPeerList]=useState({});
    const [signalSocket,setSignalSocket]=useState(io.connect(process.env.REACT_APP_SOCKET_URL+"testMeeting", { transports: ['websocket'] }));

    let sUsrAg = navigator.userAgent;
    if (sUsrAg.indexOf("Edg")>-1){
        peerName="Edge";
    }else{
        if (sUsrAg.indexOf("Chrome")>-1){
            peerName="Chrome";
        }else {
            if (sUsrAg.indexOf("Firefox")>-1){
                peerName="Firefox";
            } else {
                if (sUsrAg.indexOf("Safari")>-1){
                    peerName="Safari";
                }
            }
        }
    }

    useEffect(()=>{
        signalSocket.on("greeting",greeting=>{
            let peer=new Peer(greeting.from,greeting.socketId);
            let temp={...peerList};
            temp[greeting.socketId]=peer;
            setPeerList(temp);
        })
        signalSocket.on("newPeerAdded",(remotePeer)=>{
            let peer=new Peer(remotePeer.from,remotePeer.socketId);
            peerList[remotePeer.socketId]=peer;
            let temp={...peerList};
            temp[remotePeer.socketId]=peer;
            setPeerList(temp);
            signalSocket.emit("sayHi",{socketId:remotePeer.socketId,"peerName":peerName});
        });
    },[signalSocket,peerList,peerName])
    let connect=()=>{
        signalSocket.emit("newPeer",peerName);
    }
    console.log(peerList);
    return(

            <button onClick={connect}>Connect</button>

            {
                Object.keys(peerList).map((key,index) => (

                        {peerList[key].peerName()}

                ))
            }

    );
}
class Peer {
    constructor(remotePeerName,remoteSocketId) {
        let peerName=remotePeerName;
        let socketId=remoteSocketId;

        this.peerName=()=>{return peerName}
        this.socketId=()=>{return socketId}
    }
}
export default Peer;

Here is my server side code:
class TestMeeting{
    constructor(socket){
        console.log("TestMeeting:Connection established");
        socket.on('disconnect', function () {
            console.log("TestSimplePeer:Disconnected");
        });
        socket.on("newPeer",(peerName)=>{
            console.log("TestMeeting:newPeer event received.")
            socket.broadcast.emit("newPeerAdded", {from:peerName,socketId:socket.id});
        });
        socket.on("sayHi",(sayHi)=>{
            console.log("sayHi event received.");
            socket.to(sayHi.socketId).emit("greeting",{from:sayHi.peerName,socketId:socket.id});
        });
    }
}
module.exports=TestMeeting;

How it works
When user click on the "connect" button, it would send "newPeer" event to other peers via server.
The other peers would response the "sayHi" event with the socket id to sender via server.
Test case
I opened 3 browsers to test these codes, so when I click on the "connect" button, I expect the browser console should show the following:
Object { e_VLiK2A2ZrSS6uqAABn: {…} }                             TestMeeting.js:45
Object { e_VLiK2A2ZrSS6uqAABn: {…}, wjsYo70xzMWwkebkAABr: {…} }  TestMeeting.js:45

However, the browser console show the following:
Object { e_VLiK2A2ZrSS6uqAABn: {…} }                             TestMeeting.js:45
Object { wjsYo70xzMWwkebkAABr: {…} }                             TestMeeting.js:45
Object { e_VLiK2A2ZrSS6uqAABn: {…}, wjsYo70xzMWwkebkAABr: {…} }  TestMeeting.js:45

Would you tell me what's happening? And how to fix it?

A: After several tried, I made it work:
Client side code:
import { useEffect, useReducer } from "react";
import io from "socket.io-client";
export default function TestMeeting() {
    let peerName;
    let sUsrAg = navigator.userAgent;
    if (sUsrAg.indexOf("Edg") > -1) {
        peerName = "Edge";
    } else {
        if (sUsrAg.indexOf("Chrome") > -1) {
            peerName = "Chrome";
        } else {
            if (sUsrAg.indexOf("Firefox") > -1) {
                peerName = "Firefox";
            } else {
                if (sUsrAg.indexOf("Safari") > -1) {
                    peerName = "Safari";
                }
            }
        }
    }
    let socket=io.connect(process.env.REACT_APP_SOCKET_URL + "testMeeting", {
        transports: ["websocket"],
    })
    const initialState = {
        peerList:{},
        socket:socket
    };
    let reducer=(state,action)=>{
        let result=null;
        switch (action.type){
            case "addPeer":
                let temp={...state.peerList};
                //console.log(state.peerList);
                temp[action.peer.socketId]=action.peer;
                result=result={...state,peerList:temp}
                break;
            case "initialPeerList":
                result={...state,peerList:action.peerList}
                break;
            case "removePeer":
                let temp1={...state.peerList};
                delete temp1[action.socketId]
                result=result={...state,peerList:temp1}
                break;
            default:
                result=state;
                break
        }
        return result;
    }
    useEffect(() => {
        socket.emit("hi", peerName, (response) => {
            console.log("=======================hi===============");
            dispatch({type:"initialPeerList",peerList:response.peerList})
        });
        socket.on("newPeer", (peer) => {
        dispatch({type:"addPeer",peer:peer})
        });
        socket.on("removePeer",(socketId)=>{
            dispatch({type:"removePeer",socketId:socketId})
        });
    },[]);
    const [state, dispatch] = useReducer(reducer, initialState);
    console.log(state);
    return(
        <>
        {Object.keys(state.peerList).map((key, index) => (

{state.peerList[key].name}

        ))}
        </>
    )
}

Server side code:
class TestMeeting{
    constructor(){
        let peerList={};
        this.addPeer=(socket)=>{
            socket.on('disconnect', function () {
                let peer=peerList[socket.id];
                console.log("TestSimplePeer:Disconnected");
                if (peer){
                    console.log(peer.name+" leave the meeting.");
                }
                delete peerList[socket.id];
                console.log("==================peer list===============");
                console.log(peerList);
                socket.broadcast.emit("removePeer",socket.id);
            });
            socket.on("hi",(peerName,calllBack)=>{
                peerList[socket.id]={name:peerName,socketId:socket.id};
                console.log("Received say hi from "+peerName+".");
                socket.broadcast.emit("newPeer",peerList[socket.id]);
                console.log("Broadcast newPeer ("+peerName+") to other peer.");
                calllBack({"peerList":peerList})
            })
        }
    }
}
module.exports=TestMeeting;


text:
Q: Warning: POST Content-Length of 90612004 bytes exceeds the limit of 8388608 bytes in Unknown on line 0 I got this error

Warning: POST Content-Length of 90612004 bytes exceeds the limit of
  8388608 bytes in Unknown on line 0

I've done some searches and I changed post_max_size and upload_max_filesize
to 150M and reset Wamp  but STILL I get this error what should I do?

A: There are 2 way to fix.
First - change php.ini file information.

set configurations as following.
   post_max_size=100M
   upload_max_filesize=100M

Second - use .htaccess file.
   php_value upload_max_filesize 100M
   php_value post_max_size 100M


text:
Q: Tomcat 8 change catalina.out permissions to be readable by all The catalina.out file is getting created with "-rw-r-----" permissions (i.e 640 permissions). I want to give read permission to "others" too but that is not happening.
Tried setting umask as 022 in setenv.sh and in other places but this did not help.
Also tried touching files manually using the same tomcat user and they are getting created with "-rw-rw-r--" (i.e 664 permissions). So not sure why tomcat is behaving this way.
Also don't want to manually change the permissions using chmod etc as this is a hack and needs to be repeated in case of file deletion.

A: Solved the problem by adding an environment variable called "UMASK" (all capitals) as follows. This env variable should be set before invoking catalina.sh.
export UMASK="0022"

To give some background, the catalina.sh script looks for UMASK environment variable (Optional). If this variable is not present in the environment, Tomcat uses default UMASK of 0027, else it uses the override value for umask.

A: I am guessing you have already tried these solutions:

*

*setting umask in .profile/.bash_profile.

*Setting umask in etc/init.d/tomcat6 if it is installed.

*verified umask to be existing and restarted the process to check the file permission.

Try giving special permission to the log directory for the required user.
Refer this link for complete configuration.


text:
Q: When I write in csv how do I separate columns in Python My code is
import pymysql
conn=pymysql.connect(host=.................)
curs=conn.cursor()
 import csv
f=open('./kospilist.csv','r')
data=f.readlines()
data_kp=[]
for i in data:
    data_kp.append(i[:-1])

c = csv.writer(open("./test_b.csv","wb"))

def exportFunc():
    result=[]
    for i in range(0,len(data_kp)):
        xp="select date from " + data_kp[i] + " where price is null"
        curs.execute(xp)
        result= curs.fetchall()

        for row in result:
            c.writerow(data_kp[i])
            c.writerow(row)

        c.writerow('\n')

exportFunc()

data_kp is reading the tables name
the tables' names are like this (string, ex: a000010)
I collect table names from here.
Then, execute and get the result.

The actual output of my code is ..

My expectation is

(not 3 columns.. there are 2000 tables)
I thought my code is near the answer... but it's not working..
My work is almost done, but I couldn't finish this part.
I had googled for almost 10 hours..
I don't know how.. please help
I think something is wrong with these part
for row in result:
            c.writerow(data_kp[i])
            c.writerow(row)

A: The csvwriter.writerow method allows you to write a row in your output csv file. This means that once you have called the writerow method, the line is wrote and you can't come back to it. When you write the code:
for row in result:
    c.writerow(data_kp[i])
    c.writerow(row)

You are saying:

"For each result, write a line containing data_kp[i] then write a
  line containing row."

This way, everything will be wrote verticaly with alternation between data_kp[i] and row.
What is surprising is that it is not what we get in your actual output. I think that you've changed something. Something like that:
c.writerow(data_kp[i])
for row in result:
    c.writerow(row)

But this has not entirely solved your issue, obviously: The names of the tables are not correctly displayed (one character on each column) and they are not side-by-side. So you have 2 problems here:
1. Get the table name in one cell and not splitted
First, let's take a look at the documentation about the csvwriter:

A row must be an iterable of strings or numbers for Writer objects

But your data_kp[i] is a String, not an "iterable of String". This can't work! But you don't get any error either, why? This is because a String, in python, may be itself considered as an iterable of String. Try by yourself:
for char in "abcde":
    print(char)

And now, you have probably understood what to do in order to make the things work:
#  Give an Iterable containing only data_kp[i]
c.writerow([data_kp[i]])

You have now your table name displayed in only 1 cell! But we still have an other problem...
2. Get the table names displayed side by side
Here, it is a problem in the logic of your code. You are browsing your table names, writing lines containing them and expect them to be written side-by-side and get columns of dates!
Your code need a little bit of rethinking because csvwriter is not made for writing columns but lines. We'll then use the zip_longest function of the itertools module. One can ask why don't I use the zip built-in function of Python: this is because the columns are not said to be of equal size and the zip function will stop once it reached the end of the shortest list!
import itertools

c = csv.writer(open("./test_b.csv","wb"))

# each entry of this list will contain a column for your csv file
data_columns = []

def exportFunc():
    result=[]
    for i in range(0,len(data_kp)):
        xp="select date from " + data_kp[i] + " where price is null"
        curs.execute(xp)
        result= curs.fetchall()

        # each column starts with the name of the table
        data_columns.append([data_kp[i]] + list(result))

    # the * operator explode the list into arguments for the zip function
    ziped_columns = itertools.zip_longest(*data_columns, fillvalue=" ")

    csvwriter.writerows(ziped_columns)

Note:
The code provided here has not been tested and may contain bugs. Nevertheless, you should be able (by using the documentation I provided) to fix it in order to make it works! Good luck :)


text:
Q: Надёжный установщик сертификатов X509 Для шифрования данных на канальном уровне при работе через Интернет мы используем сертификаты X509. Разворачивание этих сертификатов по инструкции, прилагаемой к нашей продукции - процесс весьма муторный.
Все попытки написать батники или утилиты для автоматизации этой работы не увенчались успехом, т.к. все они обычно работают только на той машине, на которой разрабатываются. Всякие консольные утилиты типа makecert тоже работают только в своей версии Windows.
Может, существуют какие-нибудь библиотеки, которые предоставляют уровень абстракции над зависимостью сертификатов от окружения? Их необходимо встроить либо в приложение, написанное на C#, либо в инсталлятор WIX.
Требования у нас такие.

*

*Пользователь должен иметь возможность создать сертификат, введя имя файла через диалог сохранения файла и пароль. Создаваемый сертификат должен быть связан с нашим корневым центром сертификации.

*Импортировать либо свой сертификат, либо созданный на предыдущем шаге, в хранилище "Доверенные лица" локального компьютера. При этом, если ещё не создан, должен автоматически создасться наш корневой центр сертификации в соответствующем хранилище.

*В зависимости от того, конфигурируется клиент или сервер, должен загружаться либо файл .cer, либо .pfx.

*Если пользователь при импорте сертификата ввёл неправильный пароль, надо это внятно сообщить, без всяких "process {0} exited with code -1".

То есть, пользователь должен иметь возможность сконфигурировать сертификаты одной кнопкой при наличии готового сертификата. Создать сертификат тоже должна быть возможность одной кнопкой.


text:
Q: Xcode 4 - Header file not found when including 3rd party static lib I am trying to check out Nocilla but I can't seem to get my test target to build when I include it. I cloned the Nocilla repo and built the static lib (targeting simulator) from source. I am linking the nocilla static lib to my test target.
I have all of Nocilla's public headers included in my project but for some reason Xcode complains that it cannot find headers which are located in the same relative location from which they are being referenced.
Trying to run my tests results in the following compilation error:

'LSHTTPRequest' file not found

Nocilla provides installation instructions which include using CocoaPods. I am not interested in using CocoaPods. Does anyone have any clues for me as to why my tests cannot find these header files? Am I missing a build step to ensure they are copied to the test execution location?
Thanks!!

A: You must set the User Header Search Paths for the project that wants to include the static library headers:

The exact location of the header files will vary on the relative location between the two projects of course.


text:
Q: How do I set the current frame (or similar) of a CSS animation? I have a CSS keyframe animation that, in itself, is pretty ordinary.  However, I want to be able to force the animation to be at a particular frame.  Something like anim.setProgress(0.13), which would set the animation to be 13% along.  How can I do that?
Note that I don't just want to start the animation at an arbitrary point.  I want to be able to interrupt it and say "go back to 32%" or something, regardless of how far along the animation is.

A: Give the animation a negative animation-delay value. For an animation that runs for 10 seconds, the frame at 13% would be targeted with -1.3s.
Documentation

If the value for 'animation-delay' is a negative time offset then the animation will execute the moment it is applied, but will appear to have begun execution at the specified offset. That is, the animation will appear to begin part-way through its play cycle. In the case where an animation has implied starting values and a negative 'animation-delay', the starting values are taken from the moment the animation is applied.

Example

div.loading {
  animation: loading 10s linear 1;
  animation-play-state: paused;
  animation-delay: -1.3s;
  /*start at 13%*/
}
div.ten-seconds {
  animation-delay: -1s;
  /*start at 10%*/
}
div.zero-seconds {
  animation-delay: 0s;
  /*start at 0%*/
}
/*Note how the keyframes start at 0 width*/

@keyframes loading {
  0% {
    width: 0;
  }
  100% {
    width: 100%;
  }
}
/*Just for this example below*/

input {
  display: none
}
label {
  display: block;
  background: gray;
  width: 120px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  margin: 20px 0 20px 0;
  color: #FFF;
  cursor: pointer;
}
input:checked ~ .loading {
  animation-play-state: running;
}
div {
  height: 100px;
  background: pink;
}
div.ruler {
  width: 13%;
  height: 20px;
  line-height: 20px;
  text-align: center;
  color: #FFF;
  background: gray;
  border-bottom: solid 2px #000;
}
div.ruler.bottom {
  width: 10%;
}
<input type="checkbox" id="start" />
Start / Pause

Go 13%

Go 10%

No delay below


text:
Q: Saving uploaded files I'm trying to save image files that users upload to the host server but I'm not sure how.
When they submit, the file gets sent to javascript where I store the file as a variable. What am I supposed to do next? Do I need to do it in PHP or is there a method I can use to store this file at a specified URL on the server?

A: When you say you store the image in a variable in JavaScript, I assume you are referring to the client's web browser. If this is true, then you haven't yet transmitted it to the server much less stored it anywhere.
Typically you would make a POST request with the image in the form data and the target URL being a PHP script on the server that would process the POST data.
You would want to use an AJAX request instead of a simple form with an action="" URL to avoid leaving the current webpage and landing on the PHP script (which probably doesn't render any HTML, it would just be a blank page).
Libraries like jQuery can make doing POST requests very easy. Here are some tutorials on uploading images to web servers with jQuery and PHP:
http://phppot.com/php/php-ajax-image-upload/
That tutorial assumes you still have the server-side PHP file from their previous tutorial:
http://phppot.com/php/working-on-file-upload-using-php/


text:
Q: WPF app custom ttf font not being used? I downloaded a custom font which displays EAN 128 barcode.
I also downloaded some source code and sample program which converts a string to an encoded string to use with the font (includes check sum etc).
I installed the font, opened my WPF app and set a textblock font to this new font and added some text. The text comes out as if it was Arial or something.
I tried adding the font as a resource and referencing it that way but still not joy.
So I then ran the program that came with the font. The interesting part I found was that when you entered text, the program encoded it and set a label's text and the barcode showed. However, that app allowed you to print preview and print the bar code but when you did the font of the barcode in the print preview and printout changed to like Arial or what ever it was, same issue as I am seeing in my app.
This is how the xaml looks at the moment but as I say, I have tried just setting the font in expression blend.
#Code 128 is the font name and not the file name.
<TextBlock x:Name="tbkBarCode" FontFamily="/Fonts/#Code 128" FontSize="24" HorizontalAlignment="Center"/>

Any ideas?

A: Try this:
<TextBlock x:Name="tbkBarCode" FontFamily="pack://application:,,,/Fonts/#Code 128" FontSize="24" HorizontalAlignment="Center"/>

EDIT: I tried a different font first and this way of doing it worked.
I downloaded and tried it with a Code 128 font and it didn't work right away. To get it to work I had to change the Build Action to "Content" and the Copy to Output Directory to "Copy if newer".

A: If you create a test Windows Forms app, add a TextBox and select the "Code 128" font as the font to use, then it correctly shows the Barcode font.
With WPF it looks the rendering system inside that that deals with fonts doesn't like that particular font for some reason...maybe some information it expects in the file isn't there.
Even "Glyphs" has trouble getting anything sensible out of that font file:
<Glyphs UnicodeString="ABCD1234567890" FontUri="c:\windows\fonts\code128.ttf" Height="50" Fill="#FF000000" FontRenderingEmSize="25"/>

it just returns "blocks".....which means no-character.

When you use a TextBox/TextBlock etc....the fallback font is used to display the content (because it is unable to display it with the Code123 font)......which is why you see the text reverting to the Arial font (or whatever your fallback font is defined to be).

From where did you download the custom font and sample program...was it this place?

*

*http://www.barcoderesource.com/wpfbarcode.shtml
Or from here?:

*

*http://grandzebu.net/informatique/codbar-en/code128.htm
Are you sure the font name is #Code 128 ?
If you copy the .ttf font into your \Windows\Fonts directory and then use CharacterMap, what font names can you see?
After installation with the barcoderesource font, I have these fonts listed:

That would mean using:
FontFamily="CCode128_S3_Trial"

to refer to the font IF it was installed in Windows
or
FontFamily="/Fonts/#CCode128_S3_Trial"

to refer to a .ttf font file embedded into your application.
Did you add the .TTF font file to your project in a folder called "Fonts" and set the Build Type="Resource"?

*

*http://msdn.microsoft.com/en-us/library/ms753303.aspx

A: Here is the method I used to do that...

*

*I add the Font on my project

*I Set property "Build action" of the Font on "Resource"

*Finally, I used the Font like that :

TextBlock Grid.Column="2" HorizontalAlignment="Center" FontSize="32" VerticalAlignment="Stretch" FontFamily="./#Code 128" Grid.Row="5" Margin="1" Text="{Binding Checksum}"/


text:
Q: Connectivity P/invoke to Delphi 5 Because MS only supports their own languages in code equivalent to Delphi *.dcu,
and because their is no msdn for library P/invoke.   I have no connectivity to P/invoke
Has any one got any idea's for connectivity
As a dll do I use loadlibrary and doing so its defeating the purpose
Is P/invoke just extra code to connect to .com
The only thing it offers is universal error messaging as I see.
Has any one got any idea's for connectivity becuse it looks like its what every one is doing to future proff my projects.
Best Regards,
Lex Dean

A: I'm using an old version of Delphi and their are many users with an old version of delphi that need/desire a .net connection.
I cannot find P/Invoke documention to use P/Invoke that I have no option at the moment but to try and convert Visual C# Code to make connectivity to .net if its possible.


text:
Q: Psych's reverse.code function producing NAs in R When using reverse.code in R, the values in my ID column (which are not meant to be reversed) turn into NA once the ID value exceeds 999 (I have 10,110 observations).
Does anyone know if there is anything I can do to fix this?
Is there another function I can use to reverse these items without loosing data?
Here is my code:
library(psych)
keys <- c(1,-1,-1,-1) #Where column 1 = ID and the rest are my variables to be reversed
rev_dat2 <- reverse.code(keys, rev_dat)

Thanks!

A: Here is the relevant line of the source code of reverse.code(), where new is the object holding the reverse-coded data:
new[abs(new) > 999] <- NA

As you can see, setting values larger than 9999 to missing is hard-coded into the routine.  You could write a new version of the function that didn't do that. For example, in the function below, we just make a much larger threshold:
my.reverse.code <- function (keys, items, mini = NULL, maxi = NULL)
{
  if (is.vector(items)) {
    nvar <- 1
  }
  else {
    nvar <- dim(items)[2]
  }
  items <- as.matrix(items)
  if (is.null(maxi)) {
    colMax <- apply(items, 2, max, na.rm = TRUE)
  }
  else {
    colMax <- maxi
  }
  if (is.null(mini)) {
    colMin <- apply(items, 2, min, na.rm = TRUE)
  }
  else {
    colMin <- mini
  }
  colAdj <- colMax + colMin
  if (length(keys) < nvar) {
    temp <- keys
    if (is.character(temp))
      temp <- match(temp, colnames(items))
    keys <- rep(1, nvar)
    keys[temp] <- -1
  }
  if (is.list(keys) | is.character(keys)) {
    keys <- make.keys(items, keys)
    keys <- diag(keys)
  }
  keys.d <- diag(keys, nvar, nvar)
  items[is.na(items)] <- -99999999999
  reversed <- items %*% keys.d
  adj <- abs(keys * colAdj)
  adj[keys > 0] <- 0
  new <- t(adj + t(reversed))
  new[abs(new) > 99999999999] <- NA
  colnames(new) <- colnames(items)
  colnames(new)[keys < 0] <- paste(colnames(new)[keys < 0],
                                   "-", sep = "")
  return(new)
}

The reason they used a numeric value threshold is that for the recoding they do to work, they needed all values to be numeric.  So, they set missing values to -999 and then later turn them back into missing values.  The same is done above, but with a lot bigger number.
keys <- c(1,-1,-1,-1) #Where column 1 = ID and the rest are my variables to be reversed
rev_dat <- data.frame(
  id = 9998:10002,
  x = 1:5,
  y = 5:1,
  z = 1:5
)
library(psych)
reverse.code(keys, rev_dat)
#      id x- y- z-
# [1,] NA  5  1  5
# [2,] NA  4  2  4
# [3,] NA  3  3  3
# [4,] NA  2  4  2
# [5,] NA  1  5  1
my.reverse.code(keys, rev_dat)
#         id x- y- z-
# [1,]  9998  5  1  5
# [2,]  9999  4  2  4
# [3,] 10000  3  3  3
# [4,] 10001  2  4  2
# [5,] 10002  1  5  1


text:
Q: What is the difference between isdigit() and isnumber()? I have the function isnumber() in my ctype.h. I don't find references of this function in the books I have neither in http://www.cplusplus.com/reference/cctype/ for consult.
I intend to detect and show the difference between isdigit() and isnumber() by a simple  example, but there is not (besides, U+0C6A, U+0ED2 and ½ are undetectable by the functions).
Is there any difference? How could I resolve that?
int main(int, char *[])
{
    string text("Hello½123, Poly౪ ໒girl0.5!!!");
    decltype(text.size()) punct = 0, alpha = 0, number = 0, space = 0, digit = 0, graf = 0;
    for(auto i : text) {
        if(ispunct(i)){
            cout << i << "<punct  ";
            ++punct;
        }
        if(isalpha(i)) {
            cout << i << "<alpha  ";
            ++alpha;
        }
        if(isnumber(i)) {
            cout << i << "<number  ";
            ++number;
        }
        if(isdigit(i)) {
            cout << i << "<digit  ";
            ++digit;
        }
        if(isgraph(i)) {
            cout << i << "<graph  ";
            ++graf;
        }
        if(isspace(i))
            ++space;
    }
    cout << endl << "There is " << endl;
    cout << punct <<  " puncts," << endl;
    cout << alpha << " alphas," << endl;
    cout << number << " numbers," << endl;
    cout << digit << " digits," << endl;
    cout << graf << " graphs," << endl;
    cout << space << " spaces" << endl;
    cout << "in " << text << endl;

    return 0;
}

A part of the result:
...

5 numbers,
5 digits,
23 graphs,
2 spaces
in Hello½123, Poly౪ ໒girl0.5!!!

A: isnumber() may be an Apple-specific C++ method (I don't have a Mac on hand to check).
You can see it in the Apple dev guide:

The isnumber() function behaves similarly to isdigit(), but may recognize additional characters, depending on the current locale setting.

Besides, isnumber() is not declared on Linux:
I use g++ 6.1.1 on Linux 4.7.2 and get the error:
g++ a.cpp
a.cpp: In function 'int main(int, char**)':
a.cpp:20:17: error: 'isnumber' was not declared in this scope
   if (isnumber(i)) {
                 ^

I also use clang3.8.1 to test:
clang++ a.cpp --std=c++11
a.cpp:20:7: error: use of undeclared identifier 'isnumber'
                if (isnumber(i)) {
                    ^

A: isdigit() only works with 0-9.
isnumber() allows other number values such as fractions. Some characters that are 'numeric' but not digits include 0x00b2 and 0x00b3 which are superscripted 2 and 3 ('²' and '³') and the glyphs that are fractions such as '¼', '½', and '¾'.

A: The isnumber() function was added by Apple, so you need to use Apple documentation.
Here's a quote from the ctype.h manpage for iOS†:

STANDARDS
     These functions, except for digittoint(), isascii(), ishexnumber(),
     isideogram(), isnumber(), isphonogram(), isrune(), isspecial() and
     toascii(), conform to ISO/IEC 9899:1990 (``ISO C90'').

The same page doesn't actually link to a manpage for isnumber(), but I extrapolated its URL from the links to manpages for the standard functions, and found this:

The isnumber() function behaves similarly to isdigit(), but may recognize
additional characters, depending on the current locale setting.

† Result #4 on Google for isnumber ctype…


text:
Q: Windows Defender seems to be flagging Java applications I'm trying to evaluate some software tools (ERD diagrams) and have downloaded dbSchema and ModelXtractor.  Attempting to install either tool results in a Windows Defender popup:

dbSchema provides three different packges, a self-extracting .exe, a .msi and a .zip file.  The first two flag on attempting to launch. The .zip can be extracted, but attempting to run the app executable also alerts.
The vendor provides md5 checksums on their website, and all three files (.exe, .msi and .zip) match.
Is Windows Defender alerting on vulnerable versions of log4j?
I did a Google search and didn't find anything.

A: Some versions of log4j have a critical safety bug. Maybe you have it because of this bug.
https://logging.apache.org/log4j/2.x/security.html


text:
Q: How can I automate creation of GPO shutdown script? I'm managing Windows VMs in AWS ASGs that are not attached to a domain. I want to run a script at shutdown (not logoff) to remove these nodes from Chef, and I want to create/register the scripts using Chef. I have the removal script ready, it's getting them to run at shutdown that I cannot find an implementation for.
I can do it manually via gpedit.msc Local Computer Policy -> Computer Configuration -> Windows Settings -> Scripts (Start/Shutdown) -> Shutdown. This places the scripts in C:\WINDOWS\System32\GroupPolicy\Machine\Scripts\Shutdown. Unfortunately:

*

*It looks like the scripts directories are only created when gpedit.msc is first run, and it's unclear if creating them manually is valid

*Just placing scripts there does not on its own seem to register them - they don't show up in gpedit.msc

*Placing the script and running gpupdate /force (as suggested here) also doesn't cause it to show up in gpedit, though gpupdate did suggest a reboot may be required to apply some changes - that's not an option as a reboot in an ASG may cause instance termination and replacement

I'm aware of a possible use of Task Scheduler to run a script at shutdown, but (from my research at least) it seems that the key difference is that a task scheduler shutdown script only has as much time to run as the system takes to shutdown, whereas a GPO shutdown script will postpone shutdown until it finishes.
So, the question is: is there a way, via Chef (i.e. via PowerShell, DSC, or batch script) to register a GPO shutdown script on a machine not attached to AD without rebooting?

A: Try using this LGPO utility. You should be able to use the GUI to config the shutdown script on a pilot machine, back it up with LGPO, and then use LGPO to import it onto newly built systems.
https://blogs.technet.microsoft.com/secguide/2016/01/21/lgpo-exe-local-group-policy-object-utility-v1-0/

A: Thanks to insight from @Clayton's answer and from this answer to another question, I was able to get it working on Win2016. I had to create C:\Windows\System32\GroupPolicy\Machine\Scripts\psscripts.ini:
[Startup]
0CmdLine=C:\WINDOWS\System32\GroupPolicy\Machine\Scripts\Shutdown\seppuku.ps1
0Parameters=

As well as set a slew of registry keys:

*

*HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0

*HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0\0

*HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0

*HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0\0

*HKLM\SOFTWARE\Policies\Microsoft\Windows\System\Scripts\Shutdown\0

*HKLM\SOFTWARE\Policies\Microsoft\Windows\System\Scripts\Shutdown\0\0
Those ending in \Shutdown\0 get policy values:
"GPO-ID"="LocalGPO"
"SOM-ID"="Local"
"FileSysPath"="C:\\Windows\\System32\\GroupPolicy\\Machine"
"DisplayName"="Local Group Policy"
"GPOName"="Local Group Policy"
"PSScriptOrder"=dword:00000001

Those ending in \Shutdown\0\0 get script values:
"Script"="C:\\WINDOWS\\System32\\GroupPolicy\\Machine\\Scripts\\Shutdown\\seppuku.ps1"
"Parameters"=""
"IsPowershell"=dword:00000001
"ExecTime"=hex(b):00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00

This is for a PowerShell shutdown script located at C:\WINDOWS\System32\GroupPolicy\Machine\Scripts\Shutdown\seppuku.ps1. Setting all this is a pain but entirely possible using Chef, and after a converge, I see the script registered in gpedit.msc. I have yet to fully confirm the script actually executes at shutdown, that's my next step, but I believe it should.


text:
Q: R: shiny: all components in a panel stretch to 100% I have a WellPanel which has 2 selectInputs as 2 rows. By default they stretch across the panel. This seems to happen for all panels, for e.g. all components in sidebar panel stretch. Is there a way to set the width to max selection length in options?

A: sidebarPanel(..., width = 4)

sidebarPanel(..., width = "100%")

sidebarPanel(..., width = NULL)


text:
Q: What's the size of an ASP.NET 3.5 session ID? Is it 32 bit, or 64 bit or 128 bit or bigger?

A: The reason for the extra 8 characters in the database vs what you get in code is the application id.  In the database the session is appended with the tempApplicationID from ASPStateTempApplications table.  This is why you get 24 characters in code, and 32 in the db.

A: It's neither int nor guid; from the MSDN help file...

The ASP.NET session identifier is a randomly generated number encoded into a 24-character string consisting of lowercase characters from a to z and numbers from 0 to 5.

A: I would go with 88 bytes. If you look at the ASP.NET state database, that is how it is defined.

A: Because it's generated as a System.Guid Valuetype, it's a 128-bit integer, which is 16 bytes.


text:
Q: How to lower a files length by chopping off its beginning rather than the end part? I've been using SetFilePointer/SetEndOfFile to manage the size of the memory mapped files I got. I've had a bunch of trouble with windows filesystem responding to the rapid changes I sometimes need to make but I think I finally got a hang of it.
Currently it seems like the best solution would be to make a new file each time I need to grow/shrink my data (it needs to temporarily coexist with the old file) but another potential solution would be if I could extend the file and after the old section loses its significance just cut it out. That would make it all neat and tidy.
I couldn't find any reference as to how I could actually do it though. Also would it be possible to preserve the map views (pointing to the same new part despite their actual position in regards to file start being different) throughout the resizing effort?


text:
Q: dynamically change css class using js I'm having a problem while trying to dynamically change a table cell's styling class using JavaScript.
The following issue happens on FF, I opened the page on other browsers too and it worked fine.
I have a html page that contains a 4x4 table. I would like when I click on a cell, to zoom it in and when I click on it again to zoom it out. I defined 2 CSS classes, one for the normal size cell and one for the zoomed cell. I am using JS to change the CSS class when a cell is clicked.
The issue on FF is that when changing from zoomClass to normalClass all the cells to the right of the clicked cell are shifted to the right...
I can't find a solution or a workaround for this problem, if somebody has any ideas please post them here.
Next, I will attach the html, css and js files.
Thanks :)
util.js

function zoom(id) {

    if (document.getElementById(id).className == "zoomClass") {

        document.getElementById(id).className = "normalClass";

    } else {

        document.getElementById(id).className="zoomClass";

    }

}

calendar.css

table, td, th, tr {
    border-color:#D2D3D4;
    border-style:solid;
    border-width:2px;
}

#main_table {
    border-spacing:1px;
    height:450px;
    margin-left:auto;
    margin-right:auto;
    position:relative;
    top:30px;
    width:850px;
}

td.normalClass {
    padding:0;
    font-size:4px;
    color:#3333FF;
}

td.zoomClass {
    display:inline;
    position:absolute;
    width:320px;
    height:240px;
    z-index:100;
    font-size:18px;
}

test.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <link rel="stylesheet" type="text/css" href="css/calendar.css" media="screen" />

A: This is how tables work. I possible I would try and do the same thing using divs and then you should be able to deal with the problem using position:absolute so the expanded div will overlay the others. This could work the same for a table cell.

A: Unfortunately "position" doesn't work on table cells. You could try putting a div inside the table cell and positioning that.
Edit: Something like this should do the trick:
td.normalClass div {
    display: none;
}
td.zoomClass div {
    display: block;
    position: absolute;
    width: 320px;
    height: 240px;
}

Make sure the div is the first thing in the td and it'll be positioned at the td's top left corner. You might need to play with relative positioning on the td if you need to change the top and left values further.

A: A few comments on your code, if I may. I would keep the layout in the CSS file and not in the HTML, so I'd remove all of those align="right" and valign="top". Also, you can reference the cells in your table much more efficiently. Then you won't have to set the class for each cell.
#main_table td{
    padding:0;
    font-size:4px;
    color:#3333FF;
}

I would also keep all of the behaviour of the page in a separate script file (Javascript). So no more onclick="zoom(x)" at every cell. You can use event binding to do that.
Also, if you use event binding, you can just "read" the id of the clicked cell, so you don't have to pass that value in statically in the call of the zoom function.
Lastly: I can highly recommend using jQuery to do this kind of DOM manipulation as it's a lot easier, the code is shorter and more readable and your scripts work across browsers pretty much out of the box.
I don't have a solution for this specific problem but using jQuery it's quite easy to insert a new DOM element, a div for instance, with the content of the clicked cell, float over the table and simulate the zoom effect. That div would be be absolutely positionable and can be styled a lot better than the cell the user clicked on.


text:
Q: Reducing object values based on values pulled from array? I am building an idle game with JavaScript.
It is a game where you run a bakery.
The resources of the bakery are represented within an object 'mainObj'.
let mainObj = {
  "Money": 100,
  "Resources": {
    "Milk": 10,
    "Eggs": 10,
    "Flour": 10,
    "Water": 10,
    "Sugar": 10
  },
  "Employees": {
    "Bakers": 1,
    "Cooks": 0,
    "Servers": 0,
    "Farmers": 0
  },
  "Inventory": {
    "Cake": 0,
    "Cookies": 0
  }
}

The associated costs to bake an item, such as a cake or cookies, are stored in the array 'bakeInfo'.
let bakeInfo = [{
  "Name": "Cake",
  "Milk": 1,
  "Eggs": 2,
  "Flour": 1
}, {
  "Name": "Cookies",
  "Eggs": 1,
  "Flour": 1
}]

I want to write a function that takes the info from bakeInfo, such as for baking a cake (1 Milk, 2 Eggs, 1 Flour) checks the mainObj for the required ingredients (and throws an error if there isn't enough) and if there is enough of each, it reduces the ingredients in resources by the amount in bakeInfo, and then adds the appropriate item (cake/cookies) to the mainObj inventory.
I've tried a few different ways to go about it, which pretty much entails an individual function for each ingredient type, which seems extremely inefficient to me.
Also, some items that will be baked omit some ingredients (cookies don't require milk). So if the function checked this/only removed required items from the mainObj inventory that would be ideal, in fact, it is necessary.
If someone could point me in the right direction that would be great.

A: Marko's solution above is for adding one item at a time. However, if you want to check multiple items at a time, and error if there isn't enough ingredients for all of them, this solution might be better:

let mainObj = {
  Money: 100,
  Resources: {
      Milk: 10,
      Eggs: 10,
      Flour: 10,
      Water: 10,
      Sugar: 10
  },
  Employees: {
      Bakers: 1,
      Cooks: 0,
      Servers: 0,
      Farmers: 0
  },
  Inventory: {
      Cake: 0,
      Cookies: 0
  },
}

let bakeInfo = [
  {Name: 'Cake', Milk: 1, Eggs: 2, Flour: 1},
  {Name: 'Cookies', Eggs: 1, Flour: 1}
]

function bakeOrError(bakeInfo, mainObj) {
  // first make a copy of resources
  const resources = Object.assign({}, mainObj.Resources);
  // now, iterate over all the bakeInfo and reduce resources
  bakeInfo.forEach(bi => {
    Object.keys(bi)
      .filter(k => k !== 'Name') // don't operate on the Name key, everything else is an ingredient
      .forEach(k => {
        resources[k] -= bi[k];
        if (resources[k] < 0) throw new Error('insufficient resources');
      })
  })

  // if we haven't errored by here, there were enough ingredients to support everything.
  // update the resources object
  mainObj.Resources = resources;
  // then add to inventory
  bakeInfo.forEach(bi => mainObj.Inventory[bi.Name]++);
}

bakeOrError(bakeInfo, mainObj);
console.log(mainObj);

A: This should work:
function reduceResources(info){
  let bakeInfoKeys = Object.keys(info);

  // check if there is enough resources
  bakeInfoKeys.forEach(key => {
    if(mainObj.Resources[key] !== undefined){
        if(mainObj.Resources[key] < info[key])
            return false; // return false if there is not enough resources
    }
  });

  // reduce the resource amount
  bakeInfoKeys.forEach(key => {
    if(mainObj.Resources[key] !== undefined){
        mainObj.Resources[key] -= info[key];
    }
  });

  // add the item to the inventory
  mainObj.Inventory[info['Name']] += 1;

  return true;
}

The function will return true if it was successful, and false if the resources are not enough.
You can use it like this:
if(reduceResources(bakeInfo[0]))
    console.log("Success!")
else
    console.log("Fail!")

A: With the makeItem function below, you could make cakes until your run out of resources by using a try-catch and throwing an Error when the minimum number of required resources cannot be met.

const player = {
  "Money": 100,
  "Resources": { "Milk": 10, "Eggs": 10, "Flour": 10, "Water": 10, "Sugar": 10 },
  "Employees": { "Bakers": 1, "Cooks": 0, "Servers": 0, "Farmers": 0 },
  "Inventory": { "Cake": 0, "Cookies": 0 }
};

const recipes = [
  { "Name": "Cake", "Milk": 1, "Eggs": 2, "Flour": 1 },
  { "Name": "Cookies", "Eggs": 1, "Flour": 1 }
];

const retrieveRecipe = (name) =>
  recipes.find(({ Name }) => Name === name);

const canMake = (player, recipe) => {
  const found = retrieveRecipe(recipe);
  if (found == null) return false;
  const { Name, ...ingredients } = found;
  const { Resources } = player;
  return Object.entries(ingredients)
    .every(([ name, amount ]) => amount <= Resources[name]);
}

const makeItem = (player, recipe) => {
  if (!canMake(player, recipe)) throw new Error('Insufficient resources');
  const found = retrieveRecipe(recipe);
  const { Name, ...ingredients } = found;
  Object.entries(ingredients).forEach(([name, amount]) => {
    player.Resources[name] -= amount;
  });
  player.Inventory[Name]++;
}

// Make cakes until required resources cannot be met.
try {
  while (true) {
    makeItem(player, 'Cake');
  }
} catch (e) {
  console.log('Ran out of resources!');
}

console.log(player);
.as-console-wrapper { top: 0; max-height: 100% !important; }


text:
Q: Not so smoothly sliding down/up and details and thumbnail relate before sliding detail Use Bootstrap 3

    Thumbnail 1

    Thumbnail 2

    Thumbnail 3

    Thumbnail 4

CSS
.details{
  display: none;
}

JQuery
$('.thumbnail').on('click', function(e){
console.log('here');
$('.details').slideToggle('slow');
$(this).addClass('active');
$('.thumbnail').removeClass('active');
});

Two issues:
1. when it slide down, it is not sliding smoothly. Is there any way to use CSS3 animation to make the details slide up and down smoothly? For example, the whole detail div should show all info at one go. Slidetoggle slide down giving details bit by bit in a sense.
2. Realized that details div will be outside the thumbnails. How to relate detail div to clicked thumbnails?
Updated
JSFiddle Demo
Tried data-rel to see if it show specific detail when clicking specific thumbnail but it seems not to work?

A: For the smoothness issue, try the velocity plugin (or similar). It converts animate() style commands (use velocity() instead) into CSS animation behind the scenes (much smoother). That usually means you have to replace all your slideToggle() function etc with the animate(...) equivalent, then rename them to velocity(...).
Velocity link: http://julian.com/research/velocity/
For the second issue, use data- attributes to mark what the associated element is (could use an id, a class selector, or whatever you like).
Your HTML is incomplete, but use it like this:

and

    Thumbnail 1

and change the click handler to lookup the related element:
$('.thumbnail').on('click', function(e){
    var target = $(this).data('rel');
    var $target = $(target);

    // Close all but the new target and open it
    $('.details').not($target).slideUp();
    $(target).slideDown('slow');

    // Remove active from all active elements
    $('.thumbnail .active').removeClass('active');

    // Add active only to this element
    $(this).addClass('active');
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/fpx9gvzw/3/
You can use an id selector with IDs on the target elements, a class selector with unique classes on the targets, or a data- attributes on the targets and match with a selector like $([data-rel="..."]) but that is much slower (not that speed matters on this).
Note: I am not a huge fan of the "toggle" animation methods (except to toggle a current element), as the state can get messed up, hence using not and the slideUp and slideDown on appropriate elements.

A: jsFiddle demo
$('.thumbnail').on('click', function(e){
    var rel = $(this).data().rel;

    $('.details').stop().slideUp('slow');                       // all up!
    $('.details[data-rel='+rel+']').stop().slideToggle('slow'); // this toggle

    $('.thumbnail').removeClass('active'); // Remove from all
    $(this).addClass('active');            // Add to this
});


text:
Q: Subset multiple different rows of a Data frame Hi How can I subset 2 different N random samples in a data frame. See example below.
I have df the main dataset. I need 2 subsets of the main dataset. I got 2 subsets by getting 3 random rows from the main dataset. However I need those 2 subsets to be unique with each other.
> df = data.frame(matrix(rnorm(20), nrow=10))
> df
            X1          X2
1   0.19234071 -0.86702704
2  -0.18264853  1.75276062
3   0.75824257 -0.51314220
4  -0.84571563 -1.24841675
5   0.75470152  1.51408945
6   1.04546517  1.33292716
7  -0.51449011 -1.51275633
8   1.36014747  0.07400024
9  -0.02397481  0.17177997
10 -1.37967248 -0.50416489

df1 = df[sample(nrow(df), 3), ]
df1
           X1         X2
10 -1.3796725 -0.5041649
1   0.1923407 -0.8670270
4  -0.8457156 -1.2484167

df2 =  df[sample(nrow(df), 3), ]
df2
          X1         X2
3  0.7582426 -0.5131422
4 -0.8457156 -1.2484167
6  1.0454652  1.3329272

As you can see the random subsets df1 and df2 have same row which is the row 4. I need 2 random subsets of the dataframe that had different rows.

A: If you want to split the data into 2 distinct sets, you can create an index and split the frames, something like this
set.seed(42)
idx <- sample(1:nrow(df), 3)
df1 <- df[idx, ]
df2 <- df[-idx, ]
df1
         X1        X2
10 1.359814 0.6919378
9  1.248144 0.9783253
3  1.903994 0.4371896
df2
          X1          X2
1 -0.3743900  0.54040310
2 -0.3204993  0.02383999
4 -0.2552918  0.94148533
5 -0.7327228 -1.25263998
6 -1.0648850  0.06567222
7 -0.2147909 -0.19137447
8  1.2148835  1.36361765

For much more complex splits, do see caret::createDataPartition

A: We can create a function if we nee to reuse the same logic
f1 <- function(data, n) {
      data[sample(nrow(data), n),]
}

Or if we need to create train/test dataset, we can use split
lst1 <- split(df,  seq_len(nrow(df)) %in% sample(nrow(df), 3))

A: You could also do something like this-
idx <- sample(seq(1, 2), size = nrow(df), replace = TRUE, prob = c(.8, .2))
set1 <- df[idx == 1,]
set2 <- df[idx == 2,]

Output-
> set1
            X1         X2
1  -0.85768451 -0.1545485
2  -0.76420259  1.2054883
3  -0.91973457  1.4867429
6  -1.07558176  0.2527374
7   0.03189408  1.4057502
8   0.64270649  1.3742131
9   1.59246097 -0.3845688
10 -0.14158552 -1.5792062

> set2
          X1         X2
4 -0.6317524 0.06571271
5  0.5005460 0.46277511

Note**- You can change split percent in sample function. I have used 80-20%.


text:
Q: create UIView with xib in Swift I want to create a Custom View with xib,
So I did CreateTask.xib that contain a TextField
and class is CustomUIView: UIView
I follow this step from
http://swiftdeveloperblog.com/creating-custom-user-interface-files-with-xib-in-xcode-6-and-swift/

import UIKit

class CreateTaskView: UIView {

@IBOutlet weak var taskNameField: UITextField!
var nibView: UIView!

var taskName: String? {
    get {
        if taskNameField == nil {
            return "taskNameField is nil"
        }
        if let s = taskNameField.text {
            return s
        } else {
            return ""
        }
    }
}

override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init?(coder aDecoder: NSCoder) {
    print("infinite loop")
    super.init(coder: aDecoder)
    setup()
}

func setup() {
    nibView = loadViewFromNib()
    nibView.frame = bounds
    nibView.autoresizingMask = [UIViewAutoresizing.flexibleWidth ,UIViewAutoresizing.flexibleHeight]
    addSubview(nibView)
}

func loadViewFromNib() -> UIView {
    let nib = UINib(nibName: "CreateTask", bundle: nil)
    let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView

    return view
}

}

when i instance CreateTaskView, that CreateTaskView was created infinite by loadViewFromNib(), I think it probably the reason is "xib class is CustomUIView", so I take it out.
but i can't get the UITextField outlet in xib now, how can i do?

A: It is not a good idea to create nib from the class itself, instead the class that creates the instance of the customview should load the view with its nib file. An Objective-C example:
CustomView *myView = (CustomView *)[[[NSBundle mainBundle] loadNibNamed:@"CustomViewXIB" owner:nil options:nil] firstObject];

It will create the instance of CustomView class by using its corresponding XIB file.

A: *

*Go to CreateTask.xib and tap on File's Owner tab

*set the owner of the xib by tapping Identity Inspectorand set the custom class as CreateTaskView

*then try creating the outlet of textfield to CreateTaskView


text:
Q: Cannot load VGG19 ImageNet weights stored in a ".mat" file on disk I'm trying out transfer learning and I have downloaded weights for VGG19 model from ImageNet dataset. It downloaded as a ".mat" file. At first I tried to load in the entire .mat file as
import tensorflow as tf
from tensorflow.keras.applications.vgg19 import VGG19

model_path = os.path.join('trained_model', 'imagenet-vgg-verydeep-19.mat')
pre_trained_model = VGG19(weights = None, include_top = False)
pre_trained_model.load_weights(model_path)

but, I got the following error.
OSError: Unable to open file (file signature not found)

Then I tried the set_weights() method instead of load_weights(), as
pre_trained_model = VGG19(weights = None, include_top = False)
pre_trained_model.set_weights(model_path)

then I got the following error,
ValueError: You called `set_weights(weights)` on layer "vgg19" with a weight list of length 42,
but the layer was expecting 32 weights. Provided weights: trained_model\imagenet-vgg-verydeep-19.mat...

I have also tried
pre_trained_model = VGG19(weights = None, include_top = True)
pre_trained_model.set_weights(model_path)

but, I still get the same errors.
I have downloaded the weights from https://www.kaggle.com/teksab/imagenetvggverydeep19mat

A: you can't load weights cause layer size are different.
here is the way you can :
How to read .mat file format in tensorflow?

A: This line pre_trained_model = VGG19(weights = None, include_top = False)
include_top = False means that the model does not load the fully connected layers. Have you checked if the pretrained model on Kaggle uses include_top = True?


text:
Q: Two branches pull request yeilds entirely different commit histories I cloned a repo to my computer:
git clone <repo>

Then I created a new repo on Github.
In my cloned repo I assigned a remote origin:
git remote <new repo>

I got two branches: main (marked as 'default' on Github) and master.
I started working with master. Everything was fine, I could even 'push' my changes. But when I tried to create a pull request to merge master into main.
I didn't get a PR button and got the notification that

There isn't anything to compare.
main and master are entirely different commit histories.

I tried to find a solution, but because of my lack of experience with Git I can't decide if one of them fits in to my problem. Here are many [examples][1].
How can I merge my changes from master into main?

A: If you're receiving this error for a newly created Github repo, it's likely that you added files to your default main branch during project creation, for example a README.md.
Your local master branch will indeed have no shared history with your remote main branch, and you cannot create pull requests from one to the other.
To fix this, you need to check fetch your main branch locally and then rebase your master branch on top of it, so that it shares main's history:
git fetch
git checkout master
git rebase origin/main


text:
Q: Help with this determinant I need help to calculate this determinant:
$$\begin{vmatrix}
1^k & 2^k & 3^k & \cdots & n^k \\
2^k & 3^k & 4^k & \cdots & (n+1)^k\\
3^k & 4^k & 5^k & \cdots & (n+2)^k\\
\vdots & \vdots & \vdots & \ddots & \vdots\\
n^k & (n+1)^k & (n+2)^k & \cdots & (2n-1)^k
\end{vmatrix}$$
Where $2\leq n$ and $0\leq k \leq n-2.$
I did the $2\times 2$, $3\times 3$ and $4\times 4$ cases but I couldn't find a pattern to follow.
I did those cases by making zeros in the first column (except the $1^k$ in the first row) and then using the Laplace expansion.
The $2\times 2$ case equals: $3^k -4^k$, the  $3\times 3$ case equals: $15^k -16^k -20^k -27^k +24^k +24^k$

A: For any $n \ge 1$, let $u_1, \ldots, u_n$ and $v_1,\ldots ,v_n$ be any elements
in any commutative ring.
For any $0 \le k \le n-2$, consider the $n \times n$ matrix $A = (a_{ij})$ whose entry at row $i$ and column $j$ has the form:
$$a_{ij} = (u_i + v_j)^k$$
By binomial theorem, it can be decomposed as
$$a_{ij} = \sum_{\ell=0}^k \binom{k}{\ell} u_i^\ell v_j^{k-\ell}$$
This means $A$ can be rewritten as a sum of $k+1$ matrix products of column vectors
$$A = \sum_{\ell=0}^k \binom{k}{\ell} U_\ell V_{k-\ell}^T
\quad\text{ where }\quad
U_\ell = \begin{bmatrix}u_1^\ell \\ u_2^\ell \\ \vdots \\ u_n^\ell\end{bmatrix}\text{ and }
V_\ell = \begin{bmatrix}v_1^\ell \\ v_2^\ell \\ \vdots \\ v_n^\ell\end{bmatrix}.
\tag{*1}$$
Since matrix product of a pair of column vectors has rank at most $1$ and matrix rank are sub-additive, i.e. ${\rm rank}(P + Q) \le {\rm rank}(P) + {\rm rank}(Q)$, we get
$${\rm rank}(A) \le \sum_{\ell=0}^k {\rm rank}(U_\ell V_\ell^T) \le \sum_{\ell=0}^k 1 = k+1 < n$$
As a result, matrix $A$ doesn't have full rank and hence $\det A = 0$.
For the problem at hand, take $u_i = i$ and $v_j = j-1$.
When $0 \le k \le n - 2$, the determinant at hand vanishes.
Update
If one doesn't want to use the concept of rank, there is another approach.
Construct three auxiliary $n \times n$ matrices by

*

*$U$, whose $\ell^{th}$ column is the column vector $U_{\ell-1}$ for $1 \le \ell \le k+1$ and zero otherwise.

*$V$, whose $\ell^{th}$ column is the column vector $V_{k-\ell+1}$ for $1 \le \ell \le k+1$ and zero otherwise.

*$D$, a diagonal matrix whose $\ell^{th}$ diagonal entry is $\binom{k}{\ell-1}$
for $1 \le \ell \le k+1$ and zero otherwise.

The decomposition of $(*1)$ can be rewritten as $A = UDV^T$.
When $k < n - 2$, $U$ contains a zero column and hence
$$\det U = 0\quad\implies\quad\det A = \det U \det D \det V = 0$$
As a side benefit, this approach allow us to compute the determinant at hand when $k = n - 1$.
When $u_i = i$ and $v_j = j - 1$,
$U$ is a Vandermonde matrix
with determinant
$$\det U = \prod_{1\le i < j \le n}(u_i - u_j) = \prod_{1\le i < j \le n}(i-j) = (-1)^{n(n-1)/2} \prod_{\ell=1}^{n-1} \ell!$$
$V$ can be obtained from a Vandermonde matrix but reversing the order of its columns. It is easy to see its determinant equals to
$$\det V = \prod_{1 \le i < j \le n }(v_j - v_i) = \prod_{1 \le i < j \le n}(j-i)
= \prod_{\ell=1}^{n-1} \ell!$$
The determinant of $D$ is easy, it is just the product of a bunch of binomial coefficients.  Combine these, when $k = n - 1$, the determinant at hand becomes
$$\left. \det A  \right|_{k=n-1}
= (-1)^{\frac{n(n-1)}{2}} \prod_{\ell=0}^{n-1}\binom{n-1}{\ell} \times \left(\prod_{\ell=1}^{n-1}\ell!\right)^2 = (-1)^{\frac{n(n-1)}{2}} ((n-1)!)^n$$

A: Another proof:
Consider the polynomials $P_1(X)=(X+1)^k,\; P_2(X)=(X+2)^k,\dots,\;P_n(X)=(X+n)^k$, which belong to the vector space $\mathbf R_k[X]$ of polynomials of degree at most $k$. This space has dimension $k+1$, hence, if $n>k+1$ (i.e. $k\le n-2$), these polynomials are linearly dependent, so there's a linear relation with  coefficients $\lambda_i\enspace (1\le\lambda\le n)$, not all $0$, such that the polynomial
$$Q(X)=\sum_{i=1}^{n}\lambda_iP_i(X)=0.$$
Now  observe row n° $i$ in the determinant is just $\;\bigl(P_1(i-1), P_2(i-1), \dots P_n(i-1)\bigr)$, so $Q(i-1)=0$ for all $i=1,\dots,n.\,$ If   $C_i$ denotes the $i$-th column of the determinant, this shows we have the following linear relation between columns:
$$\sum_{i=1}^{n}\lambda_i\,C_i=0, $$
hence the determinant is $0$, under the assumption $k\le n-2$.

A: Another proof.
This involves some tricks on manipulating polynomials.
$\mathit{Proof}.\blacktriangleleft$
Consider
$$
f(z) =
\begin{vmatrix}
(z+1)^k & (z+2)^k & (z+3)^k & \cdots & (z+n)^k\\
2^k & 3^k & 4^k & \cdots &  (n+1)^k\\
3^k & 4^k & 5^k & \cdots & (n+2)^k \\
\vdots & \vdots & \vdots & \ddots & \vdots\\
n^k & (n+1)^k & (n+2)^k & \cdots & (2n-1)^k
\end{vmatrix}.
$$
Then the computational definition determinant, i.e.
$$
\det(\boldsymbol A) = \sum_{\sigma \in \mathfrak S_n} \mathrm{sgn}(\sigma) \prod_1^n a_{\sigma(j), j}
$$
implies that $f(z)$ is a polynomial of degree $k$. The goal is to compute $f(0)$. Note that $f(1) = f(2) = \cdots = f(n-1) = 0$, since the $1^{\mathrm {st}}$ row coincides with the $ (j+1 )^{\mathrm {st}}$ row, and a determinant with duplicated rows is $0$. Therefore $f(z)$ is a real  polynomial with $n-1$ zeros while its degree is $k \leqslant n-2$. Thus the polynomial is just the zero polynomial, and the original determinant is $f(0) = 0$. $\blacktriangleright$


text:
Q: What scanners are there for Ubuntu 16.04? Can anyone recommended some scanners for Ubuntu 16.04?

A: I have a Samsung Xpress M2070W. It is a Monochromatic Laser Printer and Scanner. It perfectly works in Linux Mint 18  with the drivers downloaded directly from Samsung website.


text:
Q: Writting a simple mail client and server, user authentication by using signature, verifying signature , user failed to login Here are my codes in github. Click [here] https://github.com/bearer1024/cryptographyEmail
user failed to pass verifyLogin every times, even given with right .pub and .prv key. I'm quite sure problem is about signature. But I don't know how to solve it.
her are my running output in client side:
java MailClient localhost 1111 bearer
in the client,the length of signature is :256
false
failed to login
Here are running output in server side:
java MailServer 1111
Welcome...
in the server,the length of signature is:256
verifying for clientid is:bearer
Server position2
Client failed to log in
Client bearer failed to log in.
client login codes:
// connect to server
        Socket s = new Socket(host,port);
        DataInputStream dis = new DataInputStream(s.getInputStream());
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
        oos.flush();
        ObjectInputStream ois = new ObjectInputStream(s.getInputStream());

        // TO DO: login

        // these two lines are here just to make the supplied programs run without crashing.
        // You may want to change them, and certainly add things after them
        dos.writeUTF(userid);

        String userPrivateKeyFileName = userid + ".prv";
        // Get the key to create the signature
        ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(userPrivateKeyFileName));
        PrivateKey privateKey = (PrivateKey)keyIn.readObject();
        keyIn.close();

        // create timeStamp and random number
        long t1 = (new Date()).getTime();
        // ByteBuffer to convert to bytes later
        ByteBuffer bb = ByteBuffer.allocate(16);
        bb.putLong(t1);
        bb.put(userid.getBytes());

        // create signature, using timeStamp and random number as data
        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initSign(privateKey);
        sig.update(bb.array());
        byte[] signature = sig.sign();

        // send data and signature
        dos.writeLong(t1);
        dos.writeInt(signature.length);
        System.out.println("in the client,the length of signature is :"+signature.length);
        dos.write(signature);
        dos.flush();

        boolean answer = dis.readBoolean();

        System.out.println(answer);

server verifySignature code:
 public static boolean verifyLogin(DataInputStream dis, String userid) throws Exception {

    // TO DO

    // receive data and signature

    long t1 = dis.readLong();
    //double q1 = dis.readDouble();
    int length = dis.readInt();
    System.out.println("in the server,the length of signature is:"+length);
    byte[] signature = new byte[length];
    System.out.println("verifying for clientid is:"+userid);
    dis.readFully(signature);
    System.out.println("Server position2");

    // ByteBuffer to convert to bytes later
    ByteBuffer bb = ByteBuffer.allocate(16);
    bb.put(userid.getBytes());
    bb.putLong(t1);

    // should actually retrieve the appropriate key file using the received user name. For simplicity, hardcoded here
    String userPublicKeyFileName = userid + ".pub";
    ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(userPublicKeyFileName));
    PublicKey publicKey = (PublicKey)keyIn.readObject();
    keyIn.close();

    // verify signature
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(publicKey);
    sig.update(bb.array());

    // verify timeSpan
    // server local timeStamp
    long t2 = (new Date()).getTime();
    long timeSpan = t2 - t1;
    boolean timeFresh = false;
    if (timeSpan < 60000)
        timeFresh = true;

    //final check
    /*if (sig.verify(signature)&&timeFresh){
        System.out.println("Client logged in");
        return true;}
    else{
        System.out.println("Client failed to log in");
        return false;}*/
    if (sig.verify(signature)){
        System.out.println("signature is right");
        if(timeFresh){
           System.out.println("timespan is fresh");
        }
        return true;}
    else{
        System.out.println("Client failed to log in");
        return false;}

}

A: yeah, It's a stupid bug,cause I used datainputstream and dataoutputstream, cause client output sequence and server input sequence should be same.
// ByteBuffer to convert to bytes later
ByteBuffer bb = ByteBuffer.allocate(16);
bb.put(userid.getBytes());
bb.putLong(t1);

This bug not so easy to find because I use bb.array(). lol.


text:
Q: How to declare RDF containers in RDF Schema? When writing an RDF schema, I can do the following to declare that a committee consists of a number of persons:
<rdfs:Class rdf:ID="Committee" />
<rdf:Property rdf:ID="members">
  <rdfs:domain rdf:resource="#Committee" />
  <rdfs:range rdf:resource="#Person" />
</rdf:Property>

However, I have read that there is a fine semantic difference between defining individual persons as committee members as I did above, and the fact that only the whole group of given persons forms the committee. Hence, in such cases, one should consider using the RDF containers such as rdf:Bag.
My question is: How to declare such a "bag of Persons" in the RDF schema?
Any help is appreciated.

A: If you want to declare that ONLY these people form the commitee, you should use Collection, not rdf:Bag. The RDF tutorial at w3schools.com gives an example:
https://www.w3.org/TR/rdf-schema/#ch_collectionvocab
In the RDF schema you need to declate a property "hasMember" or "member". Its domain is a commitee, and its range is a member. Then, the RDF file can describe an unlimited number of members for a given commitee. If in the commitee resource you want to specify that these are the ONLY memebrs, you use a collection. If you allow more members, use a rdf:Bag.
Note: This does not mean it's impossible to define a "bag of members" or "collection of members" as the range of a property. You can take a look at existing simple ontologies on the web (there are hundreds of them written in RDFS) and compare how they define a similar concept.


text:
Q: Python How to send POST requests with parameters I Want to make script that send a post request with custom parameters to change the time table for another value And then print the output.
The Website is THIS
I've written the following code, but it gives me not the answer i wanted, It says the value is 14  however i sent a request for 42..
import requests
r = requests.post("http://tikah.iscool.co.il/default.aspx", data={'dnn$ctr6707$TimeTableView$ClassesList': "42"})
print(r.status_code, r.reason)
print(r.text)


text:
Q: How much space is minimum enough for VS 2008 and SQL Server I'm preparing the new partitioning of my laptop, so I would like to know how much space are going to take a full installation of this development environment.
Long time ago has elapsed since my last installation of a full Visual Studio environment, so my guesses are that these days the minimum space needed will be around 15 GB.

A: The answer depends on whether the partition needs to hold data, too. How large will the databases be that you intend to create, and what is the number and size of your Visual Studio projects? What languages do you want to install, what SDKs will you install? Do you need the full MSDN library?
If you plan to do real work, allocate 50GB at least, better 100GB. There is a lot of stuff that accumulates.

A: I run my main server with a small bootable partition, it has XP, VS2008, SQL 2005 plus a few other tools and it comes it at 11G.


text:
Q: input past end of file - vb.net application when opening csv file In my VB.net application, I am opening a .csv file to read its contents:
FileOpen(1, filename, OpenMode.Input)

While NOT EOF(1)
    ...do code here
End While

it works perfectly, but there are some files I am having issues with. It keeps displaying an error saying Input past end of file
I tried adding If NOT EOF(1) inside and outside my while loop to test for the end of the file but its still displaying the same error message


text:
Q: firebase runTransactionBlock I'm reading firebase.google's example seen here https://firebase.google.com/docs/database/ios/save-data#save_data_as_transactions
and I am trying to write my own version. I am having trouble as the firebase example leaves me more confused than i was before i started
All i am trying to do is when a person taps a button is that it ++ (or +=1) to the count
and another button removes it
Can somebody help me figure out how to do this...another user on a previous question posted links to other language answers and i tried to write it in the swift language but I failed miserably

A: Thanks to the comments seen above I was able to get this to work
....runTransactionBlock { (currentData: FIRMutableData) -> FIRTransactionResult in

        var value = currentData.value as? Int

        if value == nil {
            value = 0
        }

        currentData.value = value! + 1
        return FIRTransactionResult.successWithValue(currentData)

    }

A: Seems to work in 2021 Swift 5
gv.dbRef.child("referenceToLikes ie posts/user/likes").runTransactionBlock({ (currentData: MutableData) -> TransactionResult in
        var value = currentData.value as? Int
                if value == nil {
                    value = 0
                }
                currentData.value = value! + 1
        return TransactionResult.success(withValue: currentData)
    }) { error, committed, snapshot in
        if let error = error {
          print(error.localizedDescription)
        }
    }


text:
Q: PHP How to delete post in group? I want to delete post in facebook group with method:
https://graph.facebook.com/{Post-ID}/?method=delete&access_token={Admin token}

And it displayed: (#200) Permissions error

But I can delete comments in post with comment-id
How to fix? Please!!
Thanks.

A: According to this https://developers.facebook.com/docs/graph-api/reference/v3.1/group/feed
,you cant.

Deleting
  This operation is not supported.


text:
Q: How to change the color of a plane geometry in three.js? (always keeps giving me a black outcome) I am adding a plane to the scene like this
   var plane = new THREE.Mesh(new THREE.PlaneBufferGeometry(300, 300), new THREE.MeshPhongMaterial({specular: '#fff',fog: false,color: '#ff9a00',shininess: 10 }));

Then I am changing that plane's color with
plane.material.color = '#ff9a00';

But all I get is a black plane after that color change. Before the color change, the plane is orange-brown color. After the color change it should still be orange-brown but it turn to pitch black no matter what color I try to change it to.

A: You are not specifying the color value correctly.
plane.material.color.setHex( 0xff9a00 );

See http://threejs.org/docs/#Reference/Math/Color
three.js r.73


text:
Q: How to make an AutoCompleteField in Eclipse just like Refactoring Dialog? This question is related to Eclipse plug-in development.
I want to code an SWT Text field (or Combo) just like the "Return type" field in the "Change Method Signature" refactoring dialog page. I would like to have the same auto complete behavior as in this field.
I know I could use AutoCompleteField and TextContentAdapter, but I have no idea how to set the proposals array with all the classes in the project classpath. What about those image decorations to the left of the class name?
I'd appreciate any help.

A: Do you need a ContentProposals example only or to you want to know how to get all the class names in the classPath? With the first thing I can help you. Hope this code helps, if you have questions then just ask.
package com.porsche.dps.core;

import org.apache.log4j.Logger;
import org.eclipse.jface.bindings.keys.KeyStroke;
import org.eclipse.jface.bindings.keys.ParseException;
import org.eclipse.jface.fieldassist.ContentProposal;
import org.eclipse.jface.fieldassist.ContentProposalAdapter;
import org.eclipse.jface.fieldassist.SimpleContentProposalProvider;
import org.eclipse.jface.fieldassist.TextContentAdapter;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class ContentProposalsTest {
   public static void main(String[] args) {
      Display display = new Display();
      Shell shell = new Shell(display);
      shell.setLayout(new GridLayout(1, false));

      Text text = new Text(shell, SWT.BORDER);

      String[] proposals = new String[] {"abc", "bcd", "cde", "abc2", "bcd2", "cde2"};
      String autoActivationCharacters = "";
      SimpleContentProposalProvider simpleContentProposalProvider = new     SimpleContentProposalProvider(proposals);

      for (int i = 0; i < proposals.length; i++) {

         if (proposals[i].length() == 0)
            continue;

         char c = proposals[i].charAt(0);

         if (autoActivationCharacters.indexOf(c) == -1) {
            autoActivationCharacters += c;
         }
      }

      KeyStroke keyStroke = null;
      simpleContentProposalProvider.setFiltering(true);
      try {
         keyStroke = KeyStroke.getInstance("Ctrl+Space");
      } catch (ParseException e) {
         Logger.getLogger("").error("KeyStroke Parse Exception");
      }
      ContentProposalAdapter proposalAdapter = new ContentProposalAdapter(text, new TextContentAdapter(),
     simpleContentProposalProvider, keyStroke, autoActivationCharacters.toCharArray());

          proposalAdapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
      proposalAdapter.setLabelProvider(new ILabelProvider() {

         @Override
         public void removeListener(ILabelProviderListener listener) {}

         @Override
         public boolean isLabelProperty(Object element, String property) {
            return false;
         }

         @Override
         public void dispose() {}

         @Override
         public void addListener(ILabelProviderListener listener) {}

         @Override
         public String getText(Object element) {
            return ((ContentProposal)element).getLabel();
         }

         @Override
         public Image getImage(Object element) {
            return <insert image>;
         }
      });
      shell.open();
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      display.dispose();
   }
}


text:
Q: Zip/Postal Code validation not working properly In billing.phtml file Zip/Postal Code validation is not working properly.
1) When I field is empty it's asking it's required fine.
2) But letter's also allowing this field. I don't want to allow letters only Numeric values will allow.
my code is

                        *<?php echo $this->__('Zip/Postal Code') ?>

                            <input type="text" title="<?php echo $this->__('Zip/Postal Code') ?>" name="billing[postcode]" id="billing:postcode" value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>" class="input-text validate-zip-international <?php echo $this->helper('customer/address')->getAttributeValidationClass('postcode') ?>" />

and
I set to true in javascript also
var billingForm = new VarienForm('co-billing-form',true);

May I know Where I went wrong? or how to do this?
Thanks.

A: You should be able to change the class from "validate-zip-international" to "validate-number" to add Magento's frontend JS validation for numbers, or "validate-digits".
Source: /js/prototype/validation.js for a list of all validation classes (addAllThese method)
['validate-number', 'Please enter a valid number in this field.', function(v) {
    return Validation.get('IsEmpty').test(v) || (!isNaN(parseNumber(v)) && !/^\s+$/.test(parseNumber(v)));
}],
['validate-digits', 'Please use numbers only in this field. Please avoid spaces or other characters such as dots or commas.', function(v) {
     return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
}]