text:
Q: Less less.modifyVars not working in Visual Studio? I am trying to change the variable of LESS on the fly via HTML in an AngularJS function. I wrote the same code and ran on xamp, with simple HTML, CSS it works. Now when I put the same code in the enterprise app in Visual Studio, it doesn't work. The variables compile, the function works. Just that the less.modifyVars doesn't work, and it doesn't change on the fly. This is how my HTML looks
<link rel="stylesheet/less" href="~/Content/brandnew.less">
<script>
var less = {
    logLevel: 0,
    env: "development"
};
</script>
<script src="~/Content/less.min.js"></script>

In the body
 <form ng-submit="changeLess()">
                Enter text and hit enter to change color:
                <input type="text" ng-model="text" name="text" />
                <input type="submit" id="submit" value="Submit" />
            </form>

My less file.
@color: #f16e8d;
.custom-anchor-color {
    color: @color;
}

And my JS function. This is the exact same function, I ran on my localhost. But it doesn't work on the VS.
$scope.changeLess = function() {
            if ($scope.text) {
                debugger;
                less.modifyVars({
                    color: $scope.text
                });
                console.log($scope.text + ' inside $scope.text')
            }
        }

It is logging the function properly, but the variable color doesn't change. I tried keeping it as 'color' as well with the quotations.

A: I found the bug. The app was already rendering the code beforehand, and hence there weren't any variables left in the LESS file because it was rendered. This is possible in VS by using dotless. This is how the code looks for it.
<httpHandlers>
      <add path="*.less" verb="GET" type="dotless.Core.LessCssHttpHandler, dotless.Core" />
    </httpHandlers>

More about can be found here. http://www.dotlesscss.org/

A: try this:
less.modifyVars({
  '@color': $scope.text
});


text:
Q: A word to describe a person who has gone astray What is a person who has gone astray called?
This basically refers to the person who is not following the path to success but has gone astray . For instance these lines from the psalm of life depict a person who has gone astray :
"A forlorn and shipwrecked brother "

A: A person can "go off the rails", which means they may have started to behave out of line, in an unacceptable way, or they are not conforming or performing to the standards expected of them (by society).
Example: If a child starts skipping school and falls in with a bad crowd, you might say they have gone off the rails.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I design a generic observer pattern protocol in Swift? I want to design a generic Swift protocol for the observer pattern for use with different types/classes. The problem is that I can't seem to specify the type for the observer's notify() method.
Initially, I tried creating an associatedtype with my Observer protocol.
protocol Observer {
    associatedtype T
    func notify(_ value: T)
}

protocol Observable {
    var observers: [Observer] { get set }
    func registerObserver(_ observer: Observer)
    func unregisterObserver(_ observer: Observer)
}

This doesn't work (compilation error): error: protocol 'Observer' can only be used as a generic constraint because it has Self or associated type requirements.
So I tried using generic methods instead:
protocol Observer {
    func notify<T>(_ value: T)
}

protocol Observable {
    associatedtype T
    var observers: [Observer] { get set } // This is okay now
}

extension Observable {
    // implement registerObserver()
    // implement unregisterObserver()

    func notifyObservers<T>(_ value: T) {
        for observer in observers {
            observer.notify(value)
        }
    }
}

This works just fine, but leads to some pretty interesting result. To test it out, I created FooObserver and FooObservable:
class FooObserver: Observer {
    func notify<T>(_ value: T) {
        print(value)
    }
}

class FooObservable: Observable {
    typealias T = Int // For simplicity I set T to Int type
    var observers: [Observer] = []
}

let a = FooObserver()
let b = FooObserver()
var c = FooObservable()
c.registerObserver(a)
c.registerObserver(b)
c.notifyObservers("hello") // This works, but why?

I was able to successfully notify my 2 observers of the string "hello". I'm guessing this has to do with type erasure...?
So my question is: how can I implement a generic-type observer pattern where I can be sure that the value in notify() is of the correct type?

A: protocol Observer {
    associatedtype T
    func notify(_ value: T)
}

This says that a given observer can handle one specific type (T) that the observer chooses.
protocol Observable {
    var observers: [Observer] { get set }
    func registerObserver(_ observer: Observer)
    func unregisterObserver(_ observer: Observer)
}

This is invalid, because the system has no way to know what T you want for these observers. Each observer can only handle exactly one T.
protocol Observer {
    func notify<T>(_ value: T)
}

This is basically meaningless. It says that notify can be called with any type at all. If that's what you mean, you want to say:
protocol Observer {
    func notify(_ value: Any)
}

But that means that every observer has to deal with Any, which is not good. The reason it happens to work is that you chose print as your test. print can handle Any. When you want to test these kinds of things, you need to try something like what you really want to do in your program. Printing works for all kinds of things that are useless for any other purpose.
The basic problem is that Observer shouldn't be a protocol. It should be a function. For example:
typealias Observer<T> = (T) -> Void

protocol Observable {
    associatedtype T
    var observers: [Observer<T>] { get set }
    func registerObserver(_ observer: Observer<T>)
    func unregisterObserver(_ observer: Observer<T>)
}

The problem with this approach is there's no way to implement unregisterObserver. I'm not clear how you've implemented unregisterObserver in your code, either. It doesn't really look possible.
Here's one very simple way to build an observable:
typealias Observer<T> = (T) -> ()

struct Subscription {
    let cancel: () -> Void
}

final class Observable<T> {
    private var observations: [UUID: Observer<T>] = [:]
    func subscribe(observer: @escaping Observer<T>) -> Subscription {
        let uuid = UUID()
        observations[uuid] = observer
        return Subscription(cancel: { [weak self] in self?.observations[uuid] = nil })
    }
}

(See https://stackoverflow.com/a/55389143/97337 for where this comes from.)
For a more fully worked out version that is very simple, see Observable. For a somewhat more complicated version that is a little quirky, see Stream. For a more powerful and less quirky version, see Properties. For a very powerful version that establishes a whole way of programming, see RxSwift.


text:
Q: Como buscar un valor en un dataframe y tomar el valor de una variable de ese df en R Tengo valores en un dataframe que debo buscar en un segundo dataframe y tomar el valor de una variable de este último.
Es algo similar a la función buscarv de excel.
El primer data frame es algo así:
angulos <- data.frame(stringsAsFactors = FALSE, valor = c(10,235,179.4,16))

El segundo dataframe es este:
sec <- data.frame(stringsAsFactors = FALSE,
            sectores = c("NNE","NE","ENE","E",
                   "ESE","SE","SSE","S","SSW","SW","WSW","W","WNW",
                   "NW","NNW","N"),
            V2 = c(33.75,56.25,78.75,
                   101.25,123.75,146.25,168.75,191.25,213.75,236.25,
                   258.75,281.25,303.75,326.25,348.75,11.25))

Lo que necesito realizar es buscar los valores del df angulos en el df sec que coincida o esté cercano a un valor de la variable V2, tomar el valor de la variable sectores y colocarlo en una nueva variable en el df angulos junto a su valor correspondiente.
De tal manera que el resultado quede algo similar a esto:

valor
sector

10
NNE

235
WSW

179.4
S

16
NNE

La búsqueda no la realiza exacta sino que busca el valor más cercano y eso lo asocia con el valor de la variable sectores.
Buscando en otros posts, la solución la plantean con left_join pero en este caso no existe una columna común en los dos df, por lo que no es aplicable.
Les agradecería si me brindan ayuda para encontrar la solución.

A: Este es un enfoque bien básico con R base, la idea es: por cada fila de angulos ubicar el valor más cercano en sec y luego sí hacer un "join" de los dos data.frames:
valores <- sapply(1:nrow(angulos), FUN=function(i) sec$V2[which.min(abs(angulos$valor[i] - sec$V2))][1])
merge(cbind(angulos, V2=valores), sec, by="V2", all.x=TRUE)

      V2 valor sectores
1  11.25  10.0        N
2  11.25  16.0        N
3 168.75 179.4      SSE
4 236.25 235.0       SW

Otro enfoque, un poco más "elegante" aunque no necesariamente más performante es usar dplyr/tidr, hacer un producto cartesiano entre ambas tablas y filtrar los valores que sean más cercanos:
library(tidyverse)

angulos %>%
  left_join(angulos %>%
              crossing(sec) %>%
              group_by(valor) %>%
              filter(abs(valor-V2) == min(abs(valor-V2))),
            by = "valor")

# A tibble: 4 x 3
# Groups:   valor [4]
  valor sectores    V2
  <dbl> <chr>    <dbl>
1   10  N         11.2
2   16  N         11.2
3  179. SSE      169.
4  235  SW       236.


text:
Q: Need to create a list of sets, from a list of sets whose members may be connected I'm dealing with polygonal data in realtime here, but the problems quite simple.
I have a huge list containing thousands of sets of polygon Indecies (Integers) and I need to simplify the list as "fast" as possible into a list of sets of "connected" Indecies.
i.e. Any sets containing integers that are also in another set become one set in the result. I've read several possible solutions involving sets & graphs etc. All i'm after are a final list of sets which had any degree of commonality.
I'm dealing with lots of data here, but for simplicities sake here's some sample data:
setA = set([0,1,2])
setB = set([6,7,8,9])
setC = set([4,5,6])
setD = set([3,4,5,0])
setE = set([10,11,12])
setF = set([11,13,14,15])
setG = set([16,17,18,19])

listOfSets = [setA,setB,setC,setD,setE,setF,setG]

In this case I'm after a list with a result like this, although ordering is irrelevant:
connectedFacesListOfSets = [ set([0,1,2,3,4,5,6,7,8,9]), set([10,11,12,13,14,15]), set([16,17,18,19])]
I've looked for similar solutions, but the one with the highest votes gave incorrect results on my large test data.
Merge lists that share common elements

A: It's hard to tell the performance without a sufficiently large set, but here is some basic code to start from:
while True:
    merged_one = False
    supersets = [listOfSets[0]]

    for s in listOfSets[1:]:
        in_super_set = False
        for ss in supersets:
            if s & ss:
               ss |= s
               merged_one = True
               in_super_set = True
               break

        if not in_super_set:
            supersets.append(s)

    print supersets
    if not merged_one:
        break

    listOfSets = supersets

This works in 3 iterations on the provided data. And the output is as follows:
[set([0, 1, 2, 3, 4, 5]), set([4, 5, 6, 7, 8, 9]), set([10, 11, 12, 13, 14, 15]), set([16, 17, 18, 19])]
[set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), set([10, 11, 12, 13, 14, 15]), set([16, 17, 18, 19])]
[set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), set([10, 11, 12, 13, 14, 15]), set([16, 17, 18, 19])]

A: This is a union find problem.
Though I haven't used it, this Python code looks good to me.
http://code.activestate.com/recipes/577225-union-find/

A: Forgive the messed up caps (autocorrect...):
# the results cotainer
Connected = set()

sets = # some list of sets

# convert the sets to frozensets (which are hashable and can be added to sets themselves)
Sets = map(frozenset, sets)

for s1 in sets:
    Res = copy.copy(s1)
    For s2 in sets:
        If s1 & s2:
            Res = res | s2
    Connected.add(res)

A: So.. I think I got it. It's a mess but I got it. Here's what I did:
def connected_valid(li):
    for i, l in enumerate(li):
        for j, k in enumerate(li):
            if i != j and contains(l,k):
                return False
    return True

