text:
Q: How to install 32-bit libraries of android studio properly to a 64-bit machine? I have been trying to install Android Studio properly to my  Ubuntu 16.04 64-bit machine, but I can not solve this very problem. Android studio requires us to install some 32 bit files to 64 bit computers. But when I try to install, I cannot solve the problem.
I have given so many inputs to the terminal and couldn't trace them all. However, I'm sure that I wrote lots of commands on installing lib32stdc++6 and other packages that has been suggested on the internet but every time I got the error message:

[ E: Unable to correct problems, you have held broken packages. The following packages have unmet dependencies: X depends Y but it won't be installed ]

Edit: input & output example:
***@***:~$ sudo apt-get install lib32stdc++6
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 lib32stdc++6 : Depends: gcc-5-base (= 5.3.1-13ubuntu6) but 5.3.1-14ubuntu2 is to be installed
                Depends: lib32gcc1 (>= 1:4.2) but it is not going to be installed
                Depends: libc6-i386 (>= 2.18) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

A: (Posted on behalf of the OP):
I solved the problem. I'll write a brief info about the solution process in case anyone else faces with a similar situation. First of all I realised that this problem was all about the incompatibility of 32 bit libraries with 16.04. So that, I changed the "download from" section from the System Settings - Software&Updates.
Select Netherlands instead of your country's repo, that'll be convenient (mine was Turkey before). Then simply update your repos by typing sudo apt-get update to terminal. Lastly, install the required libraries for 16.04 by typing sudo apt-get install lib32stdc++6. After all, install Android Studio from the very beginning. I did all those and now Android Studio runs properly.


text:
Q: Kivy buttons not pressable I dynamically created buttons based on how many sound files there are in a folder but I'm having an issue where I cannot press any of the buttons. I tried looking up tutorial or similar question but it seems as what I have should be correct, yet when I run it I get a window with buttons, but the buttons do nothing when pressed.
import os, glob

from os.path import isfile, join
from os import listdir
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.config import Config
from kivy.app import App

Config.set('graphics', 'borderless', False)
Config.set('graphics', 'width', '500')
Config.set('graphics', 'height', '300')

class Soundboard(GridLayout):
def soundSearch(self):
    os.chdir("./sound")
    self.sounds = []
    for Wav in glob.glob("*.wav"):
        self.sounds.append(Wav)
    for Flac in glob.glob("*.flac"):
        self.sounds.append(Flac)
    for mp3 in glob.glob("*.mp3"):
        self.sounds.append(mp3)

def __init__(self,**kwargs):
    super(Soundboard, self).__init__(**kwargs)
    self.soundSearch()
    self.cols = 3
    for sound in self.sounds:
        self.button = Button(text=os.path.splitext(sound)[0])
        self.button.bind(on_press=lambda x:self.clk())
        self.add_widget(self.button)
    self.row_force_default = True
    self.row_default_height = 40
    self.padding = [50, 10]
    self.spacing = 5

def clk(self, *args):
    print('The button is pushed')
class MyApp(App):
    def build(self):
        return Soundboard()

if __name__ == '__main__':
    MyApp().run()

A: In the code you provided there is a problem with indentation. Other than that, the code works fine for me:
import glob
import os

from kivy.app import App
from kivy.config import Config
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout

Config.set('graphics', 'borderless', False)
Config.set('graphics', 'width', '500')
Config.set('graphics', 'height', '300')

class Soundboard(GridLayout):
    def soundSearch(self):
        self.sounds = []
        os.chdir("./sound")
        for Wav in glob.glob("*.wav"):
            self.sounds.append(Wav)
        for Flac in glob.glob("*.flac"):
            self.sounds.append(Flac)
        for mp3 in glob.glob("*.mp3"):
            self.sounds.append(mp3)

    def __init__(self,**kwargs):
        super(Soundboard, self).__init__(**kwargs)
        self.soundSearch()
        self.cols = 3
        for sound in self.sounds:
            self.button = Button(text=os.path.splitext(sound)[0])
            self.button.bind(on_press=lambda x: self.clk())
            self.add_widget(self.button)
        self.row_force_default = True
        self.row_default_height = 40
        self.padding = [50, 10]
        self.spacing = 5

    def clk(self, *args):
        print('The button is pushed')

class MyApp(App):
    def build(self):
        return Soundboard()

if __name__ == '__main__':
    MyApp().run()

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make the predicate spent(Passengers, Year, Sum) in prolog? I need to write a predicate "spent" that would find the total costs for tickets of passengers from
of the "Passengers" list in the given year "Year".
I have these facts:
trip(01, Tokio, Toronto, 1500).        /trip   (Id, From, To, Price)/
trip(02, California, London, 700).

ticket(01, Sara, 2021-12-26).          /ticket (Id, Passenger, Date)/
ticket(02, Jane, 2021-05-21).

I wrote this code, but it is not enough to complete the task, please help.
sum_cash(Price) :- spent(sum(A), trip(_, _, _, A), Price).


text:
Q: Enum does not hold its keys, only a ref to keys instead According to documentation at https://code.kx.com/q/ref/enumerate/

Enumerate
Syntax: x$y, $[x;y]
Where

*

*x and y are lists

I suppose a correct way to create enum would be through giving lists to the $:
q)e:`a`b`c$`b`a`c`c`a`b
'length
  [0]  e:`a`b`c$`b`a`c`c`a`b
               ^

but obvious it is not. After reading more examples I tried:
q)mykeys:`a`b`c
q)show e:`mykeys$`b`a`c`c`a`b
`mykeys$`b`a`c`c`a`b

And it works. But then I've seen that my enum e contains its values and only a reference to its keys mykeys:
q)(key;value)@\:e
`mykeys
`b`a`c`c`a`b
q)`:e.raw set e
`:e.raw

So saving e to a file saves no keys! In a fresh session:
q)e: get `:e.raw
q)e
`mykeys!1 0 2 2 0 1
q)mykeys
'mykeys
  [0]  mykeys
       ^
q)mykeys:`a`b`c
q)e
`mykeys$`b`a`c`c`a`b

I know one could save keys with a neat enum extend functionality:
q)`:mykeys?`b`a`c`c`a`b;
q)get `:mykeys
`b`a`c

But why do enums act like this? - it seems like they hardly splitted apart into keys and values. May be in a big picture with tables, indexes, table splaying it makes more sense.
And how enumeration could exists just after loading from a file? Is it a semi-normal state when its keys domain does not exist yet?:
q)e: get `:e.raw
q)e
`mykeys!1 0 2 2 0 1

A: This behaviour is by design because, like you presumed, there is a bigger and more generalised picture.
Enums are primarily used for:

*

*the sym file, in which the syms (keys) are always stored permanently in the database with the help of enum-extend ?

*foreign-keys, as per https://code.kx.com/q4m3/8_Tables/#852-example-of-simple-foreign-key
In the latter case, it would not make sense to also store the keys with the enumeration because the keys are contents of a table. It is presumed that if you will persist the enum then you will also persist the table which contains the keys.
A similar concept is column-linking - https://code.kx.com/q/kb/linking-columns/
Finally, the reason
`a`b`c$`b`a`c`c`a`b