def contains(set1, set2):
    for s in set1:
        if s in set2:
            return True
    return False

def combine(set1, set2):
    set2 |= set1
    return set2

def connect_sets(li):
    while not connected_valid(li):
        s1 = li.pop(0)
        s2 = li[0]
        if contains(s1, s2):
            li[0] = combine(s1,s2)
        else:
            li.append(s1)
    return li

Then in the main function you'd do something like this:
setA = set([0,1,2])
setB = set([6,7,8,9])
setC = set([4,5,6])
setD = set([3,4,5,0])
setE = set([10,11,12])
setF = set([11,13,14,15])
setG = set([16,17,18,19])

connected_sets = connect_sets([setA,setB,setC,setD,setE,setF,setG,])

After running it, I got the following output
print connected_sets
[set([0,1,2,3,4,5,6,7,8,9]), set([10,11,12,13,14,15]), set([16,17,18,19])]

Hope that's what you're looking for.
EDIT: Added code to randomly generate sets:
# Creates a list of 4000 sets with a random number of values ranging from 0 to 20000
sets = []
ma = 0
mi = 21000
for x in range(4000):
    rand_num = sample(range(20),1)[0]
    tmp_set_li = sample(range(20000), rand_num)
    sets.append(set(tmp_set_li))

The last 3 lines can be condensed into one if you really wanted to.

A: I tried to do something different: this algorithm loops once for each set and once for each element:
# Our test sets
setA = set([0,1,2])
setB = set([6,7,8,9])
setC = set([4,5,6])
setD = set([3,4,5,0])
setE = set([10,11,12])
setF = set([11,13,14,15])
setG = set([16,17,18,19])

list_of_sets = [setA,setB,setC,setD,setE,setF,setG]

# We will use a map to store our new merged sets.
# This map will work as an reference abstraction, so it will
# map set ids to the set or to other set id.
# This map may have an indirection level greater than 1
merged_sets = {}

# We will also use a map between indexes and set ids.
index_to_id = {}

# Given a set id, returns an equivalent set id that refers directly
# to a set in the merged_sets map
def resolve_id(id):
    if not isinstance(id, (int, long)):
        return None
    while isinstance(merged_sets[id], (int, long)):
        id = merged_sets[id]
    return id

# Points the informed set to the destination id
def link_id(id_source, id_destination):
    point_to = merged_sets[id_source]
    merged_sets[id_source] = id_destination
    if isinstance(point_to, (int, long)):
        link_id(point_to, id_destination)

empty_set_found = False
# For each set
for current_set_id, current_set in enumerate(list_of_sets):
    if len(current_set) == 0 and empty_set_found:
        continue
    if len(current_set) == 0:
        empty_set_found = True
    # Create a set id for the set and place it on the merged sets map
    merged_sets[current_set_id] = current_set
    # For each index in the current set
    possibly_merged_current_set = current_set
    for index in current_set:
        # See if the index is free, i.e., has not been assigned to any set id
        if index not in index_to_id:
            # If it is free, then assign the set id to the index
            index_to_id[index] = current_set_id
            # ... and then go to the next index
        else:
            # If it is not free, then we may need to merge the sets
            # Find out to which set we need to merge the current one,
            # ... dereferencing if necessary
            id_to_merge = resolve_id(index_to_id[index])
            # First we check to see if the assignment is to the current set or not
            if id_to_merge == resolve_id(merged_sets[current_set_id]):
                continue
            # Merge the current set to the one found
            print 'Merging %d with %d' % (current_set_id, id_to_merge)
            merged_sets[id_to_merge] |= possibly_merged_current_set
            possibly_merged_current_set = merged_sets[id_to_merge]
            # Map the current set id to the set id of the merged set
            link_id(current_set_id, id_to_merge)
# Return all the sets in the merged sets map (ignore the references)
print [x for x in merged_sets.itervalues() if not isinstance(x, (int, long))]

It prints:
Merging 2 with 1
Merging 3 with 0
Merging 3 with 1
Merging 5 with 4
[set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), set([10, 11, 12, 13, 14, 15]), set([16, 17, 18, 19])]


text:
Q: git fails because of an untracked working tree file I'm not an expert at google. Needless to say, I'm not even sure what this means or how to resolve it?
>> git merge admin_playground
error: Untracked working tree file 'vendor/gems/panda-1.0.0/.gitignore' would be overwritten by merge.
fatal: merging of trees 538b2824765956cc44c42a8ad628e4f4 and d5d4cda68518cd1c81bf70ba8c339fea6 failed

I am trying to perform a git merge and getting this failing statement.

A: It's because .gitignore isn't in your current branch (it's untracked), but it's in the branch you're trying to merge. Add the .gitignore file in question and commit, then try the merge again; or delete the .gitignore file if you don't need it and are happy with the one in the other branch.

A: Note: mipadi (author of the accepted answer) also mentioned this error message in the context of case conflicts between filenames on different branches.
If cleaning the untracked files is a valid option, then the extreme solution is mentioned in this answer (a git clean -f -d would remove all untracked files and directories).
In your case, that could be overkill (or dangerous).
Another original solution:
git checkout -f admin_playground # will overwrite files
git checkout yourBranch # get back where you where when trying the merge
git merge admin_playground

This forced git to go ahead and overwrite the files.
  I assume you could have used the '-f' option with merge also, but switching to the other branch and then back fixed the issue and I was able to merge without any trouble the next time.

Note: there is actually no '-f' option on git merge.

A: Try running below commands :
git add *

git stash

git pull


text:
Q: Compiz-like effects in Gnome shell? In Gnome-shell we do not have compiz any more? In KDE4 we have the native desktop effects, I would like to know if the Gnome-shell we will need yet of compiz.

A: Gnome is quoted as saying "'Because the GNOME Shell project wanted "tighter integration" between the panel and window manager than cooperating with the Compiz project would allow, this could actually be true. This mailing list post has more information.'" that statement was made in response to "I can't use Compiz with GNOME Shell!"
Most likely Compiz will be phased out of Gnome Desktops.
It might be best to see how well Compiz works with KDE, LXDE, IceWM, and XFCE.

A: Compiz compositing capability will be replaced by Clutter, which will be integrated into the next generation of Metacity window manager, called Mutter. This means you won't need Compiz.  Since Mutter is closely integrated, you cannot replace Mutter with Compiz.

GNOME shell uses compositing and is
  integrated with Mutter, a compositing
  window manager for X11. Mutter is the
  next generation of the Metacity window
  manager which uses the Clutter toolkit
  for compositing.
GNOME Shell has received some
  controversy in the free software
  community because the planned tight
  integration with Mutter will mean that
  users of GNOME Shell will not be able
  to switch to an alternative window
  manager without breaking their
  desktop. In particular, users will no
  longer be able to use Compiz while
  GNOME Shell is running.[2]. Discussion
  between the developers of Compiz and
  GNOME has failed to resolve the issue.
  However, it will still be possible for
  users to run the GNOME desktop
  environment without GNOME Shell and
  still use whatever window manager they
  choose.

http://en.wikipedia.org/wiki/GNOME_Shell

A: Compiz works well with Xfce and KDE however the latest KWin effects have better integration into KDE 4.6 Plasmoids.  Compiz-Fusion was meant to be a transitionary package for DEs to use in developing their own native effects.

A: No
compiz is not supported in gnome-shell , gnome-shell uses mutter instead of compiz


text:
Q: What happens when a browser does not support SNI A seemingly simple question, but valid nonetheless.
What exactly happens when a browser which does not support SNI attempts to visit a site configured to force SSL via SNI.
Thanks

A: It will probably connect to the default SSL virtual host. In other words, the same site you'd see if you connect using the IP: https://1.2.3.4/

A: It won't be able to load the website, that's for sure.  Which is why no large sites will move to SNI-hosted HTTPS sites anytime soon.  IE6 and IE7 in XP appear to be the largest old browsers that don't support SNI.
If you can get a hold of a non-SNI supporting browsers, you can see what happens by going to https://alice.sni.velox.ch/
It also appears to matter which server software you are using.  With Apache, browsers without SNI support will just get the first configured website (and a hostname mismatch warning probably).

A: That depends on how your web server reacts when receiving a HTTPS request without SNI. (If you want to test it, you can simulate a non-SNI browser with openssl. Basic HTTP protocol knowledge required.)
With IIS 10, the following happens:

*

*If there is a "default SSL site" (a site bound to port 443 without a host name) configured, the non-SNI client will see:

*

*the certificate of the default (wrong) SSL site (usually resulting in a certificate warning, unless you configured your default SSL site certificate to include SANs for all sites hosted at your IP address) and

*the content of the requested (correct) site (after the user dismissed the certificate warning).

This makes perfect sense:

*

*The SSL handshake happens before the HTTP request can be transmitted. Thus, without SNI support from the browser, the server has no option but to return the default SSL site certificate.

*After the SSL connection has been established (using the "wrong" certificate), the server receives the HTTP request, reads the requested host name via the Host: header and returns the correct content.

*If there is no "default SSL site" configured, the connection will be closed.
(Source: Just tested it with an old Windows XP IE8 virtual machine.)

A: I just tested it using IE 4.0 running on Windows NT 4 Workstation.  My website, hosted at http://www.nosupportlinuxhosting.com/, loads perfectly.  I'm not sure if their hosting meets the criteria above, but their "Limiations" page suggests that is the case.  I'm a bit surprised the page loaded.


text:
Q: Laplace's equation after change of variables
Show that if $u(r, \theta)$ is dependent on $r$ alone, Laplace's
  equation becomes $$u_{rr} + \frac{1}{r}u_r=0.$$

My first reaction is to replace $r=x$ and $\theta=y$, but obviously it does not work. Then I recall $x=r\cos \theta$ and $y=r\sin \theta$. Then I obtain the following: $$v(r, \theta) = u(r\cos \theta, r\sin \theta).$$
Then I start to differentiate it, but what is $u_r$ and $u_{rr}$? Can anyone give me some hints to move on?

A: The Laplace operator in $2$D is
$$\nabla^2 \equiv \frac{\partial^2}{\partial x^2} + \frac{\partial^2}{\partial y^2}$$
To express this in polar-coordinates we need to express the $x,y$-derivatives in terms of $r,\theta$-derivatives. Since $(x,y)=(r\cos\theta,r\sin\theta)$ the chain-rule gives us that
$$\frac{\partial}{\partial x} = \frac{\partial r}{\partial x} \frac{\partial}{\partial r} + \frac{\partial \theta}{\partial x}\frac{\partial}{\partial \theta}$$
Now $r=\sqrt{x^2+y^2} \implies \frac{\partial r}{\partial x} = \frac{x}{r} = \cos\theta$ and $\frac{y}{x}=\tan(\theta) \implies \frac{\partial\theta}{\partial x} = -\frac{y}{r^2} = -\frac{\sin\theta}{r}$ so
$$\frac{\partial}{\partial x} = \cos\theta \frac{\partial}{\partial r}  - \frac{\sin\theta}{r}\frac{\partial}{\partial \theta}$$
From this we can compute $\frac{\partial^2}{\partial x^2}$ as follows
$$\frac{\partial^2}{\partial x^2} = \left[\cos\theta \frac{\partial}{\partial r}  - \frac{\sin\theta}{r}\frac{\partial}{\partial \theta}\right]\left[\cos\theta \frac{\partial}{\partial r}  - \frac{\sin\theta}{r}\frac{\partial}{\partial \theta}\right]$$
To compute this (see this answer for more info) remember that a derivative acts on everything that is behind it so for example
$$\cos\theta \frac{\partial}{\partial r} \cos\theta \frac{\partial}{\partial r} \equiv \cos\theta \frac{\partial}{\partial r}\left(\cos\theta \frac{\partial}{\partial r}\right)$$
You also need to do the same thing as above to compute $\frac{\partial^2}{\partial y^2}$. Once you have done this you will have an expression for  $\nabla^2 $ in polar coordinates. Then you can let this act on $u$, i.e. consider $\nabla^2 u$, and use that $u = u(r)$ so $\frac{\partial u}{\partial \theta} = 0$ to get the desired result.

A: You have
$$ \frac{\partial f}{\partial r} = \frac{\partial x}{\partial r} \frac{\partial f}{\partial x} + \frac{\partial y}{\partial r} \frac{\partial f}{\partial y} = f_x \cos{\theta} + f_y \sin{\theta}. $$
Then differentiating again (and using that $\partial \theta/\partial r=0$),
$$ f_{rr} = \cos{\theta} (\cos{\theta} \partial_x+\sin{\theta} \partial_y)f_x + \sin{\theta} (\cos{\theta} \partial_x+\sin{\theta} \partial_y)f_y \\
f_{xx} \cos^2{\theta} + f_{yy}\sin^2{\theta} + 2f_{xy} \sin{\theta}\cos{\theta} $$
Similarly, we can show that
$$ \partial_{\theta} = -r\sin{\theta} \partial_x + r\cos{\theta}\partial_y, $$
so
$$ f_{\theta\theta} = \partial_{\theta}(-r\sin{\theta} f_x + r\cos{\theta}f_y) = r^2[(-\cos{\theta} f_x -\sin{\theta} f_y ) +\sin^2{\theta} f_{xx}+\cos^2{\theta}f_yy -2\sin{\theta}\cos{\theta} f_{xy}] $$
Thus
$$ f_{rr} + \frac{1}{r^2}f_{\theta\theta} + \cos{\theta} f_x + \sin{\theta} f_y = f_{xx}+f_{yy} $$
But the last terms on the left are just $r^{-1}\partial_r $, so
$$ f_{xx} + f_{yy} = f_{rr}+\frac{1}{r}f_r + \frac{1}{r^2}f_{\theta\theta}. $$

That's a bit of a mess, though. Instead, we can use $u(r,\theta)=f(r)$, and $r=\sqrt{x^2+y^2}$, and compute
$$ \Delta f = \frac{\partial^2}{\partial x^2} f(\sqrt{x^2+y^2})+\frac{\partial^2}{\partial y^2} f(\sqrt{x^2+y^2}) \\
= \frac{\partial}{\partial x} \left( \frac{x}{\sqrt{x^2+y^2}} f'(\sqrt{x^2+y^2}) \right) + \frac{\partial}{\partial y} \left( \frac{y}{\sqrt{x^2+y^2}} f'(\sqrt{x^2+y^2}) \right) \\
= \frac{y^2}{(x^2+y^2)^{3/2}}f'(\sqrt{x^2+y^2}) + \left(\frac{x}{\sqrt{x^2+y^2}}\right)^2 f''(\sqrt{x^2+y^2}) + \frac{x^2}{(x^2+y^2)^{3/2}}f'(\sqrt{x^2+y^2}) + \left(\frac{y}{\sqrt{x^2+y^2}}\right)^2 f''(\sqrt{x^2+y^2}) \\
= f''(\sqrt{x^2+y^2})+\frac{1}{\sqrt{x^2+y^2}}f'(\sqrt{x^2+y^2}) = u_{rr}+\frac{1}{r}u_r. $$


text:
Q: XML Bulk Load issue into SQL Server I am trying to use XML Bulk Load (sql server 2008).  I am almost there, but I think my schema file is wrong.  The error I am getting is this:

Here is what I have:
SQL Table Structure:

Schema File:
<?xml version="1.0" ?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data"
    xmlns:dt="urn:schemas-microsoft-com:xml:datatypes"
    xmlns:sql="urn:schemas-microsoft-com:xml-sql" >

    <ElementType name="weight" dt:type="string" />
    <ElementType name="fwd" dt:type="float" />
    <ElementType name="aft" dt:type="float" />

    <ElementType name="CGs" sql:is-constant="1">
        <element type="gross" />
    </ElementType>

    <ElementType name="gross"  sql:relation="tblCGLimits">
      <element type="weight"  sql:field="weight" />
      <element type="fwd" sql:field="fwd" />
      <element type="aft"        sql:field="aft" />
   </ElementType>
</Schema>

XML File:
<?xml version="1.0" encoding="utf-8" ?>
<CGs>
    <gross weight="8000">
        <fwd>196.5</fwd>
        <aft>208.88162</aft>
    </gross>
    <gross weight="8001">
        <fwd>196.495</fwd>
        <aft>208.8825148</aft>
    </gross>
    <gross weight="8002">
        <fwd>196.49</fwd>
        <aft>208.8834096</aft>
    </gross>
</CGs>

And the VBScript I am using:
Set objBL = CreateObject("SQLXMLBulkLoad.SQLXMLBulkLoad")
objBL.ConnectionString = "provider=SQLOLEDB.1;data source=MyServer;database=MyDB;uid=MyUser;pwd=MyPW"
objBL.ErrorLogFile = "c:\XMLError.log"
objBL.Execute "c:\Schema.xml", "c:\CGLimits.xml"
Set objBL = Nothing

A: Your XSD file specifies that weight values are elements, rather than attributes, which would look as follows:
<?xml version="1.0" encoding="utf-8" ?>
<CGs>
    <gross>
        <weight>8000</weight>
        <fwd>196.5</fwd>
        <aft>208.88162</aft>
    </gross>
    <gross>
        <weight>8001</weight>
        <fwd>196.495</fwd>
        <aft>208.8825148</aft>
    </gross>
    <gross>
        <weight>8002</weight>
        <fwd>196.49</fwd>
        <aft>208.8834096</aft>
    </gross>
</CGs>

To correct this, change
<element type="weight" sql:field="weight"/>

to
<attribute type="weight" sql:field="weight"/>

in the XSD file.


text:
Q: Motion of an object near a force field I'm trying to simulate the motion of an object near a force field, given an initial velocity $v_0$.
I couldn't find anything that fits what I'm trying to achieve.
I have a point of mass $m_1$ in the origin of the Cartesian plane (0.0, 0.0) (blue in the image).
The coordinate system is the Cartesian one.
The position of $M_1$ shouldn't change.
I figured out this:

*

*The attraction force between the blue body and the red body is F defined like this: $F =G{m_0m_1}/{r^2}$ by Newton's theory.

*The resulting position of the red body should be the sum of $v_0$ and a vector representing the component of the motion directed towards the center.

But I didn't get further than that. How could I calculate the position of the body at time t?

A: For the body with mass $m_0$, split the velocity and acceleration vectors into its perpendicular components. Let the body be at position $(a,b)$ initially. The displacement due to the initial velocity will be $s=vt$. Do the same  for the acceleration using the formula $s=\frac 12at^2$. Add them together for the x-components and y-components and you arrive at your answer.


text:
Q: Сортировка по параметрам из другой таблицы Здравствуйте. Подскажите пожалуйста, можно ли сделать следующее?
Хотел отсортировать статьи по рейтингу, рейтинг насчитывается через этот модуль https://github.com/hauntd/yii2-vote.
Что-то вроде этого, только views это поле из таблицы со статьями, а мне нужно
сортировать по полю из таблицы с рейтингом:
<?php usort($competition, function ($a, $b) {
            return ($b['views'] - $a['views']);
        }) ?>
        <?php foreach ($competition as $item1): ?>
        ...

Связал модели, попробовал вот так:
<?php usort($competition, function ($a, $b) {
            return ($b->aggregate['rating'] - $a->aggregate['rating']);
        }) ?>
        <?php foreach ($competition as $item1): ?>
        ...

Порядок статей меняется, но не так как хотелось бы.


text: Q: Wifi not working after I changed MAC address I wanted to change my ip, so I looked online and saw that you can do that by changing the MAC address, so I changed my MAC address directly, but no matter what I do, none of the changes work and my wifi is still there, but there is no connection to the internet and the connection starts to work again only if I reset the address. I rebooted and restarted(this is as far as my capabilities go) the router, it still does not work. My router is a TP-link and my connection type is dynamic if that matters. How do I get this to work and change my ip.I do not know that much about this, so sorry if I did not give enough information, please ask if you need anything. Thank You in advance.


text:
Q: How to make sure [BsonId] field is named like property name in the database instead of `_id` I'm using Mongo for some denormalized data storage, however found a minor annoyance that I would like to get fixed.
Since my objects have their own RegistrationCode which are unique for every record I would like to use that as ID so I just add [BsonId]. So far so good.
However when I look into actual database I see that this field is not RegistrationCode but instead _id. How can I make sure that it's named correctly in the actual database?
public class Company
{
    [BsonId]
    public string RegistrationCode { get; set; } // Why is this named "_id" in the database?
    // ...
}

A: As Evk stated, every document in a Mongo collection must have an _id field - see MongoDB Reference Glossary.
Essentially what you are doing when adding the '[BsonId]' attibute is assigning the value of your RegistrationCode property to the _id field.
By convention you should add an Id field to your POCO class which will still allow you to still be able to query/insert/update/remove/index on your unique RegistrationCode field.
public class Company
{
    public ObjectId Id { get; set; } //By convention

    public string RegistrationCode { get; set; }
    // ...
}


text: Q: Is there any way to perform MLE on a 1d gaussian mixture model comprised of two gaussians? The MLE of the mean of a single gaussian distribution is the mean of the sample. But is there any way to do this when you have two gaussians such as in the figure attached? I know how to estimate the two means with a methods like least squares regression. But I am wondering could a MLE of this type of distribution exist? Is there a proof showing that is does not?


text:
Q: Enqueue script with version number not working I am trying to enqueue a script for a custom plugin and I want to include a version number for cache busting. However, the ?ver= query is not being appended to the script name in the html and therefore cache busting is failing.
The php code:
wp_enqueue_script('bundle', plugins_url('dist/client.js', __FILE__), array(), '20190520430', true);

And the html tag that is being produced (with identifiable info removed):
<script type="text/javascript" src="https://site.url/wp-content/plugins/plugin-name/dist/client.js"></script>

Any help or explanation is appreciated, thanks!

A: You don't strictly need wp_register_script() but it is considered a best practice to use it as it allows other developers to programmatically work with the order and list of scripts being included.
Regarding your issue, your code looks correct. Be sure to call it inside the wp_enqueue_scripts action (but I don't think that's influencing the behavior you are seeing).
If I had to guess, and I kind of do, I would guess that there is some other plugin or system configuration that is stripping the query string as part of a caching mechanism. The thought is that query string parameters, if they are present, can keep some proxy servers, and possibly browsers, from caching the resource. There are even some plugins such as Ratify and possibly W3 Total Cache that will strip query string parameters from resources for you, intentionally. The way to test if another plugin is interfering is by disabling them and seeing if anything changes.
If you are using a caching server or CDN, they may also be stripping the query string (but seems unlikely). Cloudflare offers a maintenance mode that allows you to briefly disable the CDN while you test things.
HTH and please let me know how you get on.


text:
Q: Unable to connect to Amazon RDS from EC2 Wordpress during setup I have setup an RDS MySQL instance on Amazon RDS which will be accessed through EC2. When I enter my database details to WordPress setup and proceed with the installation, it returns with an error saying "Error establishing a database connection".
I thought this is because the Security Group of the database instance is not allowing the inbound traffic for EC2. Then I added the Security Group of my EC2 instance to the inbound rules of RDS instance's Security Group. Still the same issue.
Allowing All traffic also did not resolve the problem.
Although I found some people have encountered with similar problems, I could not resolve this problem with the suggested answers.

I appreciate if someone could help me to resolve this.

A: This could result from so many reasons. It would be hard to give you a short answer.
First of all, did you check that the username and password are correct? Can you connect from elsewhere?
Secondly, security groups are not always enough. There could be a problem with network routing or ACLs. In order to verify that there is indeed connectivity between your EC2 instance and the RDS instance, run this from the EC2 instance:
nc -vz RDS_HOSTNAME 5432
Where RDS_HOSTNAME is the RDS instance endpoint. You should receive a message that the connection was successful.


text:
Q: Python - Append dictionary in dictionary I am new to python and have a perhaps basic question.. I have a dictionary, and want to add another dictionary to a key in the first dictionary :)
So currently the dictionary look like this:
{
    "name": "custname",
    "slug": "custslug",
    "group": "1"
}