didn't work is because the list you're enumerating against must be passed by name, not passed by value. So it has to be
`mykeys$`b`a`c`c`a`b


text:
Q: Ajust height of one or more  in a cell of table In this example, is possible to autofit ORANGE to set the largest row height? And with two or more   will be possible to split the cell to adjust the heights?
(Now use: display: table, table-row, table-cell, but also could use a classic table)

http://jsfiddle.net/EjqL8/

Header

Header

Header

Header

Row 1

Row 1

Row 1

Row 1

            RED
            YELLOW
            GREEN
            ORANGE
            GREY

Row 2

Row 2

            ORANGE

            RED
            YELLOW
            GREEN
            ORANGE
            GREY

Row 2

Row 2

            GREEN
            ORANGE

A: http://jsfiddle.net/EjqL8/2/
$(".row .cell:last-child").has("span").each(function(){
    var counter = 0;
    $(this).find("span").each(function(){
        counter += 1;
    });

    var height = 100 / counter;

    $(this).find("span").css('height', height+'%');
});

But you need to set heights for your cells atleast. This way jQuery will calculate the height for your spans. We can also calculate the height of your calls and set them to make this work.

A: Try this:
http://jsfiddle.net/EjqL8/4/
$(document).ready(function(){
    $(".row .cell:last-child").has("span").each(function(){
        var counter = $(this).find("span").length;
        var height = $(this).height() / counter;
        $(this).find("span").css('height', height+'px');
    });
});

A: Using jQuery you can do it. You just have to use :
$('.toExpand').each(function(){
    var parentHeight = $(this).parent().height();
    $(this).height(parentHeight);
});

to expand it to the full height of parent.
Then divide the parentHeight variable to adjust it.
Here is the code:
http://jsfiddle.net/QtBlueWaffle/EjqL8/5/

A: I've created a FIDDLE by using table tag.
You could just use the rowspan=n or colspan=n (n=number of columns) to merge the columns.

A: Well I don't want to seem rude, but your majorly re-inventing the wheel here.
Your going to want to try to use a div height percentage.  However, this won't work until you define a height of the parent.  You could just end up scaling back to one starting height, but it just seems like a terrible way to go.


text:
Q: How to add blank element to an array based on value in javascript I have an array and a variable,the variable will show the integer value,based on that value I need to add blank element to the array.For example value is 4 so I should get result ['','','','','chart1','chart2','chartr3']. Here is the code below,here I hardcoded for example
HTML

How to add blank element to an array based on value in javascript

SCRIPT
var count = 4;
var array = ['chart1','chart2','chartr3'];
console.log(array);
var finalarray[] ;
console.log(finalarray);//['','','','','chart1','chart2','chartr3'];

A: You can try using unshift
var array = ['chart1','chart2','chartr3'];
var count = 4;

for (var i = 1; i++; i <= count) {
   array.unshift(' ');
}

Edit. To fire this in each click (jquery)
var start_array = ['chart1','chart2','chartr3'];

$('.element-clicked').on('click', function(e) {
    start_array.unshift(' ');
});

A: How about trying a loop?
var count = 4;
var array = ["chart1", "chart2", "chart3"];

var finalArray = array;

for (var i = 0; i < count; i++) {
    finalArray.unshift("");
}

console.log(finalArray);

Note: The unshift() method does not work properly in Internet Explorer 8 and earlier: the values will be inserted, but the return value will be undefined.
If you want this array to increment when clicking a button you could try something like this:

var array = ["after", "after2", "after3"];

// This will set the span 'originalArray' to display 'array'
document.getElementById("originalArray").innerHTML = array;

// prependValueToArray:
// - This function will add a value e.g: "" to your specified array 'x' number of times.
function prependValueToArray(array, number, value) {
    var resultArray = array;

    for (var i = 0; i < number; i++) {
        resultArray.unshift(value);
    }

    // This will change the value inside the 'resultArray' span to the new array
    document.getElementById("resultArray").innerHTML = resultArray;
}

    Original:

  [

  ]

<button onclick="prependValueToArray(array, 1, 'before');">Click me!</button>

    Result:

  [

  ]

A: if you want to use a function. and var finalarray[] ; is wrong.

var array = ["chart1","chart2","chartr3"];
var count = 4;
function myFunction() {

 var finalarray=[] ;

  for(var i=0;i< 4;i++){
   finalarray.push("") ;

}
 finalarray.push("chart1") ;
  finalarray.push("chart2") ;
   finalarray.push("chartr3") ;
console.log(finalarray);
}
<button onclick="myFunction()">Click me</button>

A: var count = 4;
for (var i = 0; i < count; i++) {
finalarray[i] = '';
}


text:
Q: A story about aliens mistaking humans as parasites Aliens discover Earth but are mistaken who the real inhabitants are: i.e. the aliens think that humans are parasites or something and that the real Earthlings are cars or something else.
Is this an old joke or a real story?

A: There was a Donald Duck comic where Scrooge sold the "1-2-3" product, an evolving car, over the whole world:

 Scrooge ended up unknowingly saving the world as aliens approached and identified the 1-2-3s as the real inhabitants of the Earth. They attacked the 1-2-3s with their shrink rays and left without harming any humans.

A: UPDATE: Found it!
I believe the work you are referring to is the animated short What on Earth! (1966). You can watch it here.

Old answer:
It sounds like you're describing a scene out of the beginning of the movie "The Hitchhiker's Guide to the Galaxy" (2005):

FORD: Remember when we met? That car was racing toward me, I was trying to greet it, you pushed me out of the way?
QUICK CUT TO A STREET - MID-DAY: Ford stands in the middle of the road, extending a hand
  to a fast approaching car. Arthur drops his shopping, dives at him and tackles him out of the way as the car zooms past.
FORD: Didn't you find it a little strange that I was trying to shake hands with a car?
ARTHUR: I assumed you were drunk.
FORD: (shaking his head) I thought cars were the dominant life
  form. I was trying to introduce myself.

(PDF of the script can be found here)
This is a specific instance of a general trope: "Mistook The Dominant Lifeform". As mentioned in the examples at the above link, the more specific cars-as-dominant-lifeform trope has cropped up in Transformer comics and Carl Sagan's book Pale Blue Dot: A Vision of the Human Future in Space (1994), but there are probably a number of other works it has appeared in as well.

A: There was a book of physics jokes that I saw in the 1980s, though it was published much earlier that contained this story as one of the jokes.

A: Probably not a story, but in Stapledon's Last and First Men, the Martians (sentient microorganisms) waged war on the earth in order to liberate diamonds from the humans, whom they first did not perceive as the source of the radio broadcasts.

A: The Day The Earth Stood Still (movie) loosely matches this description. The earth was going to be destroyed because the parasite humans were destroying it.


text:
Q: Login in Ubuntu 22.04.1 goes back to login challenge When I try to login in my Ubuntu 22.04.1 I succeed in login but The next screen is the login screen again. I switched on ubuntu on Xorg and (luckily) everything works. Once I tried to change the password and magically It worked for one day.... It's not a big deal, but I would increase my knowledge about  Ubuntu
Thank you in advance

A: Probably a graphic card drivers compatibility with Wayland.
Check your drivers:
glxinfo | grep "Vendor"
glxinfo | grep "direct rendering"

I did had that issue with pre-installed amdgpu once.
Also i suggest using ppa:kisak/kisak-mesa For latest mesa updates


text:
Q: Django cart with user defined attributes Good day.
I'm building an application for ordering prints and struggles at a part where
the user, apart from selecting from predefined values, can enter her own data for printing.
Consider the following:
class PrintItem(models.Model):
    """ Something printable. Poster, t-shirt, mug, etc """
    name = models.CharField(max_length=20)

class AttributeType(models.Model):
    """ Size,colour, etc """
    name = models.CharField(max_length=20)

class Attribute(models.Model):
    """ Size: A4, A5 | Colour: Violet, Black """
    name = models.CharField(max_length=20)
    type = models.ForeignKey(AttributeType)

# And a join model
class PrintAttribute(models.Model):
    print_item = models.ForeignKey(PrintItem)
    attributes = models.ManyToManyField(Attribute)

# The user adds these to a cart
class Cart(models.Model):
    user = models.ForeignKey(User)

class CartItem(models.Model):
    cart = models.ForeignKey(Cart)
    print_item = models.ForeignKey(PrintItem)

This works all good. The user can select from the predefined attributes, but how and where would you suggest I would implement the user input functionality?
User finds an item to print, chooses from the predefined Attributes (print size, the ink colour) and can enter her own message/slogan to print on the item.
Grateful for any suggestions.

A: If user's own slogan/message gets entered only upon adding a print item to the cart, then the slogan/message should be a field of CartItem.


text:
Q: Problemas de estilos con paginate laravel Hola a todos les pido ayuda ya que estoy haciendo una paginacion en laravel y tengo el problema que a la hora de mostrarla en mi pagina se ve de una forma rara, esta es la forma en la que hago mi paginacion desde el home.blade.php:
public function index()
{
    $data = Books::orderBy('id', 'desc')->paginate(3);
    return view('home', [
        'data' => $data
    ]);
}

Y esta es la forma en la que incluyo la paginacion:
<div class="d-flex justify-content-center">
   {{ $data->links() }}
</div>

Y de esta forma es en la que me lo muestra

Alguien me podría decir como puedo hacer que se vea "normal" o al menos como se veia en la version 5 de laravel. Desde ya gracias a todos :).

A: En la versión 8, laravel trae como predeterminados los estilos de Tailwind CSS para la paginación, pero también incluye vistas de paginación creadas con Bootstrap CSS.
Para usar estas vistas en lugar de las de Tailwind, puedes llamar al método useBootstrap del paginador dentro del método boot de tu clase App\Providers\AppServiceProvider:
use Illuminate\Pagination\Paginator;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Paginator::useBootstrap();
}

Referencia: Pagination Usando Bootstrap


text:
Q: check if user requests his own page in asp.net mvc/angularjs I'm using asp.net mvc with angularjs for my project. How to return some extra data(smth like isOwner variable) alongside with user object?
var isOwner = false;
if(user.Alias == User.Identity.Name)
isOwner = true;)

On the view I want to show edit button only if user requests his own page
Here's api controller:
public User GetUser(String id)
{
    xRM.DAO.Model.User user = null;
    using (var db = new xRMContext())
    {
        user = db.Users
            .Include("Team").Include("Unit").Include("Location")
            .FirstOrDefault(u => u.Alias.ToLower() == id.ToLower());
    }

    if (user == null)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }

    return user;
}

and angularjs controller:
.controller('UserCtrl', ['$scope', '$location', '$routeParams', 'User', function ($scope, $location, $routeParams, User) {
    $scope.user = User.get({ id: $routeParams.id })
}])

A: You just need to return a viewmodel instead of the User model. The viewmodel should contain any properties that are needed by the view and not just expose all properties of the User object. For example:
public class UserViewModel
{
    public string UserName {get; set;}
    public string Email {get; set;}
    // more properties from User
    public bool IsOwner {get; set;}
}

You obviously need to change the GetUser action method so it returns UserViewModel, add the logic that figures out if a user is owner and map the properties from a User object to the viewmodel. If you find yourself mapping properties often, which can become tedious, I strongly recommend using Automapper.


text:
Q: Linear differential equations of the $n$th order $$ L(x)=x^{(n)}+a_1(t)x^{(n-1)}+\cdots +a_{n-1}(t)x'+a_n(t)x;\qquad a_1(t),a_2(t),\ldots\in C$$
$$U_j(\varphi)= \sum_{k=0}^{n-1}(M_{jk} \varphi^{k}(\alpha)-N_{jk} \varphi^{k}(\beta))= \gamma_j\quad \text{or} \quad U(\varphi)= \gamma$$ $$L(x)=b(t) \\ U(x)=0 \tag{1}$$
$(1)$ has to be solved. This is how the answer starts off, if anyone can pinpoint the detail, step that I am not seeing feel free to notify me.
Let $\varphi_{1}(t), \varphi_2(t),\ldots,\varphi_n(t)$ be the fundamental set of answers, the Vronski matrix : $W(t)=W(\varphi_1(t),\varphi_2(t),\ldots,\varphi_n(t))$ and the algebraic complement of the element $._{ni},\ \ $ $W_{ni}(t)$. We have the given formula: $$\varphi(t)= \sum_{i=1}^{n} \gamma_i \varphi_i(t)+ \sum_{i=1}^{n}\varphi_i(t) \int_{\alpha}^{t}\frac{W_{ni}(s)b(s)}{W(s)}ds $$ from here we have: $$\varphi(t)= \sum_{i=1}^{n} \gamma_i \varphi_i(t)+ \int_{\alpha}^{t}K^{*}(t,s)b(s)ds \tag{${*}{*}{*}{*}$}$$
where:
$$K^{*}(t,s)=\frac{1}{W(s)} \begin{vmatrix}
\varphi_1(s) & \varphi_2(s)& \cdots& \varphi_n(s)\\
\varphi_1'(s)& \varphi_2'(s)& \cdots & \varphi'_n(s)\\ \vdots& \vdots & \ddots & \vdots\\
\varphi^{(n-2)}_1(s)& \varphi^{(n-2)}_2(s)& \cdots & \varphi^{(n-2)}_n(s)\\
\varphi_1(s) & \varphi_2(s)& \cdots & \varphi_n(s)
\end{vmatrix}$$
Who understands: $({*}{*}{*}{*})$ ? Made an important update.

A: I think I have got an idea how to decode the message, or at least its major part.

*

*I start with a system of linear differential equations
$$
\dot z(t)=A(t)z(t)+f(t),\quad z(0)=z_0\in\mathbb{R}^n.\tag1
$$
If $\Phi(t)$ denotes the fundamental matrix of the corresponding homogeneous system, i.e.
$$
\dot\Phi(t)=A(t)\Phi(t),\qquad\Phi(0)=I,\tag2
$$
then the solution to (1) is given by the formula (take derivative to see it)
$$
z(t)=\Phi(t)z_0+\Phi(t)\int_0^t\Phi(s)^{-1}f(s)\,ds.\tag3
$$

*The linear differential equation of order $n$
$$
x^{(n)}(t)+a_1(t)x^{(n-1)}(t)+\ldots+a_n(t)x(t)=b(t)
$$
can be in the standard way converted to the form (1) if we denote
$$
z(t)=\left[\matrix{x(t)\\ x'(t)\\ \vdots\\x^{(n-2)}(t)\\x^{(n-1)}(t)}\right]\quad\Rightarrow
\quad
\dot z=\left[\matrix{0 & 1 & 0 &  \ldots & 0\\
0 & 0 & 1 &  \ldots & 0\\
\vdots & \vdots & \vdots & \ddots & \vdots \\
0 & 0 & 0  & \ldots & 1\\
-a_n & -a_{n-1} & -a_{n-2} & \ldots & -a_1}\right]z+
\left[\matrix{0\\ 0\\ \vdots\\ 0 \\b}\right].
$$
The fundamental matrix for the homogeneous part now will be the (scaled) Wronski matrix
$$
\Phi(t)=W(\phi_1(t),\ldots,\phi_n(t))W(\phi_1(0),\ldots,\phi_n(0))^{-1}=W(t)W(0)^{-1}.
$$
Now to get the general solution I am going to use (3), but I will a) move the initial time from zero to $\alpha$, and b) take only the first coordinate of $z$, which is $x=[1\ 0\ \ldots\ 0]z$, since the other coordinates are not interesting - just the derivatives of $x$.
$$
x(t)=[1\ 0\ \ldots\ 0]W(t)z_\alpha+[1\ 0\ \ldots\ 0]W(t)\int_\alpha^tW(s)^{-1}\left[\matrix{0\\ \vdots\\ 0 \\b(s)}\right]\,ds.
$$

*The rest is pretty technical. With $z_\alpha=\gamma$ (not quite get the connections to $U(\phi)=\gamma$ here) the first term becomes
$$
\sum_{i=1}^n\phi_i(t)\gamma_i
$$
and in the second term an explicit calculation of $W^{-1}=\frac{\text{adj}\,W}{\det W}$ is done. Actually. we need only the last column of the inverse since others are multiplied with zeros anyway. This is how we obtain the algebraic complements $W_{ni}$ and (NB!) $\det W$ in the denominator.

*Finally, the function $K^*(t,s)$. We need only the last element of
$$
[\phi_1(t)\ \phi_2(t)\ \ldots\ \phi_n(t)]W(s)^{-1}=[*\ *\ \ldots\ K^*(t,s)]
$$
since the others are multiplied by zeros. Post-multiplying by $W(s)$ and taking transpose yields
$$
W(s)^T\left[\matrix{*\\*\\\vdots\\ K^*(t,s)}\right]=
\left[\matrix{\phi_1(t)\\\phi_2(t)\\\vdots\\ \phi_n(t)}\right].
$$
Now Cramer's rule gives
$$
K^*(t,s)=\frac{1}{\det(W(s))}\left|\matrix{\phi_1(s) & \phi_2(s) & \ldots &\phi_n(s)\\\phi_1'(s) & \phi_2'(s) & \ldots &\phi_n'(s)\\
\vdots & \vdots & \ddots & \vdots\\
\phi_1^{(n-2)}(s) & \phi_2^{(n-2)}(s) & \ldots &\phi_n^{(n-2)}(s)\\
\phi_1(t) & \phi_2(t) & \ldots &\phi_n(t)}\right|.
$$

A: I will post a different solution to this question, a solution based on the Green's function method. Now, again, the question reads as follows . Given the fundamental set of solutions $\phi_j(t)$ to the homogeneous equation prove that the particular solution to the in-homogeneous equation can be constructed by integrating a kernel (or a Green's function) with the right hand side.
In other words if:
\begin{equation}
(1) \quad \hat{L}(t) \phi_j(t) = 0
\end{equation}
for $j=1,\cdots,n$ then the particular solution to the equation below:
\begin{equation}
(2) \quad \hat{L}(t) y(t) = b(t)
\end{equation}
is given as follows:
\begin{equation}
y(t) = \int\limits_0^t \frac{1}{\det(W(\xi))} \left|
\begin{array}{rrrr}
\phi_1(\xi) & \phi_2(\xi) & \cdots & \phi_n(\xi)\\
\phi_1^{'}(\xi) & \phi_2^{'}(\xi) & \cdots & \phi_n^{'}(\xi)\\
\vdots\\
\phi_1^{(n-2)}(\xi) & \phi_2^{(n-2)}(\xi) & \cdots & \phi_n^{(n-2)}(\xi)\\
\phi_1(t) & \phi_2(t) & \cdots & \phi_n(t)\\
\end{array}
 \right| b(\xi) d\xi
\end{equation}
Proof: Clearly the solution to equation (2) has the form:
\begin{equation}
(3) \quad y(t) = \int\limits_0^t G(t,\xi) b(\xi) d\xi
\end{equation}
where
\begin{equation}
(4) \quad \hat{L}(t) G(t,\xi) = \delta(t-\xi)
\end{equation}
This follows from applying the operator $\hat{L}(t)$ to both sides of equation (3) and using the linearity of the operator.
Now, fix $\xi$ and treat $t$ as a variable. Clearly equation (4) is very similar to equation (1) . In fact the two equations are exactly the same except at $t=\xi$. It is therefore reasonable to assume that the sought for Green's function $G(t,\xi)$ can be written as some sort of linear combination of the fundamental solutions . In other words we assume that:
\begin{eqnarray}
(5) \quad G(t,\xi)= \left\{
\begin{array}{rr}
\sum\limits_{j=1}^n C^{+}_j \cdot \phi_j(t) & \mbox{if $t\ge \xi$}\\
\sum\limits_{j=1}^n C^{-}_j \cdot \phi_j(t) & \mbox{if $t< \xi$}\\
\end{array}
\right.
\end{eqnarray}
We determine the unknown constants $C^{\pm}$ using smoothness conditions. From the definition of the Dirac delta function it follows that, at $t=\xi$, the function itself along with all its derivatives up to order $(n-2)$ must be continuous whereas the $(n-1)$st derivative must have a jump of magnitude one. Therefore we write:
\begin{equation}
\left(
\begin{array}{rrrr}
\phi_1(\xi) & \phi_2(\xi) & \cdots & \phi_n(\xi)\\
\phi_1^{'}(\xi) & \phi_2^{'}(\xi) & \cdots & \phi_n^{'}(\xi)\\
\vdots\\
\phi_1^{(n-1)}(\xi) & \phi_2^{(n-1)}(\xi) & \cdots & \phi_n^{(n-1)}(\xi)\\
\phi_1^{(n-0)}(\xi) & \phi_2^{(n-0)}(\xi) & \cdots & \phi_n^{(n-0)}(\xi)
\end{array}
\right)
\left(
\begin{array}{r}
C_1^{+}-C_1^{-}\\
C_2^{+}-C_2^{-}\\
\vdots\\
C_{n-1}^{+}-C_{n-1}^{-}\\
C_{n-0}^{+}-C_{n-0}^{-}
\end{array}
\right)=
\left(
\begin{array}{r}
0\\
0\\
\vdots\\
0\\
1
\end{array}
\right)
\end{equation}
We solve the above system of equations using the Kramer rule and we have:
\begin{equation}
\left(
\begin{array}{r}
C_1^{+}-C_1^{-}\\
C_2^{+}-C_2^{-}\\
\vdots\\
C_{n-1}^{+}-C_{n-1}^{-}\\
C_{n-0}^{+}-C_{n-0}^{-}
\end{array}
\right)=
\left(
\begin{array}{r}
(W^{-1})_{1,n}\\
(W^{-1})_{2,n}\\
\vdots\\
(W^{-1})_{n-1,n}\\
(W^{-1})_{n,n}
\end{array}
\right)=
\frac{1}{\det(W)}
\left(
\begin{array}{r}
(M)_{n,1}\\
(M)_{n,2}\\
\vdots\\
(M)_{n,n-1}\\
(M)_{n,n}
\end{array}
\right)
\end{equation}
Here $W$ is the matrix of the fundamental system and $M_{i,j}$ is the algebraic complement of $W_{i,j}$.
Now, since we are only interested in constructing a particular solution to the in-homogeneous system we can assume that  $C^{-}_j=0$ for $j=1,\cdots,n$. Therefore from (5) the Greens function reads:
\begin{equation}
G(t,\xi)= \frac{1}{\det(W)} \cdot \sum\limits_{j=1}^n (-1)^{n+j} \cdot M_{n,j} \cdot \phi_j(t)=
\frac{1}{\det(W)}
\left|
\begin{array}{rrrr}
\phi_1(\xi) & \phi_2(\xi) & \cdots & \phi_n(\xi)\\
\phi_1^{'}(\xi) & \phi_2^{'}(\xi) & \cdots & \phi_n^{'}(\xi)\\
\vdots\\
\phi_1^{(n-2)}(\xi) & \phi_2^{(n-2)}(\xi) & \cdots & \phi_n^{(n-2)}(\xi)\\
\phi_1(t) & \phi_2(t) & \cdots & \phi_n(t)\\
\end{array}
 \right|
\end{equation}
as expected.


text:
Q: How can Url.Action already know the routevalues without me setting them? I'm doing a jquery post to an MVC action. The action returns a json result with (for example) Id = 123. Code is still in early stage, but I was very surprised to find out that Url.Action("action", "controller") is building a url complete with the id I returned from Json. Is this magic? I couldn't find documentation that says it does that.
// how I assumed it would need to be accomplished
// redirects to "Controler/Action/123123" where data = { id = 123 }
$.post(saveUrl, json, function (data) {
    var detailsUrl = "@Url.Action("Action", "Control")" + data.id;
    window.location = detailsUrl;
});

// rewritten without adding id to the route, not sure how this works...
// redirects to "Controler/Action/123" where data = { id = 123 }
$.post(saveUrl, json, function (data) {
    var detailsUrl = "@Url.Action("Action", "Control")";
    window.location = detailsUrl;
});

Just for reference, here is the action:
[HttpPost]
public ActionResult Save(Model model)
{
    return new JsonResult { Data = new { id = 123 }};
}

So I guess my question is, is this by design? How does it know what to use?

As pointed out in the answer, Url.Action has access to existing routevalues and will attempt to reuse them. To get around this I have used the slightly hacky solution below:
var detailsUrl = "@Url.Action("Action", "Control", new { id = ""})" + "/" + data.id;

This clears out the route values so that I can attach new ones in on the client side. Unfortunately, passing null or new {} as RouteValues to Url.Action does not overcome this. A nicer approach may be to create another Action helper that guarantees no routevalues will be attached. Alternativly, there is also Url.Content, but you will lose the Action/Controller wiring in the IDE doing this.

A: The UrlHelper (which is the type for Url) has access to the route data that was used to access the current action. It will try and use these values to fill in the necessary route values for you, unless you otherwise specify them.

A:
is this by design?

This magic happens because of Routing infrastructure. Some people thing that the MVC routing is only about handling incoming requests but it is also about generating outgoing URLs.
The html helpers like ActionLink and the UrlHelper these all integrated with the routing module and when you try to create an outgoing URL they check the routing schema that you defined in Global.asax.cs and create the URLs accordingly.
When the schema that you defined in Global.asax.cs changes the generated URLs changes accordingly and so when you create links in your application, rely on this helpers instead of directly hardcoding them in controller or views.


text:
Q: Change length of operation depending on a value Context
I am trying to create a program that gets the product of all n pairs in a number reading from left to right
For example, in the number 2345678:

*

*The product of all 2 pairs would be 2*3 = 6, 3*4=12, 4*5=20, 5*6=30 etc...

*The product of all 3 pairs would be 2*3*4=24,3*4*5=60, 4*5*6=120 etc...

I have completed most of the solution to the problem, but I cannot create an operation that can adapt for any value of n
Code
num = 2345678
num = str(num)

n = 2
start_pos = 0

for i in range(start_pos,len(num)):
    try:
        x += 1
        t = int(num[i]) * int(num[i+1]) # hardcoded for n = 2
        print(t)
        start_pos += 1
    except IndexError:
        break

Operation for different n values
n = 2: t = int(num[i]) * int(num[i+1])
n = 3: t = int(num[i]) * int(num[i+1]) * int(num[i+2])
n = 4: t = int(num[i]) * int(num[i+1]) * int(num[i+2]) * int(num[i+3])
n = 5: t = int(num[i]) * int(num[i+1]) * int(num[i+2]) * int(num[i+3]) * int(num[i+4])
How could I create an operation that can adapt for any value of n?

A: If you want an iterative solution without using any pythonic operator, you can simply add an inner for to iterate from i to i+n, and then accumulate the product of numbers in a variable t. Like this:
num = 2345678
num = str(num)

n = 3
start_pos = 0
x = 0
for i in range(start_pos,len(num)):
    try:

        t = 1
        for j in range(i, i+n):
            t = t * int(num[j])

        print(t)

    except IndexError:
        break

Output:
24
60
120
210
336

A: Sounds like a typical problem for recursion:
def recurse(int_list, times):
    if times == 0:
        return 1
    else:
        return int(int_list[0]) * recurse(int_list[1:], times - 1)

num = 2345678
num_string = str(num)
n = 5
recurse(num_string, n)

A: You can do it similarly to what you tried, using loops:
def products(num, n):
    num = str(num)
    digits = [int(digit) for digit in num]
    out = []
    for i in range(0, len(num)-n+1):
        product = 1
        for digit in digits[i:i+n]:
            product *= digit
        out.append(product)
    return out

print(products(num, 3))
# [24, 60, 120, 210, 336]

Or, using more advanced features:
import operator
from functools import reduce

def products2(num, n):
    num = str(num)
    digits = list(map(int, num))
    out = [reduce(operator.mul, digits[i:i+n]) for i in range(0, len(num)-n+1)]
    return out

print(products2(num, 3))
# [24, 60, 120, 210, 336]

A: The function functools.reduce is designed to operate on successive pairs from a list:
from functools import reduce
number = 2345678
numbers = [int(i) for i in str(number)]
product = reduce((lambda x,y : x*y), numbers)

A: This can be done using recursion:
num = 23456789
num = str(num)

n = 2
start_pos = 0

def nvalues(num, n):
    if n == 0:
        return 1
    else:
        return int(num[i]) * nvalues(num[1:], n-1)

for i in range(start_pos,len(num)):
    try:
        val = nvalues(num, n)
        print val

    except IndexError:
        break

A: You can use the following function:
from itertools import starmap
from operator import mul
from functools import reduce

def func(number, n):
    nums = [int(i) for i in str(number)]
    z = zip(*[nums[i:] for i in range(n)])
    r = starmap(lambda *x: reduce(mul, x), z)
    return list(r)

print(func(2345678, 2))
# [6, 12, 20, 30, 42, 56]

print(func(2345678, 3))
# [24, 60, 120, 210, 336]


text:
Q: What is the correct way of inserting \u using sed? I'm trying to find a string that contains \u and adding something to it.
For example,
$ echo \user | sed 's/\us/\\usX/' -

correctly produces
\usXer

However, if I have the contents in a file and input it to the following code
$ sed -i 's/\us/\\usX/' test

I get
\\usXer

Then, one might think that the problem is the escaped backslash, and it is not needed. But if one removes it, that only triggers the \u (uppercase) substitution of the s command of sed.
Thus, what is the correct way of inserting a \u sequence using sed?

A: First of all, sed 's/\us/…/' doesn't search for \us;
it searches for us.
To search for \us, you need to use sed 's/\\us/…/'.
If you're searching for a string with special characters in it,
and then adding something to it,
a useful technique is to use the & character
to refer to the string that you searched for.  So, for example,
$ sed -i 's/\\us/&X/' test

In general, & (sometimes called the "Find What") represents that portion of the pattern space that matched your search string.
This is more useful when the search string is a non-simple regular expression; e.g.,
$ echo You say goodbye and I say hello. | sed 's/[gh][a-z]*[eo]/"&"/g'
You say "goodbye" and I say "hello".

Just as 's/\\usmthing/…/' is the way to search for \usmthing,
you need to use 's/…/\\usmthing/' to insert \usmthing.
For example,
$ echo Boo | sed 's/oo/\ulish/'
BLish                  ← Note that \ul was interpreted to mean "put 'l' into upper case".

$ echo Boo | sed 's/oo/\\ulish/'
B\ulish


text:
Q: What is the difference between APIView class and generics.GenericAPIView What is the difference between  APIView class and generics.GenericAPIView

A: APIView is the base class based view. Viewsets have APIView as a parent class.
With APIview you code methods etc for the different HTTP call methods such as post, get, put etc. These come with no standard configuration, so you can customise to your needs
With Viewsets, you code more specific methods . For example the 'retrieve' method, will expect arguments of the request and the pk of the object to be retrieved. Thus you write methods for create, retrieve, list, etc instead of post,get…
Moving on from that, you also have the routers. These work with viewsets and will create the urls for you based on how you coded the Viewset

A: APIView is a base class. It doesn't assume much and will allow you to plug pretty much anything to it.
GenericAPIView is meant to work with Django's Models. It doesn't assume much beyond all the bells and whistles the Model introspection can provide.


text:
Q: Ubuntu 14.04 LTS login problem (incorrect login) I have a dual-boot system of Windows 7 and Ubuntu 14.04 LTS.
I primarily use my ubuntu however. Umm I tried to install Octave 4.0 into the system and then it somehow crashed and upon restart of the computer, I just cannot get into the desktop environment again.
I try to put in my login details and the system just gets stuck there and fails to load any further (only with the ubuntu background screen) Nothing else seems to happen..
I've also tried the terminal login process -> Crtl + Alt + F1 and even there, I cannot seem to login; I put my details in and it says that I have "Incorrect login" details
I want to resolve this however I can ASAP.
Could someone kindly offer me help on this issue and how I could recover and get back working into ubuntu desktop again?
Would be greatly appreciated. Thanks in advance!


text:
Q: How to improve performance of Multiple Select in React Material-UI for long lists? I would like to have a Material-UI multiple select for choosing countries, however with a long list of options ~200 I find the performance sluggish, particularly on slower machines (~1 second delay).
Is there something that can be done to improve this performance?
Below is the default multiple select example with person names switched for a country list.
https://codesandbox.io/s/material-demo-uh7k1

A: You should check this, it's an issue from material-ui github. They state that when you have a large set of items, you should use a virtualized list or the native select.


text:
Q: Troubles with saving UserCreationForm in Django I have my registration view, that uses UserCreationForm. Here it is:
def registration(request):
    if request.method == 'POST':
        form = UserCreationForm()
        if form.is_valid:
            user = form.save()
            login(request, user)
            return redirect('home')
    else:
        if request.user.is_authenticated:
            logout(request)
        form = UserCreationForm()
    context = {'form':form,}
    return render(request, "register.html",context)

But somehow when I try to create new user, I get AttributeError, that says "
'UserCreationForm' object has no attribute 'cleaned_data'" even though I don't have any calls of cleaned_data whatsoever. I tried to create my custom registration form which used cleaned_data, but I threw this away and wiped my custom form from the project completely. Why could this happen?
P.S. The line that causes problems according to my Django debug return is user = form.save()

A: When handling form submission in function based views you need to pass the request data to the form constructor in order to get a populated form instance.
Calling form.is_valid() (note this is actually a method as Abdul pointed out) will execute the form's clean method which is responsible for storing the clean data in form.cleaned_data. Again, as Abdul pointed out form.save() internally uses form.cleaned_data meaning that the form needs to be cleaned and validated before saving.
def registration(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)  # instantiate form with request data
        if form.is_valid():                    # validate and clean form
        ...

This is really nicely explained in the documentation on working with forms. Take a look at this example but I would really recommend skimming through the entire document to get a better idea of how forms in django work/are used.


text:
Q: String.format() Bug? The following gives different results in J2SE and Android for the de_DE locale:
Locale locale = new Locale("de","DE");
log(String.format(locale,"%.1f", 0.45));

In JRE 1.6.0_22, I get "0,5" as expected.
With the Android Platform 2.2 I get "0,4"
Thanks, Roland

A: I wouldn't call it a bug, unless you point me to a specification that says, which rounding mode the String.format method should be using. It seems that the 1.6 JRE uses UP or HALF_UP as a RoundingMode. In Android however, HALF_EVEN mode is used, which also seems the default mode for DecimalFormat. This is the code I've used with JRE to test the above:
import java.util.Locale;
import java.text.DecimalFormat;
import java.math.RoundingMode;

public class Test {

    public static void main(String [] args) {
        Locale locale = new Locale("de","DE");
        String str = String.format(locale,"%.1f", 0.45);
        System.out.println(str);
        System.out.println(String.format("%.1f", 0.45));

        DecimalFormat df = new DecimalFormat("#.#");
        System.out.println(df.format(0.45));
        System.out.println(df.getRoundingMode());
        df.setRoundingMode(RoundingMode.HALF_UP);
        System.out.println(df.format(0.45));
    }
}

It seems that the locale has nothing to do with the rounding mode. Unfortunately, in Android DecimalFormat doesn't seem to support Rounding Modes, so you can't run the same code as is.
I would also be interested in running the same code in JRE 1.5 (which doesn't support the setting of Rounding Mode), but I don't have a suitable environment in my machine.

A: Found the solution for Android:
// format
DecimalFormat df = new DecimalFormat("0.0");
BigDecimal valDec = new BigDecimal(String.valueOf(val));
BigDecimal roundedDec = valDec.setScale(1,BigDecimal.ROUND_HALF_UP);
return df.format(roundedDec.doubleValue());

It's seems to be important to instantiate the BigDecimal with the String representation of the double because if you don't, you will get some funny values.
Here's an example:
BigDecimal test = new BigDecimal(0.85);
Log.v(TAG,"BigDecimal: "+test.toPlainString());

-----> BigDecimal: 0.84999999999999997779553950749686919152736663818359375
If you now use the code above, you of course get 0.8 and not 0.9, what you would expect.
Thanks, Roland


text:
Q: Contact Force of Inflating Balloon I am trying to roughly model the contact force an inflating balloon would apply on the skin. The idea is the balloon would be constrained between an in-extensible layer on one side, and the surface of the forearm on the other side (with the balloon sandwiched in between). As I inflate the constrained balloon, is there any intuition as to how much force would be felt on the skin at different pressures? From my understanding, a rough estimate would take the pressure of the balloon and the contact area and multiply the two to get an estimate.
Any thoughts would be greatly appreciated!


text:
Q: Serve up an aspx page in an asp.net web app using Microsoft.Owin.Host.SystemWeb (Katana) I have .net web application which includes a reference to OWIN.
This is all working fine and is serving up an web application using OWIN happily.
I want to include in the same web application an aspx web page. Is there a way I can inform my web application not to use OWIN for a single page (or a path).

A: From investigation it looks like this might not be possible.
There are a couple of handler mappings which are at play.
System.Web.UI.PageHandlerFactory handles aspx pages
Microsoft.Owin.Host.SystemWeb.OwinHttpHandler handles owin request
I can add them seperately and get close to what I require
i.e:
<system.webServer>
  <handlers>
    <clear />
    <add name="OWIN" path="test" verb="*" type="Microsoft.Owin.Host.SystemWeb.OwinHttpHandler" />
  </handlers>
</system.webServer>

This will allow serve up owin stuff from a targetted path (test in mycase)
and
<system.webServer>
  <handlers>
    <clear />
    <add name="APSX" path="*.aspx" verb="*" type="System.Web.UI.PageHandlerFactory"/>
  </handlers>
</system.webServer>

Will allow me serve up an aspx page - but only if the OWIN dlls are not in the bin directory.
If the OWIN dlls are present then the PageHandlerFactory will drop into OWIN handler and serve up via OWIN making. I.e. even though the OwinHttpHander is not specified, it still kicks into OWIN. I'm guessing this is built into the PageHandlerFactory code.
As far as I can tell, this means that you can never have an aspx page in the same web application which uses Katana (because it need the OWIN dlls, and then PageHandlerFactory calls into the OWIN code rather than aspx - deduced from testing rather than proved out right).


text: Q: how to get a branch created by coworker? we have several branches under the "branches" folder. now coworker created another new branch, dev4, under the "branches" folder. I don't want to do update at the "branches" level because there are few branches I don't need them. I don't want to do checkout because the .svn may be created there. how can I do this with SVN command line command?


text:
Q: SSH: In private network how to access the remote machine from source machine without using ssh public key I have AWS codebuild setup where want to access the EC2 ubuntu instance both are in same VPC and private subnet. Want to execute the command from codebuild to instance using SSH but getting below error, while trying to execute the command on the remote instance:
$ ssh -o 'PubkeyAuthentication no' ubuntu@X.X.X.X uname
Host key verification failed.

I also tried to create the .pem file and pasted the public key to the new pem file, changed its permission and used that. But no success.
$ssh -i "remote-instance.pem" ubuntu@X.X.X.X uname
Host key verification failed.

Is it possible to achieve the same with some options?

A: As you know the first time you ssh to a remote host it asks you whether you'd like to store the remote host key to ~/.ssh/known_hosts. Every time you access the remote host afterwards ssh verifies received host key against ~/.ssh/known_hosts.
However when ssh runs in CodeBuild or some other non-interactive setup it can't ask whether to accept the remote key (because there's no one to ask in a non-interactive session) and to be on the safe side it fails with Host key verification failed
You've got two options how to fix it:

*

*More secure is to provide the Ubuntu server's host key to your CodeBuild and store it to a known_hosts file where ssh can verify it. Make sure it's in the right path with the correct ownership and permissions.

*Less secure is to disable the check:
ssh -o StrictHostKeyChecking=no {your-ubuntu-server}

Hope that helps :)

A: You do want PubkeyAuthentication which will be attempted by default, so do not specify "-o PubkeyAuthentication=no".  The pem file referenced by "-i" should be the private key, not the public key.  The public key will already be in place on your ubuntu server.


text:
Q: Using InStr function to match values from an array to another Context
I am using a code and trying to make a little change in the function from IsInArray(custom) to Instr but get a compiling error.
I am simply tring to change
"If IsInArray(Worksheets("Sheet1").Cells(i, 11).Value, vAllSheet2Values)"

to
 If InStr(Worksheets("Sheet1").Cells(i, 11).Value, vAllSheet2Values)

But it's giving a compile error. Can't I simply change the function ? If not how can I do this?
Code
            Sub remDup()
            Dim LR As Long, LRSheet2 As Long, i As Long, a As Long
            Dim vAllSheet2Values() As Variant

            LRSheet2 = Worksheets("Sheet2").Cells(Rows.Count, 3).End(xlUp).Row
            LR = Worksheets("Sheet1").Cells(Rows.Count, 11).End(xlUp).Row
            a = 2

            For i = 1 To LRSheet2
                ReDim Preserve vAllSheet2Values(i)
                vAllSheet2Values(i) = Worksheets("Sheet2").Cells(i, 3).Value
            Next i

            For i = LR To 1 Step -1
                If IsInArray(Worksheets("Sheet1").Cells(i, 11).Value, vAllSheet2Values) Then
                    Worksheets("Sheet1").Rows(i).Copy Worksheets("Sheet3").Rows(a)
                    Worksheets("Sheet1").Rows(i).Delete
                    a = a + 1
                End If
            Next i
            End Sub

            Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
                IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
            End Function

A: Depending on the size of LR and LRSheet2, this code could take a while to run. This is one way of using InStr() to compare the cells in each column.
I defined your sheets, defined the Rows.Count parts of LR and LRSheet2, and included a second For Loop to cycle through each item in your vAllSheet2Values() array.
Option Explicit
Sub remDup()
    Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Sheet1")
    Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2")
    Dim ws3 As Worksheet: Set ws3 = ThisWorkbook.Sheets("Sheet3")
    Dim LR As Long, LRSheet2 As Long, i As Long, a As Long
    Dim vAllSheet2Values() As String, sheet2Val As Variant

    LRSheet2 = ws2.Cells(ws2.Rows.Count, 3).End(xlUp).Row
    LR = ws1.Cells(ws1.Rows.Count, 11).End(xlUp).Row
    a = 2

    For i = 1 To LRSheet2
        ReDim Preserve vAllSheet2Values(i)
        If ws2.Cells(i, 3).Value <> "" Then _
            vAllSheet2Values(i) = CStr(ws2.Cells(i, 3).Value) 'Don't add blanks
        Debug.Print ws2.Cells(i, 3).Value
    Next i

    For i = LR To 1 Step -1
        If ws1.Cells(i, 11).Value = "" Then GoTo SkipTheRest 'Skip blanks
        For Each sheet2Val In vAllSheet2Values
            If InStr(sheet2Val, CStr(ws1.Cells(i, 11).Value)) <> 0 Then
                ws1.Rows(i).Copy ws3.Rows(a)
                ws1.Rows(i).Delete
                a = a + 1
                GoTo SkipTheRest 'Match found, skip the rest
            End If
        Next sheet2Val
        'You can include the following statement if you want to catch when there
        'isn't a match on Sheet1
        'MsgBox "No match found for " & ws1.Cells(i, 11).Value, vbOKOnly, "No Match"
SkipTheRest:
    Next i
End Sub


text:
Q: How to rename multiple table names with REMAP_TABLE I have a dump file which contains several tables (A, B, C).
How can I rename these tables (A -> x, B -> y, C -> z) during data import?

A: Remapping multiple table names is possible with comma separated table names as following example:
impdp user/pass directory=my_dp_dir remap_schema=src_schema:dest_schema
REMAP_TABLESPACE=src_ts:dest_ts
REMAP_TABLE=src_schema.A:x,src_schema.B:y,src_schema.C:z
dumpfile=dump_file.dmp logfile=impdp.log


text:
Q: How do I fade a div in with jQuery? I have a div defined as the following in my css file:
    #toolbar
    {
        position:relative;
        top: 0;
        height: 50px;
        background-color: #F4A83D;
        width: 100%;
        text-align: center;
        display: hidden;
    }

Then, in my HTML file I have:

        TestApp ToolBar

        You are visiting:
        <%=ViewData["url"] %>

and finally, I have the following script at the top of my html page that I figured would fadeIn my div when the page loads:

What am I doing wrong? It instantly shows up as if it wasn't fading in at all. Am I not accessing my div correctly in the jquery script?

Based off some of the answers I've changed my div to:

        TestApp ToolBar

        You are visiting:
        <%=ViewData["url"] %>

With the same script call, and now my div starts out hidden and never shows up.  What else am I doing wrong?

A: See: http://www.w3schools.com/css/pr_class_display.asp
hidden is not a valid value for the display property. You should use display:none;
That's why you see it instantly, it never has been hidden because the browser has no idea what to do with the display:hidden; declaration.
You propably want the visibility:hidden; property though because that way the toolbar will be invisible but rendered, so it will take it's space in the document. Which will make sure your whole page won't be pushed around when you fade it in.

A: You have to hide the div first.
$('#toolbar').hide().fadeIn('slow');

or like this, so the toolbar won't be visible while the page is still loading:

...

$('#toolbar')
    .css({
        visibility: "visible",
        opacity: 0
    })
    .fadeIn('slow')
;

A: $("button").click(function() {
  $(".element")
  .css({ opacity:0, visibility:"visible" })
  .animate({ opacity:1 }, "slow");
});

A: $("#toolbar").css("display","none");

$("#toolbar").css("display","block").fadeIn('slow');

or you could use animate function.
Animate in JQuery

A: One thing i noticed is your script source.


text:
Q: changing width of button in navigation bar CSS So my html is this:

Home

About Us

and my CSS is this:
#background {
    min-widh: 960px;
}

#navigation {
    min-width: 960px;
}

#navigation ul {
    min-width: 960px;
}

#navigation ul li {
    display: inline;
    width: 100px;
    height: 50px;
    background-color: red;
}

Now, this does create an inline bar except no matter how much I change the width and height of
#navigation ul li

the background color (red) just stays strictly around the letters and nothing else. It seems as if the width and heights of the actual li's are not changing no matter what number I change it to. Any idea why it is doing this?

A: Use display:inline-block instead or display:inline.
#navigation ul li {
    display: inline-block;
}

jsFiddle here
Alternatively, you can also float the elements for a similar effect:
#navigation ul li {
    float:left;
}

jsFiddle here
Aside from both of the above solutions, if you wanted to use display:inline, you could just add padding as opposed to trying to set a height/width.
#navigation ul li {
    display:inline;
    padding:20px;
}

jsFiddle here


text:
Q: Error after uninstalling npm packages I have uninstalled the npm packages 'grunt-cli' and 'tsd' using the command:
sudo npm uninstall -g grunt-cli
sudo npm uninstall -g tsd

But now, when I list all npm packages:
npm -g ls --depth=0

I get this error. There is no such file or directory. This is correct since I just uninstalled them...
/usr/local/lib
├── bower@1.7.1
├── browserify@12.0.1
├── express-generator@4.13.1
├──  error: ENOENT: no such file or directory, open '/usr/local/lib/node_modules/grunt-cli/package.json
├── npm@3.5.3
├──  error: ENOENT: no such file or directory, open '/usr/local/lib/node_modules/tsd/package.json
└── typescript@1.8.9

Why do I get this error? How to completely remove grunt-cli and tsd? What does ENOENT mean? (tried googling it...)

A: The following directories are still there by an accident probably, in spite of you ran npm uninstall command.

*

*/usr/local/lib/node_modules/grunt-cli

*/usr/local/lib/node_modules/tsd
In this case, you need to remove them manually by rm -r command:
$ rm -r /usr/local/lib/node_modules/tsd
$ rm -r /usr/local/lib/node_modules/grunt-cli

Also, you should check the command aliases still exist or not. Command names are
tsd and grunt, just check and remove them if they exist.
$ which tsd <= check command path
/usr/local/bin/tsd <= if it exist
$ rm /usr/local/bin/tsd <= remove it

$ which grunt <= check command path
/usr/local/bin/grunt <= if it exist
$ rm /usr/local/bin/grunt <= remove it

A: Use which grunt-cli to locate the grunt-cli folder and then run sudo rm grunt-cli
Do the same for tsd.


text:
Q: website loads from the bottom of the page, possibly due to script this website: here : always loads from the bottom of the page. i was thinking that this was just a thing solely on my part. however i recently switched computers and i noticed that the problem was still there. it is possible that i have some script that is causing the page to load from the bottom. as of right now it does that in chrome, and i am pretty sure it does it in firefox as well. if you could please see if there is any scripts that are causing it to load from the bottom of the page it would be much appreciated.

A: It is because of the embedded music object at the bottom of the page. It is attempting to focus on that in Chrome.
I created a local copy of your page and removed the object which stopped the issue.
Move the music object to the top of the page and it will stop doing that.
Here is the offending markup:
<object height="1" width="1">
    <param name="src" value="https://dl.dropboxusercontent.com/u/106830429/Zetsuen%20No%20Tempest-%20The%20Civilisation%20Blaster%20Trailer%20Music.mp3">
    <param name="autoplay" value="true">
    <param name="controller" value="true">
    <param name="bgcolor" value="#FFFFFF">
    <embed src="https://dl.dropboxusercontent.com/u/106830429/Zetsuen%20No%20Tempest-%20The%20Civilisation%20Blaster%20Trailer%20Music.mp3" autostart="true" loop="true" controller="true" bgcolor="#FFFFFF" height="1" width="1">
</object>

A: There are many ways to embed audio files.
Please use the <audio> tag. example


text:
Q: ACF and PACF Formula I want to create a code for plotting ACF and PACF from time-series data. Just like this generated plot from minitab (below).

I have tried to search the formula, but I still don't understand it well.
Would you mind telling me the formula and how to use it please?
What is the horizontal red line on ACF and PACF plot above ? What is the formula ?
Thank You,

A: Autocorrelations
The correlation between two variables $y_1, y_2$ is defined as:
$$
\rho = \frac{\hbox{E}\left[(y_1-\mu_1)(y_2-\mu_2)\right]}{\sigma_1 \sigma_2} =
\frac{\hbox{Cov}(y_1, y_2)}{\sigma_1 \sigma_2} \,,
$$
where E is the expectation operator, $\mu_1$ and $\mu_2$ are the means respectively for $y_1$ and $y_2$ and $\sigma_1, \sigma_2$ are their standard deviations.
In the context of a single variable, i.e. auto-correlation, $y_1$ is the original series and $y_2$ is a lagged version of it. Upon the above definition,
sample autocorrelations of order $k=0,1,2,...$ can be obtained by computing the
following expression with the observed series $y_t$, $t=1,2,...,n$:
$$
\rho(k) = \frac{\frac{1}{n-k}\sum_{t=k+1}^n (y_t - \bar{y})(y_{t-k} - \bar{y})}{
\sqrt{\frac{1}{n}\sum_{t=1}^n (y_t - \bar{y})^2}\sqrt{\frac{1}{n-k}\sum_{t=k+1}^n (y_{t-k} - \bar{y})^2}} \,,
$$
where $\bar{y}$ is the sample mean of the data.
Partial autocorrelations
Partial autocorrelations measure the linear dependence of one variable after removing the effect of other variable(s) that affect to both variables. For example, the partial autocorrelation of order measures the effect (linear dependence) of $y_{t-2}$ on $y_t$ after removing the effect of $y_{t-1}$ on both $y_t$ and $y_{t-2}$.
Each partial autocorrelation could be obtained as a series of regressions of
the form:
$$
\tilde{y}_t = \phi_{21} \tilde{y}_{t-1} + \phi_{22} \tilde{y}_{t-2} + e_t \,,
$$
where $\tilde{y}_t$ is the original series minus the sample mean, $y_t - \bar{y}$. The estimate of $\phi_{22}$ will give the value of the partial autocorrelation of order 2. Extending the regression with $k$ additional lags, the estimate of the last term will give the partial autocorrelation of order $k$.
An alternative way to compute the sample partial autocorrelations is by solving the following system for each order $k$:
\begin{eqnarray}
\left(\begin{array}{cccc}
\rho(0) & \rho(1) & \cdots & \rho(k-1) \\
\rho(1) & \rho(0) & \cdots & \rho(k-2) \\
\vdots & \vdots & \vdots & \vdots \\
\rho(k-1) & \rho(k-2) & \cdots & \rho(0) \\
\end{array}\right)
\left(\begin{array}{c}
\phi_{k1} \\
\phi_{k2} \\
\vdots \\
\phi_{kk} \\
\end{array}\right)
=
\left(\begin{array}{c}
\rho(1) \\
\rho(2) \\
\vdots \\
\rho(k) \\
\end{array}\right) \,,
\end{eqnarray}
where $\rho(\cdot)$ are the sample autocorrelations. This mapping between the sample autocorrelations and the partial autocorrelations is known as the
Durbin-Levinson recursion.
This approach is relatively easy to implement for illustration. For example, in the R software, we can obtain the partial autocorrelation of order 5 as follows:
# sample data
x <- diff(AirPassengers)
# autocorrelations
sacf <- acf(x, lag.max = 10, plot = FALSE)$acf[,,1]
# solve the system of equations
res1 <- solve(toeplitz(sacf[1:5]), sacf[2:6])
res1
# [1]  0.29992688 -0.18784728 -0.08468517 -0.22463189  0.01008379
# benchmark result
res2 <- pacf(x, lag.max = 5, plot = FALSE)$acf[,,1]
res2
# [1]  0.30285526 -0.21344644 -0.16044680 -0.22163003  0.01008379
all.equal(res1[5], res2[5])
# [1] TRUE

Confidence bands
Confidence bands can be computed as the value of the sample autocorrelations $\pm \frac{z_{1-\alpha/2}}{\sqrt{n}}$, where $z_{1-\alpha/2}$ is the quantile $1-\alpha/2$ in the Gaussian distribution, e.g. 1.96 for 95% confidence bands.
Sometimes confidence bands that increase as the order increases are used.
In this cases the bands can be defined as $\pm z_{1-\alpha/2}\sqrt{\frac{1}{n}\left(1 + 2\sum_{i=1}^k \rho(i)^2\right)}$.

A:
"I want to create a code for plotting ACF and PACF from time-series
  data".

Although the OP is a bit vague, it may possibly be more targeted to a "recipe"-style coding formulation than a linear algebra model formulation.

The ACF is rather straightforward: we have a time series, and basically make multiple "copies" (as in "copy and paste") of it, understanding that each copy is going to be offset by one entry from the prior copy, because the initial data contains $t$ data points, while the previous time series length (which excludes the last data point) is only $t-1$. We can make virtually as many copies as there are rows. Each copy is correlated to the original, keeping in mind that we need identical lengths, and to this end, we'll have to keep on clipping the tail end of the initial data series to make them comparable. For instance, to correlate the initial data to $ts_{t-3}$ we'll need to get rid of the last $3$ data points of the original time series (the first $3$ chronologically).
Example:
We'll concoct a times series with a cyclical sine pattern superimposed on a trend line, and noise, and plot the R generated ACF. I got this example from an online post by Christoph Scherber, and just added the noise to it:
x=seq(pi, 10 * pi, 0.1)
y = 0.1 * x + sin(x) + rnorm(x)
y = ts(y, start=1800)

Ordinarily we would have to test the data for stationarity (or just look at the plot above), but we know there is a trend in it, so let's skip this part, and go directly to the de-trending step:
model=lm(y ~ I(1801:2083))
st.y = y - predict(model)

Now we are ready to takle this time series by first generating the ACF with the acf() function in R, and then comparing the results to the makeshift loop I put together:
ACF = 0                  # Starting an empty vector to capture the auto-correlations.
ACF[1] = cor(st.y, st.y) # The first entry in the ACF is the correlation with itself (1).
for(i in 1:30){          # Took 30 points to parallel the output of `acf()`
  lag = st.y[-c(1:i)]    # Introducing lags in the stationary ts.
  clipped.y = st.y[1:length(lag)]    # Compensating by reducing length of ts.
  ACF[i + 1] = cor(clipped.y, lag)   # Storing each correlation.
}
acf(st.y)                            # Plotting the built-in function (left)
plot(ACF, type="h", main="ACF Manual calculation"); abline(h = 0) # and my results (right).

OK. That was successful. On to the PACF. Much more tricky to hack... The idea here is to again clone the initial ts a bunch of times, and then select multiple time points. However, instead of just correlating with the initial time series, we put together all the lags in-between, and perform a regression analysis, so that the variance explained by the previous time points can be excluded (controlled). For example, if we are focusing on the PACF ending at time $ts_{t-4}$, we keep $ts_t$, $ts_{t-1}$, $ts_{t-2}$ and $ts_{t-3}$, as well as $ts_{t-4}$, and we regress $ts_t \sim ts_{t-1} + ts_{t-2} + ts_{t-3}+ts_{t-4}$ through the origin and keeping only the coefficient for $ts_{t-4}$:
PACF = 0          # Starting up an empty storage vector.
for(j in 2:25){   # Picked up 25 lag points to parallel R `pacf()` output.
  cols = j
  rows = length(st.y) - j + 1 # To end up with equal length vectors we clip.

  lag = matrix(0, rows, j)    # The storage matrix for different groups of lagged vectors.

for(i in 1:cols){
  lag[ ,i] = st.y[i : (i + rows - 1)]  #Clipping progressively to get lagged ts's.
}
  lag = as.data.frame(lag)
  fit = lm(lag$V1 ~ . - 1, data = lag) # Running an OLS for every group.
  PACF[j] = coef(fit)[j - 1]           # Getting the slope for the last lagged ts.
}

And finally plotting again side-by-side, R-generated and manual calculations:

That the idea is correct, beside probable computational issues, can be seen comparing PACF to pacf(st.y, plot = F).

code here.

A: Well, in the practise we found error (noise) which is represented by $ e_t $ the confidence bands help you to figure out if a level can be considerate as only noise (because about the 95% times will be into the bands).

A: Here is a python code to compute ACF:
def shift(x,b):
    if ( b <= 0 ):
        return x
    d = np.array(x);
    d1 = d
    d1[b:] = d[:-b]
    d1[0:b] = 0
    return d1

# One way of doing it using bare bones
# - you divide by first to normalize - because corr(x,x) = 1
x = np.arange(0,10)
xo = x - x.mean()

cors = [ np.correlate(xo,shift(xo,i))[0]  for i in range(len(x1)) ]
print (cors/cors[0] )

#-- Here is another way - you divide by first to normalize
cors = np.correlate(xo,xo,'full')[n-1:]
cors/cors[0]


text:
Q: How can I update an exisiting image with MYSQL I'm trying to update an existing image in my database using mysql query.
This is my edit.php where i edit user info
<?php
  require_once "config.php";

    if(isset($_GET['edit']))
    {
        $id = $_GET['edit'];
        $res = mysqli_query($link,"SELECT * FROM user_data WHERE id=$id");
        $row = mysqli_fetch_array($res);
    }

    if(isset($_GET['id']))
    {
      $newText = $_GET['voornaam'];
      $newText2 = $_GET['tussenvoegsel'];
      $newText3 = $_GET['achternaam'];
      $newText4 = $_GET['stemsoort'];
      $newText5 = $_GET['adres'];
      $newText6 = $_GET['postcode'];
      $newText7 = $_GET['plaats'];
      $newText8 = $_GET['telefoon'];
      $newText9 = $_GET['mobiel'];
      $newText10 = $_GET['email'];
      $newText11 = $_GET['status'];
      $newText12 = $_GET['lid_sinds'];
      $newText13 = $_GET['lid_tot'];

      $id    = $_GET['id'];
      $res = mysqli_query($link,"SELECT * FROM user_data WHERE id=$id");
      $row = mysqli_fetch_array($res);
      $sql     = "UPDATE user_data SET voornaam='$newText', tussenvoegsel='$newText2', achternaam='$newText3', stemsoort='$newText4', adres='$newText5', postcode='$newText6', plaats='$newText7', telefoon='$newText8', mobiel='$newText9', email='$newText10', status='$newText11',lid_sinds='$newText12',lid_tot='$newText13' WHERE id=$id";
      $res   = mysqli_query($link,$sql)
                                      or die("Could not update".mysqli_error($link));
        echo "<meta http-equiv='refresh' content='0;url=index.php'>";
    }
  ?>

And this is how I upload images to a folder and then into mysql database
 <?php

  $msg = "";
  $css_class = "";

  $conn = mysqli_connect('localhost','root','','test');

  if (isset($_POST['save-user'])) {
    echo "<pre>", print_r($_FILES['profileImage']['name']),"</pre>";

    $bio = $_POST['bio'];
    $profileImageName = time() . '_' . $_FILES['profileImage']['name'];

    $target = 'images/' . $profileImageName;

      if(move_uploaded_file($_FILES["profileImage"]["tmp_name"], $target)) {
        $sql = "INSERT INTO users (profile_image, bio) VALUES ('$profileImageName','$bio')";
        if (mysqli_query($conn,$sql)) {
          $msg = "image uploaded";
          $css_class = "alert alert-success";
        }else {
          $msg = "Database Error: Failed to save user";
          $css_class = "alert alert-danger";
        }
      } else {
        $msg = "Failed to upload image";
        $css_class = "alert alert-danger";
      }
    }

 ?>

How can I combine the two and let a user edit his uploaded profile image? Thanks for helping out


text:
Q: Concurrency guarantees of Weak/Soft/Phantom Reference clearing Besides stronge references, there are three distinct "kinds of *Reference": WeakReference, SoftReference and PhantomReference. There may be others, but they will either extend one those or be irrelevant to my question.
If an object is not strongly reachable during a GC cycle, it gets garbage collected (i.e. finalized and removed from memory). But before it is collected, any *Reference is cleared - depending on reachability conditions, the kind of *Reference to be cleared, memory demand, etc.
I was wondering, if the JLS made any guarantees about whether all *References of the same kind to the same object are cleared atomically/simultaneously, or if there is a slight chance (ie. "race condition"), that some *References get cleared while other *References of the same kind are not, such that an object could potentially be revived (ie. be strongly referenced again) through one of the remaining *References although some *References of the same kind have already been cleared and enqueued.
Question rephrased from a different POV: Is it safe to assume that a cleared *Reference implies that the previously referenced object cannot be revived through a different *Reference of the same kind?

A: You may refer to the documentation.
SoftReference:

[The garbage collector] may choose to clear atomically all soft references to that object and all soft references to any other softly-reachable objects from which that object is reachable through a chain of strong references.

WeakReference:

[The garbage collector] will atomically clear all weak references to that object and all weak references to any other weakly-reachable objects from which that object is reachable through a chain of strong and soft references.

The point is moot for PhantomReference because the referent cannot be retrieved from it (get always returns null).


text:
Q: jQuery: Content of html element is interpreted as a string, not an integer When somebody is liking a comment on my website, a "1" is added at the right of the number where the amount of likes are shown, but when they click dislike, it does correct math.
For example:
14 + 1 = 141
14 - 1 = 13

jQuery
var elem   = $('.like_button'), //Like button
    num    = $('.num_likes'), //Get the element: number of likes
    oldnum = num.html(); //Number of likes

if(elem.html() == "Like") {
    elem.html("Dislike");
    num.html(oldnum+1); //Adds one like after liking it
} else {
    elem.html("Like");
    num.html(oldnum-1); //Deletes one like after disliking it
}

I really wonder why disliking works but liking not.
Why does javascript interpret the value of the num element as a string, even though it is a number? Any tips for me?

A: Because JavaScript interprets num.html() as text. The + sign for string in javascript means concatenation, but - doesn't mean that so in that case javascript realizes you want to do numeric calculation. That's why it works with -
You should cast oldnum to an integer with parseInt().

A: You need to cast oldnum to a number:
if(elem.html() == "Like") {
    elem.html("Dislike");
    num.html(Number(oldnum)+1); //Adds one like after liking it
} else {
    elem.html("Like");
    num.html(Number(oldnum)-1); //Deletes one like after disliking it
}

Alternatively, +oldnum does the same thing as Number(oldnum).

A: Javascript is interpreting the text on your page as a string. This is because that's what text on a page normally is. Take for example:
I am a jelly donut.

Now, in JS, you use the + sign for two things: adding numbers, or putting one string after another.
var addingnumbers = 1+1;
// adding numbers, what you want
var a = "I am";
var b = " a jelly donut";
var addingstrings = a+b;
// adding strings, which you don't want.

As such, the html was interpreted as a string like it normally should be, but in this case shouldn't be. And adding the string to the other string just appended it to the end, rather than doing math. There is an easy solution: convert the innerHTML to a number by multiplying it by 1. Multiplying can't be done to a string, so JS will change it to number form, prepping it to be added to something else.
var oldnum = num.html()*1; // done! The multiplying has changed it to a number.

And if you ever do want to change it back to a string, you can do the reverse with the toString() function.
var aNumberToStartOutWith = 3;
var aStringToEndOffWith = aNumberToStartOutWith.toString();


text:
Q: Show that $X_{n}=\sum_{k=0}^{n} \frac{1}{k!}$ and $X_{n}=\sum_{k=0}^{n} \rho^{k}$ are Cauchy sequences. Show that $X_{n}=\sum_{k=0}^{n} \frac{1}{k!}$  and $X_{n}=\sum_{k=0}^{n} \rho^{k}$ are Cauchy sequences.
I know that for each sequence I have to show the following:
"$\forall \epsilon>0 \text{   }\exists \text{   } N_{\epsilon}=N(\epsilon) \in \mathbb{N}$ s.t. $\forall n \geq N_{\epsilon}$ ,        $ \left | X_{n}-X_{m} \right | < \epsilon $"
1) For the first I have done the following:
$\left | X_{n}-X_{m} \right |=\left | \sum_{k=0}^{n} \frac{1}{k!}-\sum_{k=0}^{m} \frac{1}{k!} \right |=  \left | \sum_{k=n+1}^{m} \frac{1}{k!}\right | $
After this I want to use the fact that $\frac{1}{k!}\leq \frac{1}{2k}$ for $k\geq 3$, suppose that $m\geq n$, and get:
$=  \left | \sum_{k=n+1}^{m} \frac{1}{k!}\right | \leq \left | \sum_{k=n+1}^{m} \frac{1}{2k}\right |=\left | \frac{1}{2(n+1)}+\frac{1}{2(n+2)}+\cdots +\frac{1}{2(m)}\right |$
then I have to bound this with a value that depends on n, on which I will impose that it is less or equal to $\epsilon$ and deduct the value of $N_{\epsilon}$ from there.
my guess so far is $\frac{m-n}{n}<\frac{m}{n} <\epsilon$
but this wont work because it is too big and I it should be "sufficiently" small (smaller than $\epsilon$).
2) For the second sequence I have done the following:
Since $0<\rho<1 \Rightarrow \sum_{k=0}^{\infty}\rho^{k}=\frac{1}{1-\rho}=l $, then we have that
"$\forall \frac{\epsilon}{2}>0 \text{   }\exists \text{   } N'_{\frac{\epsilon}{2}}=N'(\frac{\epsilon}{2}) \in \mathbb{N}$ s.t. $\forall n \geq N'_{\frac{\epsilon}{2}}$ ,        $ \left | \sum_{k=0}^{n} \rho^{k}-l \right | < \frac{\epsilon}{2} $"
Let  $ \epsilon>0$,    I choose $N_{\frac{\epsilon}{2}}=N'_{\frac{\epsilon}{2}}$ .
We want to show that  $N_{\frac{\epsilon}{2}}$  works.
$\text{  if  } n,m\geq N_{\frac{\epsilon}{2}} \Rightarrow$
$\left | X_{n}-X_{m} \right |=\left | \sum_{k=0}^{n} \rho^{k}-\sum_{k=0}^{m} \rho^{k}\right |< \left | \sum_{k=0}^{n} \rho^{k}-l+l-\sum_{k=0}^{m} \rho^{k}\right | \leq \left | \sum_{k=0}^{n} \rho^{k}-l\right |+\left | \sum_{k=0}^{m} \rho^{k}-l \right |<\frac{\epsilon}{2}+\frac{\epsilon}{2}=\epsilon$.
$\therefore N_{\frac{\epsilon}{2}} $ works.
Could you give me any suggestions for the first sequence?
Is the second demonstration correct?
Thanks in advance for your help.

A: For the first we have that $\frac {1}{k!}<\frac {1}{k^2}$ for $k\geq 4$ and thus $\sum_{k=n+1}^{m} \frac {1}{k!}\leq \sum_{k=n+1}^{m} \frac {1}{k^2}$ and $\sum_{k=n+1}^{m} \frac {1}{k^2}$ converges and so the sequence $x_m=\sum_{k=n+1}^{m} \frac {1}{k^2}$ is Cauchy, and thus $y_m=\sum_{k=n+1}^{m} \frac {1}{k!}$ is upper bounded by a Cauchy sequence,so $x_m$ is Cauchy(do your thing with $ε>0$).
For the second well done. But these sums converge and so there are Cauchy.You don't have to show that they are Cauchy with definition,unless you've benn asked too:)

A: For the first series: $X_{n} = \sum^{n}_{k=0} \frac{1}{k!} $ you could use the following approximation:
$$
\left| X_{n} - X_{m} \right| = \left| \sum^{n}_{k=0} \frac{1}{k!} - \sum^{m}_{k=0} \frac{1}{k!} \right| = \left| \sum^{m}_{k=n+1} \frac{1}{k!} \right| \leq \left| \sum^{m}_{k=n+1} \frac{1}{e^{k}} \right|
$$
for a all value of $n$ and  $m$ greater than $ n_{0}$ (say $n_{0} =10$, i'm lazy and this seams a good enough aproximation ) . Now this could be written as
$$
\left| \sum^{m}_{k=n+1} \frac{1}{e^{k}} \right| = \left| \sum^{m}_{k=n+1} e^{-k}  \right| = \left| e^{-(n+1)} \sum^{m-(n+1)}_{k=0} e^{-k}  \right|
$$
Now you can see there first term will drop to infinity and the second series is finite and bound above by
$$
\lim_{n \to \infty}  \sum^{m}_{k=n+1} e^{-k}   = \frac{1}{1-e^{-1}}
$$
This leads to the final expression
$$
\left| X_{n} - X_{m} \right| =  \leq \left| \sum^{m}_{k=n+1} \frac{1}{e^{k}} \right| \leq   \frac{e^{-(n+1)}}{1-e^{-1}}
$$
From here on it isn't difficult to produce an $\epsilon - \delta$ proof.
i.e. Take $\epsilon > 0$ random and $n$ so that
$$
n > \max \left( n_{0},\log(\epsilon(1-e^{-1}))-1 \right)
$$
And so on.
Hope this helps.


text:
Q: .NET Core Shared Cookies I have .NET Core app with .NET Core Identity.
I've setup shared cookie into Startup.cs:
services.AddIdentity<User, Role>()
    .AddEntityFrameworkStores<DataContext>()
    .AddDefaultTokenProviders();

services.ConfigureApplicationCookie(options =>
{
    options.Cookie.Name = ".AspNet.SharedCookie";
});

services.AddAuthentication()

...

app.UseAuthentication();
app.UseAuthorization();

Also I have 2nd .NET Core app where I don't have authentication at all but want to use just that SharedCookie and I did the following in the Startup.cs:
services.AddAuthentication("Identity.Application")
    .AddCookie("Identity.Application", options =>
    {
        options.Cookie.Name = ".AspNet.SharedCookie";
    });

...

app.UseAuthentication();
app.UseAuthorization();

and on controller actions I set attribute [Authorize].
I logged in into 1st app and go to 2nd app and see error /Account/Login... page doesn't exist.
Yes I don't have that page but why do I see this issue? Did I forget anything to add in my code?
And one more question: what's SharedCookie string? Is it random string or it's encoded some user data? can I extract any info from that SharedCookie, for example Id of User?

A: So my solution was to add DataProtection step to both apps:
if (!Env.IsDevelopment())
{
    services.AddDataProtection()
        .PersistKeysToFileSystem("{PATH TO COMMON KEY RING FOLDER}")
        .SetApplicationName("SharedCookieApp");
}

And one more question: what's SharedCookie string? Is it random string or it's encoded some user data? can I extract any info from that SharedCookie, for example Id of User?

Yes, I can extract Id, Email of user in the following way:
var id = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
var email = HttpContext.User.FindFirstValue(ClaimTypes.Email);


text:
Q: Asynchronous task in Android withou using AsyncTask everyone!
I'm building an app for the company where I work and we have to run an interaction with an API in the background, but while this interaction is running, the interaction sends us some messages that must enable/disable some views in activity/fragment.
We are running this interaction using the async task, but the problem is: I can't update a view attribute when the message comes from a background thread. I had to use a custom Progress class to handle those messages and then change the view attributes.
In our app, we are using MVVP pattern, and my async task is called from a ViewModel, which is responsible for execute the bizness logic.
But what I really want to know is: Is there another way to perform an async task without using an AsyncTask subclass? Maybe some of you guys can halp me out recommending a way that use callbacks to notify messages and when the function ends.
I know that Retrofit makes an asynchronous task using the enqueue method, but I didn't understand how can I implement that way by myself.
Ps.: The AsyncTask subclass is working fine, but I didn't get along with that implementation.

A: Why  can't you update a view attribute when the message comes from a background thread? it can be done in many ways.
Anyway, there is no other way out, since I/O operations cannot be performed on the GUI thread, only on some background thread.

A: You can take a look at libraries like retrofit for performing API calls.
Also, if you are using kotlin you can take a look at coroutines for a more generic asyncronous work.


text:
Q: How to store elements in 2d vector without knowing his width? I have a 1 dimensional vector
std::vector<int> vec1 = {4, 5, 6, 7};

and I want to store these elements in a 2 dimensional vector
std::vector<std::vector<int>> vec2;

but vec2 can only have height 3 and I have in vec1 - 4 elements.
The output of vec2 should be:
4 7
5
6

A: Maybe I do not fully understand the question, but what I understood can be achieved by 1 simple for loop. Just take into account, that we have only 3 rows.
There is not much to explain . . .
Please see:
#include <iostream>
#include <vector>

int main() {

    // 1d vector with any number of values
    std::vector<int> vec1 = { 4, 5, 6, 7 };

    //2d vector with 3 rows
    std::vector<std::vector<int>> vec2(3);

    // Take all elements from vec1 and copy them to vec2, columns first
    for (size_t i{}; i < vec1.size(); ++i)
        vec2[i % 3].push_back(vec1[i]);

    // Output
    for (const auto& v : vec2) {
        for (const auto& i : v) std::cout << i << "\t";
        std::cout << '\n';
    }

    return 0;
}

I would like to add an explanation for vec2[i % 3].push_back(vec1[i]);-
You can somehow think that the 2 dimensional std::vector consists of rows and columns. And a row contains again a std::vector, which contains the columns value.
So, if I want to use row 0, then I van write vec[0]. And if I want to add column values for row 0, then I can write vec[0].push_back().
For row 1 and row 2 the similar approach applies. And since we want to distribute all values from "vec1" with index 0,1,2,3,4,5,6,7 . . . to rows with the numbers 0,1,2,0,1,2,0,1,2,0,1,2 . . . we need to calculate the row number from the index of "vec1". And this can easily be done with the modulo division %
So:
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
4 % 3 = 1
5 % 3 = 2
6 % 3 = 0
7 % 3 = 1
. . .

That is all.


text:
Q: Update dateTimePicker in another process by DTM_SETSYSTEMTIME I am trying to update the dateTimeController in another application using DTM_SETSYSTEMTIME.
bool retVal = false;
ushort GDT_VALID = 0;

SYSTEMTIME td = new SYSTEMTIME();
td.wYear = 1990;
td.wMonth = 4;
td.wDay = 2;
td.wDayOfWeek = 0;
td.wHour = 0;
td.wMilliseconds = 0;
td.wMinute = 0;
td.wSecond = 0;

int erc = SendMessage(handle, DTM_SETSYSTEMTIME, GDT_VALID, ref td);

Unfortunately the attempt was failed, the picker is not updated, every time return value is zero.
Important thing is occasionally the application having the dataTimePicker gives an error message that illegal memory access exception after I execute the SendMessage command.
Can anybody help me to fix this up ?

A: Yes, cannot work.  The 4th argument to SendMessage is a pointer to SYSTEMTIME.  The pointer value is only valid in your process, not the one that owns the control.  Crashing the target app with that pointer value is quite possible.  You will need to

*

*call OpenProcess() on the target process to obtain its handle

*call VirtualAllocEx() to allocate memory in the target process

*call WriteProcessMemory() to copy the SYSTEMTIME value from your process to the target process

*call SendMessage, using the pointer value you got from VirtualAllocEx

*call VirtualFreeEx() to release the memory

*call CloseHandle() to release the process handle.

Lots of things that can go wrong here, starting with UAC stopping you from executing these highly privileged API functions.  The function names google well, you should have little trouble finding sample code.

A: Your information is really helpful for me to fix my issue. Following is the code.
private static bool injectMemory(IntPtr windowHandle, byte[] buffer, out IntPtr hndProc, out IntPtr lpAddress)
    {
        hndProc = IntPtr.Zero;
        lpAddress = IntPtr.Zero;
        //open local process object
        Process mainWindowProcess = FindProcess(windowHandle);
        hndProc = OpenProcess(
            (0x2 | 0x8 | 0x10 | 0x20 | 0x400), //create thread, query info, operation
            //write, and read
            1,
            (uint)mainWindowProcess.Id);
        if (hndProc == (IntPtr)0)
        {
            Console.WriteLine("Unable to attach process");
            return false;
        }
        //allocate memory for process object
        lpAddress = VirtualAllocEx(hndProc, (IntPtr)null, (uint)buffer.Length,
             AllocationType.Commit | AllocationType.Reserve, MemoryProtection.ExecuteReadWrite);
        if (lpAddress == (IntPtr)0)
        {
            Console.WriteLine("Unable to allocate memory to target proces");
            return false;
        }
        //wite data
        uint wrotelen = 0;
        WriteProcessMemory(hndProc, lpAddress, buffer, (uint)buffer.Length, out wrotelen);
        if (Marshal.GetLastWin32Error() != 0)
        {
            Console.WriteLine("Unable to write memory to process.");
            return false;
        }
        return true;
    }

Method is called by,
        int structMemLen =  Marshal.SizeOf(typeof(SYSTEMTIME));
        byte[] buffer = new byte[structMemLen];
        ushort GDT_VALID = 0;
        SYSTEMTIME sysTime = new SYSTEMTIME();
        //Assign the values as you prefer

        IntPtr dataPtr = Marshal.AllocHGlobal(structMemLen);
        Marshal.StructureToPtr(sysTime, dataPtr, true);
        Marshal.Copy(dataPtr, buffer, 0, structMemLen);
        Marshal.FreeHGlobal(dataPtr);

        IntPtr hndProc = IntPtr.Zero;
        IntPtr lpAddress = IntPtr.Zero;
        injectMemory(mainWindowHandle, buffer, out hndProc, out lpAddress);
        SendMessage(handle, DTM_SETSYSTEMTIME, (IntPtr)GDT_VALID, lpAddress);
        CloseHandle(hndProc);

A: using System;
using System.Security;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;

namespace DateTimePicker.Helpers
{
    [Flags]
    public enum ProcessAccessFlags : uint
    {
        All = 0x001F0FFF,
        Terminate = 0x00000001,
        CreateThread = 0x00000002,
        VirtualMemoryOperation = 0x00000008,
        VirtualMemoryRead = 0x00000010,
        VirtualMemoryWrite = 0x00000020,
        DuplicateHandle = 0x00000040,
        CreateProcess = 0x000000080,
        SetQuota = 0x00000100,
        SetInformation = 0x00000200,
        QueryInformation = 0x00000400,
        QueryLimitedInformation = 0x00001000,
        Synchronize = 0x00100000
    }

    [Flags]
    public enum AllocationType : uint
    {
        Commit = 0x1000,
        Reserve = 0x2000,
        Decommit = 0x4000,
        Release = 0x8000,
        Reset = 0x80000,
        Physical = 0x400000,
        TopDown = 0x100000,
        WriteWatch = 0x200000,
        LargePages = 0x20000000
    }

    [Flags]
    public enum MemoryProtection : uint
    {
        Execute = 0x10,
        ExecuteRead = 0x20,
        ExecuteReadWrite = 0x40,
        ExecuteWriteCopy = 0x80,
        NoAccess = 0x01,
        ReadOnly = 0x02,
        ReadWrite = 0x04,
        WriteCopy = 0x08,
        GuardModifierflag = 0x100,
        NoCacheModifierflag = 0x200,
        WriteCombineModifierflag = 0x400
    }

    public class DateTimePickerNativeMethods
    {
        private const int DTM_GETSYSTEMTIME = 0x1001;
        private const int DTM_SETSYSTEMTIME = 0x1002;

        public static DateTime GetDateTime(IntPtr hwnd)
        {
            var hProcess = TryOpenProcess(hwnd);
            var typeSize = Marshal.SizeOf(typeof(SYSTEMTIME));

            var hMem = VirtualAllocEx(hProcess, IntPtr.Zero, (uint)typeSize, (uint)(AllocationType.Commit | AllocationType.Reserve), (uint)MemoryProtection.ReadWrite);
            var lResult = NativeMethods.SendMessage(hwnd, DTM_GETSYSTEMTIME, IntPtr.Zero, hMem);
            var address = Marshal.AllocHGlobal(typeSize);
            if (ReadProcessMemory(hProcess, hMem, address, typeSize, out IntPtr lpNumberOfBytesRead) == false)
            {
                throw new Exception();
            }

            var systemtime = (SYSTEMTIME)Marshal.PtrToStructure(address, typeof(SYSTEMTIME));

            Marshal.FreeHGlobal(address);
            VirtualFreeEx(hProcess, hMem, typeSize, AllocationType.Decommit | AllocationType.Release);
            CloseHandle(hProcess);

            return new DateTime(systemtime.Year, systemtime.Month, systemtime.Day, systemtime.Hour, systemtime.Minute, systemtime.Second);
        }

        public static void SetDateTime(IntPtr hwnd, DateTime dateTime)
        {
            var typeSize = Marshal.SizeOf(typeof(SYSTEMTIME));
            var buffer = new byte[typeSize];

            var data = Marshal.AllocHGlobal(typeSize);
            Marshal.StructureToPtr(new SYSTEMTIME(dateTime), data, true);
            Marshal.Copy(data, buffer, 0, typeSize);
            Marshal.FreeHGlobal(data);

            CreateMemory(hwnd, buffer, out IntPtr hwndProc, out IntPtr lpAddress);
            NativeMethods.SendMessage(hwnd, DTM_SETSYSTEMTIME, IntPtr.Zero, lpAddress);
            CloseHandle(hwndProc);
        }

        private static void CreateMemory(IntPtr windowHandle, byte[] buffer, out IntPtr hwndProc, out IntPtr lpAddress)
        {
            hwndProc = TryOpenProcess(windowHandle);
            lpAddress = TryGetLParamAddress(hwndProc, buffer.Length);
            TryWriteProcessMemory(hwndProc, lpAddress, buffer);
        }

        private static IntPtr TryOpenProcess(IntPtr hwnd)
        {
            var process = FindProcess(hwnd);
            var hwndProcess = OpenProcess(process, ProcessAccessFlags.All);
            if (hwndProcess == IntPtr.Zero)
            {
                throw new Exception("failed to open process");
            }
            return hwndProcess;
        }

        private static IntPtr TryGetLParamAddress(IntPtr hwndProc, int length)
        {
            var lpAddress = VirtualAllocEx(
                hwndProc,
                (IntPtr)null,
                (uint)length,
                (uint)(AllocationType.Commit | AllocationType.Reserve),
                (uint)MemoryProtection.ExecuteReadWrite)
                ;

            if (lpAddress == IntPtr.Zero)
            {
                throw new Exception();
            }

            return lpAddress;
        }

        private static void TryWriteProcessMemory(IntPtr hwndProc, IntPtr lpAddress, byte[] buffer)
        {
            WriteProcessMemory(hwndProc, lpAddress, buffer, buffer.Length, out IntPtr wrotelen);
            if (Marshal.GetLastWin32Error() != 0)
            {
                throw new Exception();
            }
        }

        private static Process FindProcess(IntPtr windowHandle)
        {
            var automationElement = System.Windows.Automation.AutomationElement.FromHandle(windowHandle);
            var process = Process.GetProcessById(automationElement.Current.ProcessId);
            return process;
        }

        #region Win32 methods
        [DllImport("kernel32.dll", SetLastError = true)]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool CloseHandle(IntPtr hObject);

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int nSize, out IntPtr lpNumberOfBytesWritten);

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, uint processId);
        public static IntPtr OpenProcess(Process proc, ProcessAccessFlags flags)
        {
            return OpenProcess((uint)flags, false, (uint)proc.Id);
        }

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        public static extern bool VirtualFreeEx(IntPtr hProcess, IntPtr lpAddress, int dwSize, AllocationType dwFreeType);

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, int dwSize, out IntPtr lpNumberOfBytesRead);
        #endregion
    }
}