And I need it to "append" another dictionary to an existing.. I guess It is a nested dictionary I need.
{
    "name": "custname",
    "slug": "custslug",
    "custom_fields": {
        "NavID": "10023"
    },
    "group": "1",
 }

A: In case you want a nested dictionary use the below method -
d1 = {"name": "custname","slug": "custslug","group": "1"}
d1["custom_fields"] = {"NavID": "10023"}
print(d1)

This will give the output you wanted.
Or if you want to merge two dictionaries and update the values, you may use the update method.
d1 = {"name": "custname","slug": "custslug","group": "1"}
d2 = {"NavID": "10023"}
d1.update(d2)

The output here will be
{"name": "custname","slug": "custslug","group": "1","NavID": "10023"}

A: dict = {
    "name": "custname",
    "slug": "custslug",
    "group": "1"
}

another_dict = {
        "NavID": "10023"
    }

dict['Custom_fields'] = another_dict

A: Great question! This will work.
d1 = {
    "name": "custname",
    "slug": "custslug",
    "group": "1"
}
d2 = {"NavID": "10023"}
d1["custom_fields"] = d2

A: If you want to append or merge 2 dictionaries, you can use update method.
Below is how you can do it :
d1 = {
    "name": "custname",
    "slug": "custslug",
    "group": "1"
}
d2 = {"custom_fields": {"NavID": "10023"}}

d1.update(d2)

print(d1)

OUTPUT :
>>> {'group': '1', 'name': 'custname', 'custom_fields': {'NavID': '10023'}, 'slug': 'custslug'}


text:
Q: how to reopen an activity on clicking/tapping notification I am opening an activity on clicking notification. But if that activity is already open then I want to reopen that activity. From reopen I mean that; close that activity and open it again in order to display updated data. For doing that I am adding this line of code to intent of the notification:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

But the problem is that when I click/tap notification, whole the application is closed instead of finishing only that activity. So please help.

A: you can check if the Activity is already opened. I done this way
public static boolean FLAG=false;

in onCreate make it true
@Override
protected void onCreate(Bundle savedInstanceState) {
FLAG=true;
.
.
}

now you can check this variable's value in the Notification class.
boolean isOpen=YourActivty.FLAG;
if(isOpen){
 //just clear the notification with adding the notification's data in the activity if you are sending to any listview or so.
 //for adding the data to listview you need to make the `ArrayList`(i assume) and make a method in the adapter that will notify the adapter.
}else{
//call the Activity
}

A: Use this
         notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notificationIntent = null;
        notificationIntent = new Intent(context, SplashScreen.class);

        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TASK);

        PendingIntent intent = PendingIntent.getActivity(context, 0,
                notificationIntent, 0);
        RemoteViews notiview = new RemoteViews(getPackageName(),
                R.layout.notification_layout);
        final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                context).setSmallIcon(small_icon)
        // .setContentTitle(title)
                .setAutoCancel(true)
                // .setStyle(
                // new NotificationCompat.BigTextStyle().bigText(message))
                .setDefaults(
                        Notification.DEFAULT_SOUND
                                | Notification.DEFAULT_VIBRATE)
                // .setContentText(message).setNumber(noticount);
                .setContent(notiview);
        notiview.setTextViewText(R.id.noti_msgcount, "" + noticount);
        notiview.setTextViewText(R.id.noti_msgtxt, msgOld);

        mBuilder.setContentIntent(intent);


text:
Q: Open File on Notification click downloaded using Retrofit2 I am downloading a PDF using retrofit webservice. And then I am showing a self created notification to show that the file has been downloaded. But I am not able to understand how to show or open the file when clicked on notification.
Here's my notification call:
RestClient.webServices()
        .downloadFile(id)
        .enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                if (response.isSuccessful()) {

                    boolean writtenToDisk = writeResponseBodyToDisk(response.body());

                    Log.e(TAG, "file download was a success? " + writtenToDisk);

                    if (writtenToDisk) {

                        showToast("Invoice downloaded successfully");
                        showDownloadNotification();

                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });

Here's the writeResponseBodyToDisk() function:
private boolean writeResponseBodyToDisk(ResponseBody body) {
    try {
        // todo change the file location/name according to your needs
        File futureStudioIconFile = new File(Environment.getExternalStorageDirectory() + File.separator + "/bill.pdf");

        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            byte[] fileReader = new byte[4096];

            long fileSize = body.contentLength();
            long fileSizeDownloaded = 0;

            inputStream = body.byteStream();
            outputStream = new FileOutputStream(futureStudioIconFile);

            while (true) {
                int read = inputStream.read(fileReader);

                if (read == -1) {
                    break;
                }

                outputStream.write(fileReader, 0, read);

                fileSizeDownloaded += read;

                // Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
            }

            outputStream.flush();

            return true;
        } catch (IOException e) {
            return false;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }

            if (outputStream != null) {
                outputStream.close();
            }
        }
    } catch (IOException e) {
        return false;
    }
}

And here's the showDownloadNotification() function:
void showDownloadNotification() {
    try {
        Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + File.separator + "/invoice.pdf");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(selectedUri, "resource/folder");
        //            startActivity(intent);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_logo_winds)
                .setContentTitle("Invoice downloaded")
                .setContentText("")
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

        // notificationId is a unique int for each notification that you must define
        notificationManager.notify(1, builder.build());

    } catch (Exception e) {
        Log.e(TAG, "Notification " + e.toString());
    }
}

So when I tap on the created notification, nothing happens, and when I uncomment startActivity (intent); it crashes by saying cannot find activity for intent.
How do I open the file I have downloaded by clicking the notification I have created for it?

A: It seems like you're passing wrong data type to intent on showDownloadNotification() method. Here is how you can open PDF:
Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + File.separator + "/invoice.pdf");

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "application/pdf"); // here we set correct type for PDF
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);


text:
Q: 'Identity theorem' for Meromorphic functions If $f_1,f_2$ are meromorphic functions in $D$ and there exists a sequence of pairwise distinct points $z_n \in D$ such that $z_n \to z_o \in D$ and $f_1(z_n)=f_2(z_n),$ then $f_{1} \equiv f_2$ on $D.$
Appreciate if someone could advise me on how to prove this. Thank you.

A: Since $f_1$ and $f_2$ are meromorphic in $D$ then there exists a holomorphic functions $a,b,c,d$ in $D$ such that $f_1=a/b$ and $f_2=c/d$, now let $h=ad-bc$ it is a holomorphic function on $D$, and for all $z_k$ we have $h(z_k)=0$, by continuity of $h$ and the fact that $z_k\to z_0$, we get $h(z_0)=0$, hence $h=0$, so that $a/b=c/d$ i.e $f_1=f_2$.


text:
Q: Is it possible to use the touch ripple effect of MUI on a div? I have read different answers of similar questions, but they are all old and don't seem to work in the latest version of MUI.
I need to apply the touch ripple effect on a div, but I can't use a button or a ButtonBase element because there is another button inside it.
Thanks in advance for the reply.

A: You Can Use ButtonBase API
With ButtonBase API you can pass component prop as div or any component you want
For Eg.
import { ButtonBase, Typography } from "@mui/material";

const App = () => {
  return (
    <ButtonBase component="div">
        <Typography fontSize="1.2rem">Hello, I'm a div with MUI Ripple Effect!</Typography>
    </ButtonBase>
  )
}

export default App;

A: Yes, you can use TouchRipple to emulate the ripple effect. This component is undocumented, but you can see how it's used in the ButtonBase and learn to use it yourself.
First, you need to pass a ref to TouchRipple and call ref.current.start(e) or ref.current.stop(e) when you want to start or stop the effect respectively.
e is the event object. When you call start(e), it needs the mouse or touch position (from mousedown or touchstart event) to know where to start the ripple effect (Source). You can override this behavior by setting center props to true, which makes the ripple effect always start at the middle.
Below is the minimum working example to get you started:
function App() {
  const rippleRef = React.useRef(null);
  const onRippleStart = (e) => {
    rippleRef.current.start(e);
  };
  const onRippleStop = (e) => {
    rippleRef.current.stop(e);
  };

  return (
    <div
      onMouseDown={onRippleStart}
      onMouseUp={onRippleStop}
      style={{
        display: "inline-block",
        padding: 8,
        position: "relative",
        border: "black solid 1px"
      }}
    >
      Button
      <TouchRipple ref={rippleRef} center={false} />
    </div>
  );
}

Live Demo


text:
Q: Pegar cor dinamicamente Criei algumas cores no arquivo colors.xml
<color name="colorBackground1">#5c6bc0</color>
<color name="colorBackground2">#1e88e5  </color>
<color name="colorBackground3">#00838F</color>

No adapter quero setar a cor dinamicamente
val cor = "R.color." + cores.get(position)
val colorValue = getColor(context, cor)
vh.item.setBackgroundColor(colorValue)

A variável corescontém somente o nome da cor, exemplo colorBackground1.
Mas na linha
val colorValue = getColor(context, cor)
ele não aceita a variável cor, esperando um int mas tá passando uma string e não achei um jeito de converter. A string sai com o nome certo, R.color.colorBackground1. Como resolver?

A: Ou você pode transformar val cor = "R.color." + cores.get(position) em inteiro.
ou o ideal é utilizar o seguinte método:
getResources().getIdentifier("name", "resource", "package");

No seu caso ficaria então:
val cor = getResources().getIdentifier(cores.get(position), "color", getPackageName());

Espero ter ajudado.


text:
Q: $wp_query when new WP_Query I'm trying something but I have an issue with WP_Query.
I've an Hook on the_post in order to add some variation on the query.
add_filter('the_posts', 'query_variation');

function query_variation($posts, $query = false) {
    if (is_search())
    {
    // Do stuff
    }
}

It's working well when I'm searching on the site. But, I know creating an ajax search like that :
function ajax_search_123( ){
     $search_keyword = esc_attr($_REQUEST['query']);
     $args = array(
            's'                     => $search_keyword),
            'post_type'             => 'product',
            'posts_per_page'        => 3,
        );
        $products_query = new WP_Query( $args );
        // Do stuff with $product_query
}

But when I instanciate WP_Query with $args, is_search() doesn't return true so I'm entering on the if...
What Can I do ?
Thank you for your help

A: You are slightly confusing $wp_query global variable with WP_Query class/objects. $wp_query is an object instance of WP_Query, but not every WP_Query object has anything to do with $wp_query global.
Function version of conditionals, such as is_search(), always act on main global query. You shouldn't use them inside filters, since global state might be one thing and the query you are actually in another.
Inside hooks you should be always making checks on instance of query provided, via its methods. For example $query->is_search().


text:
Q: Decode a column of Base64 strings in Python Situation: I have a column that I'll be extracting from SQL with hundreds of thousands of Base 64 strings that I would like to decode.
One decoded string looks like this:
b'{"a":1,"b":2,"c":3,...}'

Objective:
How can I simply extract the value of the first dictionary. In this case, this would be 1. I would like the results to end up in a numpy array or df.
I found the following code to help me decode one string but unsure how to use it for every row in a column.
import base64
coded_string = '''value to decode'''
base64.b64decode(coded_string)

A: Assuming your snippet is well-formed Python (although, this seems more likely to be JSON), you can use literal_eval:
from ast import literal_eval
from base64 import b64decode
from pprint import pprint

binary = b64decode(some_str)

lib = literal_eval(binary.decode('utf8'))
pprint(lib)


text:
Q: PHP - How to Pass Value from Previous Textbox to Newly Created Row on the Same Page? I'm planning to use a form to register new Teacher (see image bellow). A teacher can assign to different classes to teach different subjects.
Is it possible to pass the value from textbox in Row1_Column1 (AAAA) to textbox in Row2_Column1 when a new row is created by clicking on button (+)?
I don't want the user to take pain in typing the same values in some of the textboxes - the values will be the same. Only [Subject Taught] and [Class Taught] columns might be different, so i want to leave those empty for every new row created.
Sample Form
My code is as follows:

<button class="btn btn-success" type="button" name="viewStaff">

    View List</button>

   <form method="post" id="insert_form">

       Name (Initials)
       Username
       Password
       Role
       Class Assigned
       Subject Taught
       Class Taught
       <button type="button" name="add" class="btn btn-success btn-sm add"></button>

      <button class="btn btn-info" type="submit" name="submit">

       Submit
      </button>

      <button class="btn" type="reset">

       Reset
      </button>

   </form>

And staff_insert.php
<?php
//staff_insert.php
$connect = mysqli_connect("localhost", "root", "", "studentsdatabase");
if(isset($_POST["initials"]))
{
 $initials = $_POST["initials"];
 $user_name = $_POST["user_name"];
 $password = $_POST["password"];
 $role = $_POST["role"];
 $class_assigned = $_POST["class_assigned"];
 $subject_taught = $_POST["subject_taught"];
 $class_taught = $_POST["class_taught"];

 $query = '';
 for($count = 0; $count<count($initials); $count++)
 {
  $initials_clean = mysqli_real_escape_string($connect, $initials[$count]);
  $user_name_clean = mysqli_real_escape_string($connect, $user_name[$count]);
  $password_clean = mysqli_real_escape_string($connect, $password[$count]);
  $role_clean = mysqli_real_escape_string($connect, $role[$count]);
  $class_assigned_clean = mysqli_real_escape_string($connect, $class_assigned[$count]);
  $subject_taught_clean = mysqli_real_escape_string($connect, $subject_taught[$count]);
  $class_taught_clean = mysqli_real_escape_string($connect, $class_taught[$count]);

  if($initials_clean != '' && $user_name_clean != '' && $password_clean != '' && $role_clean != '' && $class_assigned_clean != '' && $subject_taught_clean != '' && $class_taught_clean != '')
  {
   $query .= '
   INSERT INTO tbl_users(fullname, username, password, role, class_assigned, subject_taught, class_taught)
   VALUES("'.$initials_clean.'", "'.$user_name_clean.'", "'.$password_clean.'", "'.$role_clean.'", "'.$class_assigned_clean.'", "'.$subject_taught_clean.'", "'.$class_taught_clean.'");
   ';
  }
 }
 if($query != '')
 {
  if(mysqli_multi_query($connect, $query))
  {
   echo 'ok';
  }
 }
}
?>

Please if you know of a better way, kindly help.
Thanks.
EDIT:
New Image Please check this image
How can I manipulate the above jquery to make the Name, Username, Password, Role and Class Assigned appear for each row the remaining inputs Subject Taught and Class Taught?
Please help.

A: Some fields are not populated as no server side data can be retrived here. Bu you can see the example for the Role column.
Look for this part in the snippet:
  // Here is were you can do the conditional and copying part
  var last_row_role_sel_val = $('#staff_table tr:last td:nth-child(4) select option:selected').val();
  var last_row_role_sel_html = $('#staff_table tr:last td:nth-child(4) select option:selected').html();
  console.log('last_row_role_sel_val',last_row_role_sel_val);
  console.log('last_row_role_sel_html',last_row_role_sel_html);

And the replacement part
if (last_row_role_sel_val!=undefined && last_row_role_sel_val!="") {
  html += '<select name="role[]" class="form-control role"><option value="'+last_row_role_sel_val+'">'+last_row_role_sel_html+'</option></select>	';
} else {
...

//$( "b" ).clone().prependTo( "p" );
$(document).ready(function(){

 $(document).on('click', '.add', function(){
  var html = '';
  html += '
';

  // Here is were you can do the conditional and copying part
  var last_5_rows_sel_val = [];
  var last_5_rows_sel_html = [];
  for (var i=1;i<=5;i++) {
    if (i>=4) {
    last_5_rows_sel_val.push($('#staff_table tr:last td:nth-child('+i+') select option:selected').val());
      last_5_rows_sel_html.push($('#staff_table tr:last td:nth-child('+i+') select option:selected').html());
    } else {
      last_5_rows_sel_val.push($('#staff_table tr:last td:nth-child('+i+') input').val());
      last_5_rows_sel_html.push('');
    }
  }
  if (last_5_rows_sel_val[0]!=undefined && last_5_rows_sel_val[0]!="") {

  html += '<input type="text" name="initials[]" class="form-control initials" value="'+last_5_rows_sel_val[0]+'" />	';
  html += '<input type="text" name="user_name[]" class="form-control user_name" value="'+last_5_rows_sel_val[1]+'" />	';
  html += '<input type="password" name="password[]" class="form-control password" value="'+last_5_rows_sel_val[2]+'" />	';
  html += '<select name="role[]" class="form-control role"><option value="'+last_5_rows_sel_val[3]+'">'+last_5_rows_sel_html[3]+'</option></select>	';
  html += '<select name="class_assigned[]" class="form-control class_assigned"><option value="'+last_5_rows_sel_val[4]+'">'+last_5_rows_sel_html[4]+'</option></select>	';

} else {

  html += '<input type="text" name="initials[]" class="form-control initials" />	';
  html += '<input type="text" name="user_name[]" class="form-control user_name" />	';
  html += '<input type="password" name="password[]" class="form-control password" />	';
  html += '<select name="role[]" class="form-control role"><option value="">Select...</option><option value="admin">Admin</option><option value="form_master">Form Master</option><option value="staff">Staff</option></select>	';
  html += '<select name="class_assigned[]" class="form-control class_assigned"><option value="">Select...</option><?php echo fill_class_box($conn); ?></select>	';
}
  html += '<select name="subject_taught[]" class="form-control subject_taught"><option value="">Select...</option><?php echo fill_subject_box($conn); ?></select>	';
  html += '<select name="class_taught[]" class="form-control class_taught"><option value="">Select...</option><?php echo fill_class_box($conn); ?></select>	';
  html += '<button type="button" name="remove" class="btn btn-danger btn-sm remove">-</button>
';

  $('#staff_table').append(html);
 });

 $(document).on('click', '.remove', function(){
  $(this).closest('tr').remove();
 });

$('#insert_form').on('submit', function(event){
  event.preventDefault();
  var error = '';
  $('.initials').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error = "
Please enter the required information
";
    return false;
   }
   count = count + 1;
  });

  $('.user_name').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error = "
Please enter the required information
";
    return false;
   }
   count = count + 1;
  });

  $('.password').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error = "
Please enter the required information
";
    return false;
   }
   count = count + 1;
  });

  $('.role').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error = "
Please enter the required information
";
    return false;
   }
   count = count + 1;
  });

  $('.class_assigned').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
       return true;
   }
   count = count + 1;
  });

  $('.subject_taught').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error = "
Please enter the required information
";
    return false;
   }
   count = count + 1;
  });

  $('.class_taught').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error = "
Please enter the required information
";
    return false;
   }
   count = count + 1;
  });

  var form_data = $(this).serialize();
  if(error == '')
  {
   $.ajax({
    url:"staff_insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     if(data == 'ok')
     {
      $('#staff_table').find("tr:gt(0)").remove();
      $('#error').html('
Staff Details Saved
');
     }
    }
   });
  }
  else
  {
   $('#error').html('
'+error+'
');
  }
 });

});
table,th,tr,td,div,p {
border: 1px solid #888;
}

<button class="btn btn-success" type="button" name="viewStaff">

    View List</button>

   <form method="post" id="insert_form">

       Name (Initials)
       Username
       Password
       Role
       Class Assigned
       Subject Taught
       Class Taught
       <button type="button" name="add" class="btn btn-success btn-sm add">+</button>

      <button class="btn btn-info" type="submit" name="submit">

       Submit
      </button>

      <button class="btn" type="reset">

       Reset
      </button>

   </form>

UPDATED!!


text:
Q: Dividing a picture into N number of equal parts I need a formula (logic) to divide a fixed area in 'N' number of equal parts. For example I am having a picture/image of 800*800, So now I need to slice it into 10 number of equal parts and what will be the dimension of the sliced portions. Can you help me in that?

A: Since you don't specify that they need to be square, or impose any other restrictions other than "ten equal parts", why don't you just slice the image into (for your example) ten 80*800 images (or 800*80 if you want to slice in the other dimension)?
That will give ten equal sized chunks without having to worry about whether you have optimal squares and so forth. If the use case is just slicing into equal parts (such as an image coming down the wires from the net, where ten small requests may seem more responsive than one big one), this would work okay.
In other words, something like:
def getSlice (sliceNumber, sliceCount, image):
    xpos   = 0
    xsize  = image.xsize

    ypos   =  sliceNumber      * image.ysize / sliceCount
    ypos2  = (sliceNumber + 1) * image.ysize / sliceCount

    if sliceNumber < sliceCount - 1:
        ysize = ypos2 - ypos1
    else:
        ysize = image.ysize - ypos1 - 1

    return image.subImage (xpos, ypos, xsize, ysize)

When calling it with five slices, you would get:
+-------------------------------------------+
|           getSlice (0, 5, image)          |
+-------------------------------------------+
|           getSlice (1, 5, image)          |
+-------------------------------------------+
|           getSlice (2, 5, image)          |
+-------------------------------------------+
|           getSlice (3, 5, image)          |
+-------------------------------------------+
|           getSlice (4, 5, image)          |
+-------------------------------------------+

The ypos/ypos2 stuff and the if statement at the end is to cater for situations where the divisions may not give perfectly aligned numbers. They should guarantee that you won't duplicate or miss any lines from the image.

A: First, you should find for the N all such pairs of k,l that k*l=N. K - num of rows, l - num of columns.
Second, you should choose of these pairs the one you want.
After that you should cut the image.
What step makes a problem?
If you want, for example, the most square parts, check all l's  starting from sqrt(N) down by one. Get the first divider you find. Thus you can combine steps 1 and 2.


text:
Q: Где взять базу слов для Русско-Английского словаря? Пишу простой Англо-Русский словарь на Python 3. Пользователь вводит слово - выводит его аналог на английском (как же иначе). Так вот, просмотр перевода слова осуществляется через .txt файл где слова записаны(example):
дом
house
дом
цветок
flower
цветок

и так далее.
Чтобы словарь был хоть на что-либо способен нужно 2000+ слов. Может уже существует скрипт для заполнения файла таким образом, используя ресурсы какого-нибудь сайта?
Я новичок, только начинаю постигать  ООП, поэтому написать этот скрипт сам не в состоянии, а вбивать 6000 слов вручную слишком затратно по времени.

A: По этому запросу: русский английский словарь txt -разговорник, нашёлся "Англо-Русский Словарь" Мюллера 1995-го года, не форматирован, обычный текст txt, 120 тыс. строк, 10 МБ:
http://www.alleng.ru/d/engl/engl150.htm
Более продвинутый запрос google translate download dictionary txt дал более плодотворные результаты, по ссылке ниже куча словарей в формате XML. Первый попавшийся русско-английский содержит 1 млн 458 тыс строк и весит 107 МБ:
http://translateclient.com/download_dictionary/
К сожалению, компактного и простого для новичка txt/csv не нашёл, видимо, мало кому такие вещи требуются. Но если Вам действительно важна эта задача, то справитесь с парсингом одного из этих. Выбирайте и пользуйтесь на здоровье!

A: Погуглил 2000 слов на английском языке и нашел сайт. Осмотрел его HTML содержимое и решил попарсить.
Главная проблема была в том, что у сайта структура данных очень неудобная – нет атрибутов-маячков (class, id), по которым удобно выцеплять данные, поэтому понадобилось изучить структуру и найти точные данные (например, наличие определенного атрибута), чтобы отделить нужные данные.
Пример:
import requests
from bs4 import BeautifulSoup

rs = requests.get('http://www.7english.ru/dictionary.php?id=2000&letter=all')
root = BeautifulSoup(rs.content, 'html.parser')

en_ru_items = []

for tr in root.select('tr[onmouseover]'):
    td_list = [td.text.strip() for td in tr.select('td')]

    # Количество ячеек в таблице со словами -- 9
    if len(td_list) != 9 or not td_list[1] or not td_list[5]:
        continue

    en = td_list[1]

    # Русские слова могут быть перечислены через запятую 'ты, вы',
    # а нам достаточно одного слова
    # 'ты, вы' -> 'ты'
    ru = td_list[5].split(', ')[0]

    en_ru_items.append((en, ru))

print(len(en_ru_items), en_ru_items)
# 2000 [('a', 'неопределенный артикль'), ('abili... , ('zero', 'ноль')]

Думаю, вывести этот список в файл автор уже сам сможет


text:
Q: How would i make this a decryption instead of an encryption? Wanna know how to get this from being a encryption code and using the same code to create a decryption.
I know it means that I have to reverse some of the instruction and re-order it but I can't figure out which ones need to be reordered and which ones don't.
(edit) Heres the full function to make things a bit clearer. Very new to stack overflow so apologies for any confusions.
//---------------------------------------------------------------------------------------------------------------
//----------------- ENCRYPTION ROUTINES -------------------------------------------------------------------------

void decrypt_chars (int length, char EKey)
{
  char temp_char;                       // Character temporary store

  for (int i = 0; i < length; i++)      // Encrypt characters one at a time
  {
    temp_char = OChars[i];              // Get the next char from Original Chars array

    __asm
    {
      push   eax                        // stores the "eax" register out onto the stack
      push   ecx                        // stores the "ecx" register out onto the stack
      push   edx                        // stores the "edx" register out onto the stack
                                        //
      movzx  ecx, temp_char             // zeroise "ecx" register and move values in "temp_char" varaible to "ecx" register
      lea    eax, EKey                  // copies address of values contained within the EKey varaible and moves it into "eax"register
                                        //
      push eax                          //
      push ecx                          //
                                        //
      call   decryptX                   // runs the function called "decryptX"
      mov    temp_char, dl              // move values in "dl" register into "temp_char" variable
                                        //
      add esp, 8                        //
      pop    edx                        // removes the "edx" register from the stack
      pop    ecx                        // removes the "ecx" register from the stack
      pop    eax                        // removes the "eax" register from the stack
    }                                   //
    EChars[i] = temp_char;              // store encrypted char in the Encrypted Chars array
  }
  return;

  __asm
  {

  decryptX:
        push  ebp            // stores the pointer onto the stack

            mov   ebp, esp       // move values in "esp" register into "ebp" register
            mov   eax, [ebp + 12]// take value from the stack that is 8 bits above
                                 // from the pointer a putting it in the "eax" register
            mov   ecx, [ebp + 8] // take value from the stack that is 8 bits above
                                 // from the pointer a putting it on ecx

            push  eax            // stores the Ekey address onto the stack
            xchg  eax, ecx       // puts temp_char's value into the EKey address register and Ekey address into temp_char register

            ror al, 1
            ror al, 1
            dec eax
            neg al

            mov   ebx, eax       // move temp_char value into "ebx" register
            pop   eax            // removes temp_char from the stack
            push  ebx            // stores temp_char value onto the stack
            pop   edx            // removes "edx" register value from the stack
            movzx ecx, [eax]     // zeroise "ecx" register and move the address stored in "eax" register to "ecx" register
            ror   cl, 1          // rotate "cl" register value in bytes to the right by 1
            xor cl, 0x96         // Exclusive OR (or XOR) the byte values within "cl" register with hex value 0x96 in binary
            push  ecx            // stores the Ekey address onto the stack
            and   cl, 0x7        // AND the byte values within "cl" register with hex value 0x7 in binary

            X:                       // Position X:

        add dl, 2            // add 2 to value within dl
            sub cl, 1            // subtract 1 from value within cl
            jg X                   // jump to "X" position
            pop   ecx            // removes "ecx" register value from the stack
            xor   ecx, edx       // exclusive OR (or XOR) the byte values within "ecx" register with the byte values within "edx" register
            mov[eax], cl         // move "cl" register value into the address stored in "eax" register.
            pop   ebp            // returning ebp back to the orginal value
            ret                  // return, end of encryptX function
  }

  //--- End of Assembly code
}
//*** end of encrypt_chars function
//--------------------------------------------------------------------------------------------------------------

A: If this is a homework assignment, then it's actually quite a tricky one. (Though I may have overlooked a simple approach.)
Let's focus on the effect this code has on memory. For simplicity I will assume you are not interested in the effect this code has on registers, though I cannot be sure within seeing the code calling this function.
encryptL:
    push  eax
    ...                ; ignoring this code because its effect on eax is undone by the following pop
    pop   eax
    ...                ; code not affecting eax
    movzx ecx, [eax]
    ...                ; code not affecting eax
    mov   [eax], cl
    ret

So in goes an address (eax). The byte at this address is put into cl, and after some transformations, cl is put back at the same address.
We need to figure out what those transformations are, and invert those.
    ror   cl, 1
    xor   cl, 0x96
    push  ecx
    ...                ; ignoring this code because its effect on ecx is undone by the following pop
    pop   ecx
    xor   ecx, edx

So a rotate and two xors are applied to cl.
Xor is an involution, so we do not have to change those two instructions.
The inverse of rol is of course ror, though that is not entirely true. The effect on the carry flag cannot be inverted, but in this case that effect is ignored, so we are good.
But what about all the code we ignored? On close inspection, you'll notice it is only there to calculate the value of edx that is used in xor ecx,edx.
Unfortunately, the original (unencrypted) value of [eax] is involved in that calculation.
When decrypting, the original value becomes the final value, i.e. the result of xor ecx,edx.
We seem to have a chicken-and-egg problem. How to perform the calculation when it depends on the result of that same calculation?
It should be clear that the effect of [eax] on the calculation of edx, is either 1 out of only 8 possible cases, due to this statement:
    and   cl, 0x7

That means we can use a loop to try all different possibilities, until we found one where the result of the calculation matches the value we found in [eax].
That loop will be very similar to this loop found in the encryptor:
X:
    add   dl, 2
    sub   cl, 1
    jg    X

However, the exit condition of the loop will be different.
    mov   bl,0        ; using bl as a loop counter (similar to cl in original loop)
X:
    inc   bl
    add   dl,2        ; same as in the original loop
    mov   cl,[eax]    ; fetch encrypted byte from memory
    xor   ecx,edx     ; try transforming cl with the current value of dl
    xor   ebx,ecx     ; compare cl with the loop counter (bl)
    and   bl,7        ; only compare the 3 least significant bits
    jg    X           ; if not zero, try again with the next possible value of dl

Since xor is commutative and associative, we can rewrite this code.
Instead of incrementing bl until it matches cl, we will decrement cl until its (partially) transformed value is zero (modulo 8).
    mov   cl,[eax]    ; fetch encrypted byte from memory
X:
    add   dl,2        ; same as in the original loop
    sub   cl,1        ; same as in the original loop
    push  ecx
    xor   ecx,edx     ; transform cl with the current value of dl
    and   cl,7        ; only consider the 3 least significant bits
    pop   ecx         ; restore cl (without clobbering flags)
    jg    X           ; if equal, then we found the right starting point

As for the rest of the code, that can stay as it is. It is mainly the initial part of the calculation of edx, before [eax] becomes involved.
Here is the complete solution:
encryptL:
    push  eax
    xchg  eax, ecx
    neg   al
    inc   eax
    rol   al, 1
    rol   al, 1
    mov   ebx, eax
    pop   eax
    push  ebx
    pop   edx

    movzx ecx, [eax]
    push  ecx
X:
    add   dl,2
    sub   cl,1
    push  ecx
    xor   ecx,edx
    and   cl,7
    pop   ecx
    jg    X

    pop   ecx
    xor   ecx,edx
    xor   cl,0x96
    rol   cl,1
    mov   [eax],cl
    ret

Disclaimer: I did not test it, so it's quite likely it will not work. I will leave the debugging up to you.


text:
Q: Coding a GTK+ application without window manager? I want to code sth. that basically works like TiVo.  Switch it on, you only see the menu or an output, so no underlying OS or anything else is directly visible to the user.
So I want to use Linux as base. Can you suggest a good base distribution?

*

*Can I code a frontend without having a window-manager up and running?

*If yes, is that possible with java-gnome or what language/gui-framework combination would you suggest?

*If no, what's the minimal window manager that can handle fancy menus, etc?

*What does it take to create video-overlays over a HD-stream?  Are there some libraries I should take a look at?

Thanks

A: *

*Yes. If you only have one window you don't need a window manager. Using X you can start some application and set it's position and size from the commandline (making it fullscreen). You might want to take a look at xinit if this is what you want. This is likely the easiest why to get something working. But another option is skip X and use DirectFB. If you want to display several windows, on the other hand, you need some sort of window manager to manage them.

*As long as you run X there is no problem using java-gnome as framework if that's what you are confortable with. I guess you didn't mean to run the stock gnome applications, but code everything visible to the user yourself.

*This very much depends on what you mean with fancy menus. If you mean transparancy and such you need a composite manager (if you don't just render everything yourself inside your application window). I'm not sure about this but I think you can run a composite manager independent from a window manager if you find that suitable. Again, this is if you run X. Using DirectFB transparency and such are done in a more simple way.

*If you intend to write your own media player you should take a look at GStreamer. It can stream, decode and display video and also add video-overlays (among other things) and is extremly easy to use.

A: Minimalistic tiling window manages like Awesome, Ratpoison or XMonad may be useful as a base, otherwise you'll have to manage focus and window sizing yourself. It is normally fairly easy to make these invisible to the user.

A: *

*Absolutely.

*I wouldn't count on Gnome itself working without a window manager. Other than that... language doesn't matter.

*Window managers only do window management. Menus and the like are the job of the widget toolkit. Anyways, Metacity.

*... This one I have no clue about.


text:
Q: Probability distribution for number of heads obtained in a biased coin I'm a home-schooled high school student struggling with the following question. Any insights/tips on how to solve this would be highly appreciated.
A biased coin is tossed three times. The probability distribution for H, the number of heads obtained, is shown in the following table.
h          0       1       2       3
P(H = h)   0.512   0.384   0.096   a

1) Find the probability of obtaining a head each time the coin is tossed.
2) Give another discrete random variable that is related to these trials, and calculate the probability that its value is greater than the value of H.

A: If we say that the probability of getting heads is $p$, then the probability of getting $3$ heads in $3$ tosses is $p^3$.  You aren't told what the probability of getting $3$ heads is, but since all the probabilities must add up to 1 you can get it by $a = 1-(.512+.384+.096) = .008$.  Setting $p^3 = .008$, solving for $p$ gives $p=.2$.
I'm not exactly sure what they're going for in part 2), but one thing you could look at would be the number of tails.  There are more tails than heads if there are $0$ or $1$ heads, so the probability is $.512+.384=.896$.

A: Let us restate what we know.
We toss the coin three times.
In each toss the outcome may either be heads or tails. As there are only two outcomes, we have a Bernoulli trial.
We are using the same coin. This means that even if the coin is biased, the bias remains the same throughout all the tosses. Thus the probability of getting heads remains constant throughout.
From these facts we can recognize that the number of heads will follow a binomial distribution
$$
b(k; n, p) = {n \choose k} p^{k}(1-p)^{n-k}
$$
Now we know that if this equation should coincide the the table given, we require that
$$
b(0; 3, p) = {3 \choose 0} p^{0}(1-p)^{3} = (1-p)^3 = 1 -3p + 3p^2 -p^3 = 0.512
$$
Now this cubic equation is not that easy to solve, so we can instead see if we can leverage some extra info from our table. We also require that
$$
b(1; 3, p) = {3 \choose 1} p^{1}(1-p)^{2} = 3p(1-p)^2 = 3p -6p^2 + 3p^3 = 0.384
$$
Now we are getting somewhere! Using the two equations we can eliminate the 3rd order term in the equation
$$
3\cdot b(0; 3, p) + b(1; 3, p) = 3 -9p + 9p^2 -3p^3 + 3p -6p^2 + 3p^3 = 3\cdot 0.512 + 0.384 \\
b(0; 3, p) + b(1; 3, p) = 3 -6p + 3p^2 = 1.92
$$
This quadratic equation we can solve! The possible solutions are
$$
p = 0.2 \quad \text{or} \quad p = 1.8
$$
Now $p$ is supposed to be a probability so the latter doesn't really make sense. We discard this solution and assume that $p=0.2$. Let use the final entry of the table to confirm that we are right
$$
{3 \choose 2} (0.2)^{2}(0.8)^{1} = 0.096
$$
TADA! As our calculation corresponds with the table, this must be the correct value of $p$. We are finally ready to compute $a$ as
$$
a = b(3, 3, 0.2) = {3 \choose 3} (0.2)^{3}(0.8)^{0} = 0.2^3 = 0.008
$$


text:
Q: Get the txt file into the push() method? Please help me!
    I have Script:
var titles =[];
titles.push('I want file txt in here');

I can not get the txt file into the titles.push, so I need some help!
function readTextFile(){
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "text.txt", false);
  rawFile.onreadystatechange = function (){
    if(rawFile.readyState === 4){
      if(rawFile.status === 200 || rawFile.status == 0){
        var allText = rawFile.responseText;
        console.log(allText);
      }
    }
  }
  rawFile.send(null);
}

A: I do not have a text file ready to show so I used what you should be reading about XMLHttpRequest.responseText you do not want to use onreadystatechange but maybe xhr.onload I left some console.log()s in the code so you can play around with it.

var titles =[];
titles.push('I want file txt in here');

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText', true);
xhr.responseType = 'text';

xhr.onload = function () {
    if (xhr.readyState === xhr.DONE) {
        if (xhr.status === 200) {
            //console.log(xhr.response);
            //console.log(xhr.responseText);

            // not needed but do not want to push the entire page
            // to titles so lets find just one title
            var parser = new DOMParser();
            var doc = parser.parseFromString(xhr.responseText, "text/html");
            var title = doc.querySelector('h1');
            // console.log(title);
            titles.push(title);
            logTitles();
        }
    }
};

xhr.send(null);

function logTitles() {
    console.log(titles);
};


text:
Q: How to create a .docx file in a Sharepoint library programmatically and supply the content through a Sharepoint list I have a Sharepoint list which is getting updated very often. I'm retrieving the list items using client object model. I want to write the list contents into a word file(.docx) and save it in a document library on the same Sharepoint site.

A: There is a nice article on MSDN for your requirement. Please check it here. And this blog article.


text:
Q: How to add and remove single propertys to ngStyle? How can I add properties to an existing ngStyle-Attribute without setting it completely new?
For now I found a workaround by setting [style.float] but in future I want to do something like my posted code.
I tried it with:
obj.style = obj.style + { float: 'right' }

I searched with multiple Search Phrases. More and more I assume its not possible.

obj.style: { color: 'red' }

< .... [ngStyle]="obj.style"...>

public ButtonClickAddFloating(obj) {

// Target: obj.style: { color: 'red', float: 'right' }

}

public ButtonClickRemoveFloating(obj) {

// Target: obj.style: { color: 'red' }

}

A: Use the spread syntax
this.ngStyle = { ...this.ngStyle, fontFamily: 'Roboto' };

Be aware that this syntax DOES NOT remove the previous styles from the objet. If you want to remove it, then either re-assign it, or set the value to undefined.
You can also destructure your object to remove properties :
{ fontFamily, ...rest } = this.ngStyle;
this.ngStyle = rest;

A: You can use object spread syntax or Object.assign()

const obj = {style: {color: 'red'}}
obj.style = {...obj.style, float: 'right' }
obj.style = Object.assign({}, obj.style, {color: 'blue'})
console.log(obj)

Anyway this probably wont carry on the styles added outside the scope of ngStyle AFAIK

A: public objStyle: any = {'background-color': 'red'};

public addFloat(): void {
  this.objStyle = Object.assign({ 'float': 'right' }, this.objStyle);
}

public removeFloat(): void {
  delete this.objStyle['float'];
}

And html:

<p [ngStyle]="objStyle">
  Start editing to see some magic happen :)
</p>
<button (click)="addFloat()">Add float</button>
<button (click)="removeFloat()">Remove float</button>

A: you can use delete to remove property from you object example

 var obj={style:{color:'red', float: 'right'}}

console.log('Before delete',obj)

delete obj.style.float   //remove peroperty here

console.log('after delete',obj)

obj.style['float']='left';  //set float property again here

console.log('Added float property again',obj)


text:
Q: requests.exceptions.ConnectionError: HTTPSConnectionPool(host='', port=2376): Max retries exceeded with url: /v1.24/version - Docker on Windows I already went through link : Ubuntu 16.04 - > ERROR: Couldn't connect to Docker daemon - you might need to run `docker-machine start default`, but it did not solved my issue yet.
I've setup the Docker on windows-10 machine and simply trying to run the code :: https://github.com/sqshq/PiggyMetrics
pc@DESKTOP-NQ639DU MINGW64 ~/Desktop/PiggyMetrix/PiggyMetrics (master)
$ docker --version
Docker version 18.03.0-ce, build 0520e24302

pc@DESKTOP-NQ639DU MINGW64 ~/Desktop/PiggyMetrix/PiggyMetrics (master)
$ docker-compose --version
docker-compose version 1.20.1, build 5d8c71b2

Now, I am running the code from the docker-compose -f docker-compose.yml -f docker-compose.dev.yml up and getting below error:
pc@DESKTOP-NQ639DU MINGW64 ~/Desktop/PiggyMetrix/PiggyMetrics (master)
$ docker-compose -f docker-compose.yml -f docker-compose.dev.yml up
ERROR: Couldn't connect to Docker daemon - you might need to run `docker-machine start default`.

I ran the code in --verbose mode which gave me lot of errors. Any suggestion, how to fixed this?
pc@DESKTOP-NQ639DU MINGW64 ~/Desktop/PiggyMetrix/PiggyMetrics (master)
$ docker-compose --verbose -f docker-compose.yml -f docker-compose.dev.yml up
compose.config.config.find: Using configuration files: .\docker-compose.yml,.\docker-compose.dev.yml
docker.utils.config.find_config_file: Trying paths: ['C:\\Users\\pc\\.docker\\config.json', 'C:\\Users\\pc\\.dockercfg']
docker.utils.config.find_config_file: No config file found
docker.utils.config.find_config_file: Trying paths: ['C:\\Users\\pc\\.docker\\config.json', 'C:\\Users\\pc\\.dockercfg']
docker.utils.config.find_config_file: No config file found
urllib3.connectionpool._new_conn: Starting new HTTPS connection (1): 192.168.99.100
Traceback (most recent call last):
  File "site-packages\urllib3\connection.py", line 141, in _new_conn
  File "site-packages\urllib3\util\connection.py", line 83, in create_connection
  File "site-packages\urllib3\util\connection.py", line 73, in create_connection
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "site-packages\urllib3\connectionpool.py", line 600, in urlopen
  File "site-packages\urllib3\connectionpool.py", line 345, in _make_request
  File "site-packages\urllib3\connectionpool.py", line 844, in _validate_conn
  File "site-packages\urllib3\connection.py", line 284, in connect
  File "site-packages\urllib3\connection.py", line 150, in _new_conn
urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x000001E471029978>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "site-packages\requests\adapters.py", line 440, in send
  File "site-packages\urllib3\connectionpool.py", line 649, in urlopen
  File "site-packages\urllib3\util\retry.py", line 388, in increment
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='192.168.99.100', port=2376): Max retries exceeded with url: /v1.24/version (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x000001E471029978>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "docker-compose", line 6, in <module>
  File "compose\cli\main.py", line 71, in main
  File "compose\cli\main.py", line 124, in perform_command
  File "compose\cli\command.py", line 41, in project_from_options
  File "compose\cli\command.py", line 121, in get_project
  File "compose\cli\command.py", line 95, in get_client
  File "site-packages\docker\api\daemon.py", line 172, in version
  File "site-packages\docker\utils\decorators.py", line 46, in inner
  File "site-packages\docker\api\client.py", line 194, in _get
  File "site-packages\requests\sessions.py", line 521, in get
  File "site-packages\requests\sessions.py", line 508, in request
  File "site-packages\requests\sessions.py", line 618, in send
  File "site-packages\requests\adapters.py", line 508, in send
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='192.168.99.100', port=2376): Max retries exceeded with url: /v1.24/version (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x000001E471029978>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',))
[6968] Failed to execute script docker-compose

Another ::
pc@DESKTOP-NQ639DU MINGW64 ~/Desktop/PiggyMetrix/PiggyMetrics (master)
$ docker images
error during connect: Get https://192.168.99.100:2376/v1.37/images/json: dial tcp 192.168.99.100:2376: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

Now, I am getting below error:
Error setting up host only network on machine start: C:\Program Files\Oracle\VirtualBox\VBoxManage.exe modifyvm default --nic2 hostonly --nictype2 82540EM --nicpromisc2 deny --hostonlyadapter2 VirtualBox Host-Only Ethernet Adapter #2 --cableconnected2 on failed:
VBoxManage.exe: error: Code E_FAIL (0x80004005) - Unspecified error (extended info not available)
VBoxManage.exe: error: Context: "LockMachine(a->session, LockType_Write)" at line 525 of file VBoxManageModifyVM.cpp
Looks like something went wrong in step ´Checking status on default´... Press any key to continue...


text:
Q: Visualize data with heatmap like a cell I'm looking for an algorithm or method, that can visualize/create nice diagram from data. The data has size and quality properties (and there are some categorys). I found out that treemaps/heatmaps are good for that. But I need an extreme solution. Something like a cell.
I have a good example:
https://www.destatis.de/Voronoi/PriceKaleidoscope.svg
Is it possible to generate diagrams like that (with changing data)? Is there an algorithm for that? Where should I look for more information? Is there a program that does something similar to that?

A: What you want is called a vornonoi treemap. Check out the links on this other stackoverflow post and this paper from SoftVis 2005.

A: You can make that kind of map via d3.js http://d3js.org/ ,and there is a treemap example  http://mbostock.github.com/d3/talk/20111018/treemap.html .


text:
Q: alerting textbox through javascript very simple question! i was wondering how to use javascript to alert something in my textbox...not sure what i'm doing now is not working. heres the function
function alertNow(comment){
alert(comment);
}

now here is the textbox
<input type = 'text' name = 'txt_comment'>
<button onClick = alertNow(txt_comment.value) value = "Submit Comment"></button>

sure this is doable, i did it before but i just forgot some syntax prob. any ideas? thanks!

A: You are missing quotations. Also use the ID instead of name.
<input type = 'text' name = 'txt_comment' id='txt_comment'>
<button onClick = 'alertNow(txt_comment.value)' value = "Submit Comment"></button>

Also better to use, document.getElementById like below
 <button onClick = 'alertNow(document.getElementById("txt_comment").value)' value = "Submit Comment"></button>

A: <input type="text" id="testTextarea">
<input type="submit" value="Test" onClick="alert(document.getElementById('testTextarea').value);" />

A: function alertNow() {
 var a = document.getElementById("txt_comment").value;
 alert (a);
}

<input type = 'text' name = 'txt_comment' id="txt_comment">
<button onClick = "alertNow()" value= "Submit Comment"></button>

A: here is the code to complete your task...
// js code ...
function alertNow(){
   alert(document.getElementById('txt_comment').value);
   return false;
}

// html code ....
<form name="form_1" id="form_1" method="post">
     <input type = 'text' id='txt_comment' name = 'txt_comment'>
     <input type="button" onClick = "return alertNow();" value = "Submit Comment"/>
</form>

A: Use the ID instead of name.
function alertText() {
 alert(document.getElementById('txt_comment').value);
}
<input type = 'text' name = 'txt_comment' id="txt_comment">
<button onClick = "alertText()" value= "Submit Comment"></button>


text:
Q: Setting Tesseract options in R version Does anyone know how to change Tesseract options in R? According to the manual you should be able to supply a list of keywords and values. If trying to set the option 'preserve_interword_spaces=1'. Doesn't stick though.
After setting the parameter and running 'tesseract_params()' preserve_interword_spaces is still set to 0, the default value.


text:
Q: Simple proof of existence of hyperbolic triangles I've studied the hyperbolic plane by analytically building up the hyperboloid model, the Klein—Beltrami disc, the Poincaré disc, and the half-plane model from scratch. Now I'd like to prove that, given $\alpha,\beta,\gamma>0$ with $\alpha+\beta+\gamma<\pi$, there exists a hyperbolic triangle with angles $\alpha$, $\beta$ and $\gamma$.
Is there an easy proof of this fact? I mean a proof that only starts from the basic Riemannian structure of the models: the knowledge what the geodesics are, an expression for the distance, the fact that some models are conformal. (Of course, I have found proofs in literature, but they tend to refer a lot to other results, requiring e.g. an extensive theory of trigonometry.)

A: In the disc model take two lines $L_1,L_2$ emanating from the center $0$, and forming an angle $\alpha$ berween them. Now, consider the point $x_t\in L_1$ ad distance $t$ from $0$ and the line $L_3(t)$ emanating from $x_t$ and forming an angle $\beta$ with $L_1$. Let $y_t=L_3(t)\cap L_2$. Now, $y_t$ can be a single point or the empty set. If $y_t$ is a point, you get a triangle with angles $\alpha,\beta,\gamma(t)$.
You can check that $\gamma(t)$ varies continuously on $t$ and that
1) as $t\to 0$, $y_t$ is a point and the sum $\alpha+\beta+\gamma(t)\to\pi$
2) There is the first time $T$ such that $L_3(t)\cap L_2$ is empty.
As $t\to T$ you have $\gamma(t)\to 0$.
Given $\gamma<\pi-\alpha-\beta$, by means of the intermediate value theorem you see that there is $t$ so that $\gamma(t)=\gamma$

A: Yes you can
Assuming the curvature to be $ \sqrt{-1 } $ the length of the side c is
$$ c = \operatorname{arcosh} \left( \frac{\cos \alpha \cos \beta  + \cos \gamma }{\sin \alpha \sin \beta} \right) $$
(found the formula in "the foundations of geometry and the non euclidean plane" by Martin corollary 32.16 )
so you can even construct your triangle :)
edit : corection of formula
The lenght of the sides are:
$$ a = \operatorname{arcosh} \left( \frac{\cos \beta \cos \gamma  + \cos \alpha }{\sin \beta \sin \gamma} \right) $$
$$ b = \operatorname{arcosh} \left( \frac{\cos \alpha \cos \gamma  + \cos \beta }{\sin \alpha \sin \gamma} \right) $$$$ c = \operatorname{arcosh} \left( \frac{\cos \alpha \cos \beta  + \cos \gamma }{\sin \alpha \sin \beta} \right) $$
then you can make the triangle (all sides and angles are known, what more do you need?)


text:
Q: Sonar throws "failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.6:sonar" in jenkins I have integrated Sonarqube with my Jenkins project as a post build activity. While running the build I'm getting "failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.6:sonar (default-cli)" error.
If I run "mvn sonar:sonar" via command prompt, The build is getting succeeded.
Has anyone faced this issue or can help me out with this.
[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.6:sonar (default-cli) on project XXXXXXX: Execution default-cli of goal org.codehaus.mojo:sonar-maven-plugin:2.6:sonar failed: An API incompatibility was encountered while executing org.codehaus.mojo:sonar-maven-plugin:2.6:sonar: java.lang.UnsupportedClassVersionError: org/sonar/api/utils/SonarException : Unsupported major.minor version 51.0

[ERROR] -----------------------------------------------------

[ERROR] realm =    plugin>org.codehaus.mojo:sonar-maven-plugin:2.6

[ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy

[ERROR] urls[0] = file:/C:/Program%20Files%20(x86)/Jenkins/maven-repositories
/1/org/codehaus/mojo/sonar-maven-plugin/2.6/sonar-maven-plugin-2.6.jar

[ERROR] urls[1] = file:/C:/Program%20Files%20(x86)/Jenkins/maven-repositories/1/org/apache/maven/shared/maven-dependency-tree/2.1/maven-dependency-tree-2.1.jar

[ERROR] urls[2] = file:/C:/Program%20Files%20(x86)/Jenkins/maven-repositories/1/backport-util-concurrent/backport-util-concurrent/3.1/backport-util-concurrent-3.1.jar

[ERROR] urls[3] = file:/C:/Program%20Files%20(x86)/Jenkins/maven-repositories/1/org/codehaus/plexus/plexus-interpolation/1.11/plexus-interpolation-1.11.jar

[ERROR] urls[4] = file:/C:/Program%20Files%20(x86)/Jenkins/maven-repositories/1/org/codehaus/plexus/plexus-component-annotations/1.5.5/plexus-component-annotations-1.5.5.jar

[ERROR] urls[5] = file:/C:/Program%20Files%20(x86)/Jenkins/maven-repositories/1/org/eclipse/aether/aether-util/0.9.0.M2/aether-util-0.9.0.M2.jar

[ERROR] urls[6] = file:/C:/Program%20Files%20(x86)/Jenkins/maven-repositories/1/org/sonatype/plexus/plexus-sec-dispatcher/1.4/plexus-sec-dispatcher-1.4.jar

[ERROR] urls[7] = file:/C:/Program%20Files%20(x86)/Jenkins/maven-repositories/1/org/codehaus/plexus/plexus-utils/1.5.5/plexus-utils-1.5.5.jar

[ERROR] urls[8] = file:/C:/Program%20Files%20(x86)/Jenkins/maven-repositories/1/org/sonatype/plexus/plexus-cipher/1.4/plexus-cipher-1.4.jar

[ERROR] urls[9] = file:/C:/Program%20Files%20(x86)/Jenkins/maven-repositories/1/org/codehaus/sonar/runner/sonar-runner-api/2.4/sonar-runner-api-2.4.jar

[ERROR] urls[10] = file:/C:/Program%20Files%20(x86)/Jenkins/maven-repositories/1/commons-lang/commons-lang/2.6/commons-lang-2.6.jar

[ERROR] urls[11] = file:/C:/Program%20Files%20(x86)/Jenkins/maven-repositories/1/com/google/guava/guava/10.0.1/guava-10.0.1.jar

[ERROR] urls[12] = file:/C:/Program%20Files%20(x86)/Jenkins/maven-repositories/1/com/google/code/findbugs/jsr305/2.0.3/jsr305-2.0.3.jar

[ERROR] Number of foreign imports: 1

[ERROR] import: Entry[import  from realm ClassRealm[project>com.XXXX.etl:XXXX:0.0.1-SNAPSHOT, parent: ClassRealm[maven.api, parent: null]]]

[ERROR]

[ERROR] -----------------------------------------------------

[ERROR] -> [Help 1]