text:
Q: Anyonic braiding statistics from density matrix renormalization group (DMRG) simulations How does the ground state energy of the system change when we braid two anyons? Can the braiding of anyons be simulated with a computational method such as the density matrix renormalization group, and if so, could someone please give me some references? I've tried looking around, but I haven't been able to find anything.
EDIT:
I am specifically referring to the following slides, specifically around slide 56 or so, where he talks about DMRG and the quantum Hall Hamiltonian:
http://www.phys.virginia.edu/Announcements/Seminars/Slides/S2678.pdf
If, as Slaviks states below, that the ground state doesn't change, how can we learn about braiding statistics from DMRG?

A: In these modern DMRG algorithms for topological phases, braiding statistics is rarely computed directly. The reason is that it is not clear how to trap a particular anyon in the bulk, and to get braiding statistics requires a careful calculation of adiabatic non-Abelian Berry phase which is often very computationally demanding. Instead, one calculates modular transformations on cylinders (to be more precise, the Dehn twist) by measuring the so-called momentum polarization of the Schmit states. It contains a lot of useful information about the topological order. The latter part of the slides explained these ideas.

A: Yes tensor network algorithms have been developed to describe braiding of anyons, Abelian and non-Abelian. The networks are constructed from tensors that explicitly conserve topological charge and the braiding, fusion, and recoupling data are taken as input to the algorithms.
This reference:
https://arxiv.org/abs/1311.0967
describes how to use the Time Evolved Block Decimation (TEBD) algorithm with anyonic Matrix Product States to compute ground states and dynamics of braiding anyons.
This reference:
https://arxiv.org/abs/1505.00100
shows how to compute ground states of braiding anyons using DMRG.


text:
Q: Dynamic navigation in django I want to build a dynamic navigation menu that will fill in automatically based on the database, and will be on every page. For example, I have a Genre model. In this model there is a field called parent. If this is null, it is a top-level genre. Otherwise it holds the id of other genre, and is a subgenre of this genre. It looks like this:
class Genre(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)
    parent = models.ForeignKey('self', null=True, blank=True)

def __str__(self):
    return self.name

So I have a CSS dropdown menu and I want to populate it so it goes like this:
Genre -> List of top-level genres. Then for each of these, another drop-down menu of the subgenres of that genre. If that makes sense.
But I have no idea how to implement this in django. I have a context processor, but this just lists all genres as one flat drop-down currently (and I have to remember to add it for every view). I'm not sure if it would be better to use a custom tag or an inclusion tag, or how to do it for this example.
Thanks.

A: You're talking about creating a hierarchy / tree, which is rather annoying to deal with.
Look into Modified Preorder Tree Traversal, a method for dealing with trees like this.
There's a django app for it!
http://django-mptt.github.com/django-mptt/
I highly recommend using this instead of rolling your own.
Here's a quick tutorial on getting started: so much easier than doing this yourself.
http://komunitasweb.com/2010/09/a-quick-tutorial-on-django-mptt/

Otherwise, if you want to support infinite depth, you will need a recursive function that iterates through a Genre's children. Here's an example from the Satchmo shopping cart. Basically, you'd have to iterate over each top level parent, recursively iterate over its children until there are no more children.
def _recurse_for_children(self, node, only_active=False):
    children = []
    children.append(node)
    for child in node.child.active():
        if child != self:
            if (not only_active) or child.active_products().count() > 0:
                children_list = self._recurse_for_children(child, only_active=only_active)
                children.append(children_list)
    return children

I would highly recommend looking at satchmo's template tag for rendering these trees to get some ideas.
Let me know if you have any questions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Evaluating quadratic residue $(6/p) $ Evaluating quadratic residue $(6/p) $ I want to find for which numbers mod 6 this residue is equal to 1 and for which it's equal to -1. I've tried splitting it into $(3/p)(2/p)$ and expressing it as
 $(-1)^{(5 (p-1))/4} (p/6) $ both methods haven't led to me finding a solution. Is there an easier way?

A: I would simply go with your first method; the second is problematic as $6$ is not prime.
For  $\left( \frac{2}{p} \right)$ use the second supplement law of quadratic reciprocity, to get it is $1$ for $\pm 1 \mod 8$.
For $\left( \frac{3}{p} \right)$ you can use quadratic reciprocity to reduce to $ (-1)^{(p-1)/2}\left( \frac{p}{3} \right)$.
Since $1$ is a quadratic residue $\mod 3$ while $2$ is not.
You get $\left( \frac{p}{3} \right) =1$ for $p \equiv 1 \mod 3$ and $-1$ otherwise.
Now, note that $(-1)^{(p-1)/2}$ is even for $p \equiv 1 \pmod 4$. So, $\left( \frac{3}{p} \right)$ is $1$ for $ p \equiv 1 \pmod{12}$ (as $1 \times 1$) and $ p \equiv 11 \pmod{12}$ as $(-1)(-1)$ and $-1$ for $ p$ congruent to  $5,7 \pmod{12}$.
Now, combine the two and get a condition modulo $24$.

A: For every prime $p\geq 7$ we know that:
$$\left(\frac{-3}{p}\right)=1 \Longleftrightarrow p\equiv 1\pmod{3} $$
$$\left(\frac{-2}{p}\right)=1 \Longleftrightarrow p\equiv 1,3\pmod{8} $$
hence for every prime $p\geq 7$ we have:
$$\left(\frac{6}{p}\right)=1 \Longleftrightarrow p\equiv \pm 1,\pm 5\pmod{24}. $$


text:
Q: Connection Timeout while running app on device from android studio I get this error whenever I try to run app from android studio. I am stuck badly. Any suggestion?
Waiting for device.
Target device: 021eff812391377f
Uploading file
    local path: C:\Users\Optimusprime\AndroidStudioProjects\Info2\app\build\outputs\apk\app-debug.apk
    remote path: /data/local/tmp/manojmm.info
I/O Error: Connection timed out: connect

A: Lot of things that you can do:

*

*Unplug and replug the device from the USB connection.

*Ensure that the debug mode of the phone is on.

*Try killing and restarting the adb with adb kill-server and adb start-server
Source: Android Studio: "Waiting for device." Trying to run app on phone


text:
Q: Kivy/KivyMD Screen takes 10 seconds to load on Android, 3 seconds on Windows We are developing an app with many screens and much kv code, using lazy loading template by Kulothungan on GitHub and it is fine, besides one screen, the calculator. It takes 10 seconds or more to load on Android, and we don't understand why!
Part of code:
# ----- Python Class: -----
class CustomRoundButton(ButtonBehavior, CircularRippleBehavior, CircularElevationBehavior, MDFloatLayout):
    pass

# ----- KV Class: -----

<Calculator>
    name: "calculator"

    MDBoxLayout:
        padding: "35dp"
        spacing: "25dp"
        orientation: "vertical"

        MDLabel:
            id: calclabel
            text: "0"
            halign: "right"
            valign: "center"
            font_style: "H2"
            size_hint_y: .4
            pos_hint_y: .5

        GridLayout:
            cols: 4
            spacing: "15dp"

            CustomRoundButton:
                pos_hint: {"center_x": .5, "center_y": .5}
                radius: lbl.texture_size[0]  + self.height / 2
                md_bg_color: app.theme_cls.accent_color
                size_hint_y: None
                height: self.width
                elevation: 8
                on_release:
                    root.calcformula = ""
                    calclabel.text = "0"

                Label:
                    id: lbl
                    text: "AC"
                    font_size: root.height / 20
                    -text_size: None, None
                    size_hint: None, None
                    size: self.texture_size[0] + dp(50), self.texture_size[0] + dp(50)
                    pos_hint: {"center_x": .5, "center_y": .5}
                    color: 1, 1, 1, 1
...

Here is a link to the whole screen code
Any help would be really appreciated!
Thanks!

A: My app would take 10 seconds to start showing something when I open it. And after searching for a while I realized that the problem was in the images. I was loading images that were around 2000x2000 and the app had to load them before it shows anything on the screen because they were in the kv file. So I removed them from the kv file and did this:
class ItsAnApp(Widget):
    def __init__(self, **args):
        super(ItsAnApp, self).__init__(**args)

    def add_images(self, dt):
        self.add_widget(Image(source='yeah.png', height=height, x=x, y=y))
        self.add_widget(Image(source='ofcourse.jpg', height=height, x=x, y=y))
        self.add_widget(Image(source='surely.yes', height=height, x=x, y=y))
        self.add_widget(Image(source='wowthisisan.oldquestion', height=height, x=x, y=y))
        self.add_widget(Image(source='hmm.jfif', height=height, x=x, y=y))
        self.add_widget(Image(source='it_is_a_thing.qoi', height=height, x=x, y=y)

class SomeApp(App):
    def build(self):
        self.ItsAnApp = ItsAnApp()
        return self.ItsAnApp

    def on_start(self):
        Clock.schedule_once(self.ItsAnApp.add_images)

in the schedule_once function I never tell it how long it should wait for which will make the add_images function run the next frame


text:
Q: Foundation 5 Dropdowns - have link click through AND hover I am using foundation 5 and have implemented a side bar "fly out" categories / sub categories menu using the Dropdowns feature.
This all works as expected however I need the top level category link to click through as well as hover to show the sub categories.  Does anyone know how I would achieve this?

[CategoryName]

 [CategoryName]

I imagine the dropdown feature works in the same way as the top bar and this also does not seem to support having a top level link that clicks through as well as a hover.  Does anyone know why this is as this is pretty standard isn't it?
Many thanks

A: I believe the idea is that on mobile devices it's really quite annoying if you tap a dropdown menu then the page buggers off somewhere else before you can select a sub-option, so it's easier to just not listen for clicks on the parent link.
If you want to re-add the functionality you can do something simple enough such as this fiddle*:
[CategoryName]

$(function() {
    $('[data-follow-click]').on('click', function() {
        location.href = this.href;
    });
});

Obviously this is a very rough example and doesn't fire any more complicated handlers, it just lets href go through, but that works for the OP example.
*Note: the fiddle doesn't follow links to Google - check the console to see when a request is or isn't going through :-)


text:
Q: Which application does the vi command open? When you type vi in the terminal, the following output is shown
~                             VIM - Vi IMproved
~
~                               version 7.3.547
~                           by Bram Moolenaar et al.
~           Modified by pkg-vim-maintainers@lists.alioth.debian.org
~                 Vim is open source and freely distributable
~
~                        Help poor children in Uganda!

So according to this, vi must be launching VIm.
But when you type  vim it gives
aditya@aditya-desktop:~$ vim
The program 'vim' can be found in the following packages:
 * vim
 * vim-gnome
 * vim-tiny
 * vim-athena
 * vim-gtk
 * vim-nox
Try: sudo apt-get install <selected package>

This shows that vim is not installed.
Notably man vi and man vim launch the same man pages.
So what does the vi command actually launch?

A: If you do type vi:
➜  ~  type vi
vi is /usr/bin/vi

You will know where's the binary, now if you do:
➜  ~  ls -l /usr/bin/vi
lrwxrwxrwx. 1 root root 20 jun 22  2013 /usr/bin/vi -> /etc/alternatives/vi

It's provided by the alternative vi, which can be known by:
➜  ~  update-alternatives --display vi
vi - auto mode
  link currently points to /usr/bin/vim.basic
/usr/bin/vim.basic - priority 30
  slave vi.1.gz: /usr/share/man/man1/vim.1.gz
  slave vi.fr.1.gz: /usr/share/man/fr/man1/vim.1.gz
  slave vi.it.1.gz: /usr/share/man/it/man1/vim.1.gz
  slave vi.ja.1.gz: /usr/share/man/ja/man1/vim.1.gz
  slave vi.pl.1.gz: /usr/share/man/pl/man1/vim.1.gz
  slave vi.ru.1.gz: /usr/share/man/ru/man1/vim.1.gz
Current 'best' version is '/usr/bin/vim.basic'.

So, in my case, vi is a symbolic link to the alternative vi which is provided by vim.basic.
You can change which package provided vi if you do sudo update-alternatives --config vi

A: It's similar to @ignis answer, but i reduced the steps.It only works, if the file is a symbolic link to another.You can get the original file path easily, if it has thousands of symlinks in it's path.
symlnk-->symlnk-->symlnk-->symlnk-->symlnk-->symlnk-->symlnk-->symlnk-->symlnk-->symlnk-->symlnk-->symlnk-->symlnk-->symlnk-->symlnk-->symlnk-->symlnk-->.................-->original file
$ which vi
/usr/bin/vi
$ ls -l $(which vi)
lrwxrwxrwx 1 root root 20 Feb 22 20:14 /usr/bin/vi -> /etc/alternatives/vi  # So /usr/bin/vi is an symlink to /etc/alternatives/vi
$ dpkg -S $(readlink -f $(which vi))
vim-tiny: /usr/bin/vim.tiny

So vi belongs to the package vim-tiny.
readlink -f gives you the canonical path of the file(Original file path).

A: It is vim-tiny: "Vi IMproved - enhanced vi editor - compact version".
I did this on 13.10:
user@ubuntu:~$ which vi
/usr/bin/vi
user@ubuntu:~$ which vim
user@ubuntu:~$ ls -l /usr/bin/vi
lrwxrwxrwx 1 root root 20 ago 13  2013 /usr/bin/vi -> /etc/alternatives/vi
user@ubuntu:~$ ls -l /etc/alternatives/vi
lrwxrwxrwx 1 root root 17 dic 20 04:39 /etc/alternatives/vi -> /usr/bin/vim.tiny
user@ubuntu:~$ apt-cache search vim.tiny
vim-common - Vi IMproved - Common files
vim-tiny - Vi IMproved - enhanced vi editor - compact version
user@ubuntu:~$ dpkg --get-selections | grep vim
vim-common                  install
vim-tiny                    install

As you can see, vim is not installed (empty output), vi is a symlink to /etc/alternatives/vi (see alternatives mechanism), which is a symlink to /usr/bin/vim.tiny, which belongs to package vim-tiny.


text:
Q: Create model instance out of Form and add it to other instance In my models.py I have model called Bus. It contains multiple fields, including the field file below:
class Bus(models.Model):
    file = models.OneToOneField('File', on_delete=models.PROTECT, editable=False)

The File model consists of:
class File(models.Model):
    file = models.FileField(
        upload_to=get_filepath,
        max_length=45,
        validators=[
            FileExtensionValidator(allowed_extensions=['pdf', 'jpg', 'png']),
            file_size,
        ]
    )
    original_name = models.CharField(max_length=45)
    extension = models.CharField(max_length=3)

When you want to create a new Bus I need of course a form. That's defined in my forms.py:
class BusForm(forms.ModelForm):
    upload = forms.FileField(max_length=45, required=False,
                            validators=[
                                FileExtensionValidator(allowed_extensions=['pdf', 'jpg', 'png']),
                                file_size,
                            ],)

My problem:
In the save() method of BusForm I have to create a File instance and add it to the Bus instance (file field).
For multiple hours I tried to achieve that. However, I don't get it. If someone could try to help me how the save() method has to look like, that would be great!

A: You can create save method like this
def save(self, commit=False):
    # This will create bus_instance but not save in database
    bus_instance = super(self, BusForm).save(commit=False)

    # create file instance
    file_instance = File.objects.create() # add the required parameters

    # Assign file_instance to file attribute of bus_instance
    bus_instance.file = file_instance

    # Save to database only if user calling save method wants to save in database
    if commit:
        bus_instance.save()

    return bus_instance


text:
Q: excel: color cells of a column if a matching value is found in other column I have two columns, column A and column B. I want to highlight/color those cells in column A who have a match in column B.

A: Add a third column that's doing a vlookup for A values in B.
Then you can have a conditional format depending on the values of C.

A: I figured it out:
Conditional formatting with this formatting rule:
=NOT(ISERROR(MATCH($A1,$B$1:$B$8,0)))
EDIT: BrakNicku is correct, following is enough:
=MATCH($A1,$B$1:$B$8,0)


text:
Q: Querying dynamo db if key exists in java I am new to dynamo db. Given this filter condition on aws UI
student_name - exists

I could filter the rows only if student_name key exists. How do I query the same in java. I am using the following code
 QuerySpec spec = new QuerySpec()
         .withKeyConditionExpression("Exists('student_name'')");
 ItemCollection<ScanOutcome> allRows = myTable.scan(spec);

A: You can use QuerySpec Java class to achieve similar results.
Javadoc
Reference and code example:


text:
Q: VBA copy and past loop I am trying to write a macro that goes into an infinite amount of sheets and copies and pastes a data range from A10:E10, A11:E11 and so on until it hits a blank cell until pastes it into a new tab until it has gone through each sheet and grabbed the data. I have tried to use the code below, but it will only let me paste one cell and if I change the range to more than one it pastes over and leaves out data. Any Help would be greatly appreciated.
Dim sh As Worksheet
Dim wb As Workbook
Dim DestSh As Worksheet
Dim i As Integer

With Application
    .ScreenUpdating = False
    .EnableEvents = False
End With

Set wb = ThisWorkbook
Set DestSh = wb.Sheets("Combined")

' Loop through worksheets that start with the name "20"
i = 4
For Each sh In ActiveWorkbook.Worksheets
If sh.Name = "Data" Then Exit Sub
    sh.Range("E10").Copy

  With DestSh.Range("AF" & i)
    .PasteSpecial xlPasteValues
    .PasteSpecial xlPasteFormats
    Application.CutCopyMode = False

    End With
i = i + 1

Next


text:
Q: Can you add a list of disables dates in given javascript code? i have code its working alright and i have all the functionalities i needed just i want one more functionality its disables dates i have copied this code codepen
here is reference link please edit and share link thanky
https://codepen.io/juan-patrick/pen/GRJWZmP?editors=1111
here is html
       <!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800&display=swap" rel="stylesheet">
        <title>Calendar - UI</title>

                    Pesquisa por data
                    <form class="form-input" id="date-search" onsubmit="return setDate(this)">
                        <input type="date" class="text-field" name="date" id="date" required>
                        <button type="submit" class="btn btn-small" title="Pesquisar"></button>
                    </form>

                    <button class="btn" onclick="prevDay()" title="Dia anterior"> </button>
                    <button class="btn" onclick="resetDate()" title="Dia atual"> Hoje</button>
                    <button class="btn" onclick="nextDay()" title="Próximo dia"> </button>

                        <button class="icon" onclick="prevMonth()" title="Mês anterior"></button>
                        <button class="icon" onclick="nextMonth()" title="Próximo mês"></button>

here is js code
const months = [
"Janeiro",
"Fevereiro",
"Março",
"Abril",
"Maio",
"Junho",
"Julho",
"Agosto",
"Setembro",
"Outubro",
"Novembro",
"Dezembro"
];
    const weekdays = ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"];

    // Váriavel principal
    let date = new Date();

    // Função que retorna a data atual do calendário
    function getCurrentDate(element, asString) {
        if (element) {
            if (asString) {
                return element.textContent = weekdays[date.getDay()] + ', ' + date.getDate() + " de " + months[date.getMonth()] + " de " + date.getFullYear();
            }
            return element.value = date.toISOString().substr(0, 10);
        }
        return date;
    }

    // Função principal que gera o calendário
    function generateCalendar() {

        // Pega um calendário e se já existir o remove
        const calendar = document.getElementById('calendar');
        if (calendar) {
            calendar.remove();
        }

        // Cria a tabela que será armazenada as datas
        const table = document.createElement("table");
        table.id = "calendar";

        // Cria os headers referentes aos dias da semana
        const trHeader = document.createElement('tr');
        trHeader.className = 'weekends';
        weekdays.map(week => {
            const th = document.createElement('th');
            const w = document.createTextNode(week.substring(0, 3));
            th.appendChild(w);
            trHeader.appendChild(th);
        });

        // Adiciona os headers na tabela
        table.appendChild(trHeader);

        //Pega o dia da semana do primeiro dia do mês
        const weekDay = new Date(
            date.getFullYear(),
            date.getMonth(),
            1
        ).getDay();

        //Pega o ultimo dia do mês
        const lastDay = new Date(
            date.getFullYear(),
            date.getMonth() + 1,
            0
        ).getDate();

        let tr = document.createElement("tr");
        let td = '';
        let empty = '';
        let btn = document.createElement('button');
        let week = 0;

        // Se o dia da semana do primeiro dia do mês for maior que 0(primeiro dia da semana);
        while (week < weekDay) {
            td = document.createElement("td");
            empty = document.createTextNode(' ');
            td.appendChild(empty);
            tr.appendChild(td);
            week++;
        }

        // Vai percorrer do 1º até o ultimo dia do mês
        for (let i = 1; i <= lastDay;) {
            // Enquanto o dia da semana for < 7, ele vai adicionar colunas na linha da semana
            while (week < 7) {
                td = document.createElement('td');
                let text = document.createTextNode(i);
                btn = document.createElement('button');
                btn.className = "btn-day";
                btn.addEventListener('click', function () { changeDate(this) });
                week++;

                // Controle para ele parar exatamente no ultimo dia
                if (i <= lastDay) {
                    i++;
                    btn.appendChild(text);
                    td.appendChild(btn)
                } else {
                    text = document.createTextNode(' ');
                    td.appendChild(text);
                }
                tr.appendChild(td);
            }
            // Adiciona a linha na tabela
            table.appendChild(tr);

            // Cria uma nova linha para ser usada
            tr = document.createElement("tr");

            // Reseta o contador de dias da semana
            week = 0;
        }
        // Adiciona a tabela a div que ela deve pertencer
        const content = document.getElementById('table');
        content.appendChild(table);
        changeActive();
        changeHeader(date);
        document.getElementById('date').textContent = date;
        getCurrentDate(document.getElementById("currentDate"), true);
        getCurrentDate(document.getElementById("date"), false);
    }

    // Altera a data atráves do formulário
    function setDate(form) {
        let newDate = new Date(form.date.value);
        date = new Date(newDate.getFullYear(), newDate.getMonth(), newDate.getDate() + 1);
        generateCalendar();
        return false;
    }

    // Método Muda o mês e o ano do topo do calendário
    function changeHeader(dateHeader) {
        const month = document.getElementById("month-header");
        if (month.childNodes[0]) {
            month.removeChild(month.childNodes[0]);
        }
        const headerMonth = document.createElement("h1");
        const textMonth = document.createTextNode(months[dateHeader.getMonth()].substring(0, 3) + " " + dateHeader.getFullYear());
        headerMonth.appendChild(textMonth);
        month.appendChild(headerMonth);
    }

    // Função para mudar a cor do botão do dia que está ativo
    function changeActive() {
        let btnList = document.querySelectorAll('button.active');
        btnList.forEach(btn => {
            btn.classList.remove('active');
        });
        btnList = document.getElementsByClassName('btn-day');
        for (let i = 0; i < btnList.length; i++) {
            const btn = btnList[i];
            if (btn.textContent === (date.getDate()).toString()) {
                btn.classList.add('active');
            }
        }
    }

    // Função que pega a data atual
    function resetDate() {
        date = new Date();
        generateCalendar();
    }

    // Muda a data pelo numero do botão clicado
    function changeDate(button) {
        let newDay = parseInt(button.textContent);
        date = new Date(date.getFullYear(), date.getMonth(), newDay);
        generateCalendar();
    }

    // Funções de avançar e retroceder mês e dia
    function nextMonth() {
        date = new Date(date.getFullYear(), date.getMonth() + 1, 1);
        generateCalendar(date);
    }

    function prevMonth() {
        date = new Date(date.getFullYear(), date.getMonth() - 1, 1);
        generateCalendar(date);
    }

    function prevDay() {
        date = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 1);
        generateCalendar();
    }

    function nextDay() {
        date = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
        generateCalendar();
    }

    document.onload = generateCalendar(date);

here is css code
* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

body {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: "Open Sans", sans-serif;
    font-size: 14px;
    color: #000000;
    -webkit-font-smoothing: antialiased;
}

input,
button,
textarea {
    font-family: "Open Sans", sans-serif;
    font-size: 14px;
}

/* Basis */

.btn {
    font-family: 'Open Sans';
    font-size: 1em;
    display: flex;
    justify-content: center;
    align-items: center;
    border: none;
    background: #fff;
    color: #262626;
    border-radius: 10px;
    height: 50px;
    font-weight: 600;
    min-width: 100px;
    padding: 0px 20px;
    transition: 0.2s ease;
    cursor: pointer;
    outline: 0;
}

.btn:hover {
    color: #FFF;
    background: #455AF7;
}

.btn-small {
    min-width: 50px;
}

.btn-day {
    font-family: 'Open Sans';
    font-size: 1em;
    display: flex;
    justify-content: center;
    align-items: center;
    border: none;
    background: rgba(0, 0, 0, 0);
    width: 100%;
    height: 100%;
    cursor: pointer;
    z-index: 99;
    outline: 0;
    border-radius: 10px;
    transition: 0.4s all;
}

.btn-day.active {
    color: #FFF;
    font-weight: 600;
    z-index: 99;
}

.btn-day.active::before {
    position: absolute;
    content: '';
    width: 40px;
    height: 40px;
    background: #455AF7;
    border-radius: 10px;
    z-index: -1;
}

.text-field {
    padding: 10px;
    height: 50px;
    width: 200px;
    border: 1px solid #f0f0f0;
    border-radius: 10px;
    margin: 0px 10px 0 0;
}

.title {
    font-size: 1.3em;
}

.subtitle {
    font-size: 1.1em;
}

/* Calendar */

.container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
    min-height: 100vh;
    background: #ecf1f8;
}

.calendar-assets {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    width: 100%;
    padding: 10px;
}

#currentDate{
  text-align:center;
  font-size:20px;
}

.field {
    display: flex;
    width: auto;
    flex-direction: column;
    align-items: left;
    justify-content: center;
    margin: 20px 0;
}

.field label {
    margin: 2px;
}

.form-input {
    display: flex;
    width: 100%;
    align-items: center;
    justify-content: center;
}

.day-assets {
    display: flex;
    justify-content: space-between;
    width: 324px;
}

.day-assets .btn:nth-child(2) i {
    padding: 0 10px 0 0 !important;
}

.calendar {
    height: 370px;
    width: 324px;
    border-radius: 18px;
    background: #ffffff;
    padding: 10px;
    user-select: none;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 18px 18px 0px 0px;
    padding: 15px;
    height: 50px;
    width: 100%;
    color: #262626;
}

.month {
    font-size: 0.7em;
}

.icon {
    padding: 10px;
    font-size: 1em;
    margin: 0 0 0 5px;
    background: #ffffff;
    color: #455af7;
    border: none;
    cursor: pointer;
    outline: 0;
}

.icon:hover {
    cursor: pointer;
}

#calendar {
    width: 100%;
}

.weekends th {
    font-size: 1em;
    color: gray;
    font-weight: 400;
    width: 40px;
    margin: 10px 0;
}

#calendar tr {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    text-align: center;
    margin: 3px;
}

#calendar td {
    display: flex;
    height: 40px;
    width: 40px;
    justify-content: center;
    align-items: center;
    text-align: center;
    z-index: 99;
}


text:
Q: SQL CLR, HttpWebRequest, and Connection Throttling Good day!
I have inherited a fairly complex MSSQL database. Used within the code are CLR Assembly DLLs that are called from within stored procedures.
Within these CLR Assembly DLLs, we are reaching out to a 3rd party web service via the .Net 2.0 HttpWebRequest object from the SQL server. (While I understand that this is not the appropriate way to do this, please keep in mind that this was inherited and we are in the process of fixing this.)
Here is the quandary we are currently experiencing:
The SQL CLR is currently throttled to two (2) outbound communication threads (as verified by netstat).
Is there any way to increase the number of outbound threads from the SQL server, either via the .Net configurations or by some other method, including altering the assembly?
Items attempted already:

*

*IIS Worker Thread increase

*Machine.Config:

*

*processModel tuning

*httpRuntime tuning

*system.net connectionManagement tuning

However, no matter what changes are done in the .Net configuration or in IIS, I cannot increase the number of outbound threads. I've spent hours Google'ing the internets to try to find an answer as it relates to HttpWebRequests, SQL CLR, Assemblies, permission types, anything that can help...
Some other stats you may request:

*

*Code written in .NET Version 2.0

*SQL Server 2008 R2 EE

*Windows Server 2008 R2, IIS 7.5

*sp_configure clr_enabled = true

*Assembly / SP set to EXTERNAL_ACCESS

*SP was built WITH ENCRYPTION

Thank you in advance for any information you might be able to provide. If you need anything else, please feel free to ask.
J.R.

A: This was solved using code, specifically the:

*

*ServicePointManager.FindServicePoint(); and

*ServicePointManager.DefaultConnectionLimit.

These two lines needed to be added to the CLR and then the assembly rebuilt on the SQL server.
Hope this helps someone later on in the future.
J.R.


text:
Q: Matrix Transpose Well-defined Let $A$ be a matrix,then both $X=AA^T$ and $Y=A^T A$ are well-defined and symmetrical matrices.
How do I prove this?

A: You have a theorem in your book that says $(AB)^T = B^TA^T$, right? If you do, you can say this:
$$
X^T = (AA^T)^T = (A^T)^TA^T = AA^T = X
$$
and likewise for $Y$.
As for well-defined... My best guess would be that transposes are well-defined and products are well-defined, so doing both of them one after another would produce something well-defined.


text:
Q: Can a host get a virus from a USB device if the guest has control of the device? For example, if running Windows with a Linux guest, is it safe to stick in a USB to scan for viruses with Linux, or can it infect the host OS as well?

A: Without specifics, the only possible answer can be yes.
The host channels all the IO from the device to the guest, and the device must be visible to the host in order for it to become connected to the guest, so autoplay features triggered from the initial plugging in can execute autoplay-triggered malware on the host.
A Host OS dedicated to virtualization, rather than productivity is less of a concern, as it likely lacks features like autoplay, etc, and has a much smaller vulnerable surface area, but that isn't a panacea. Malware can do whatever it is programmed to do, and while there are mitigations, assuming it can do the worst is always the safest approach.
I should point out that of the kinds of malware out there, Viruses in particular would probably not be able to cross any particular host-to-guest boundraries, but Trojans definitely can, and a well written worm may be able to exploit both the guest and the host (as seperate infections; unless you are talking about purple-pill like kernel exploits, guest software almost never knows its virtual). Viruses themselves are largely extinct; killed off by autoupdating applications, and security enhancements to applications with network communications capability.


text:
Q: Help me understand sizing of encrypted home partition I installed 11.10 on my laptop choosing to encrypt home directory.
Now, when I use disk usage analyzer I get this picture:

Total fs capacity is reported correctly as 40.1GB. However inside home directory I have mysterious feature of .ecryptfs which appears to have the same size as my home directory.
What exactly does that mean?

A: .ecryptfs is a special folder where the system stores the encrypted home folder data.
That data is mounted on each user's home directory, so you can see it decrypted and use it comfortably. Since you're the only user on your system, you see that folder has the same size as your home folder.
The mounting process is what makes it appear duplicated. Read more here:
http://help.ubuntu.com/community/EncryptedPrivateDirectory
Cheers!


text:
Q: Does every irreducible projective cubic curve have a nonsingular point of inflection?
Does every irreducible projective cubic curve necessarily have a nonsingular point of inflection?

I've been trying to construct counterexamples, to no avail, which leads me to believe the question can be answered in the affirmative. Here we take $\mathbb{C}$ to be the ground field.

A: I think so. You can always stick an irreducible cubic into a more or less standard form $y^2=x(x-\lambda_1)(x-\lambda_2)$ by a linear change of variables. Then on the patch $y=1$ the curve is nonsingular -- either the whole curve is nonsingular or it has a unique singular point at the origin in the $xy$-plane, depending on the values of the $\lambda$s -- and in the form $z=x^3+ax^2z+bxz^2$. The tangent line here is clearly $z=0$ and it is also clearly inflectionary, as there is no degree-$2$ piece.


text:
Q: How to create a secret in a Docker Vault container I'm familiar with how to create, get, delete, etc secrets in a Vault server running on dev mode (by this I mean all the command line prompts and commands that are used from creating/starting the server, setting the vault address and root token, and then actually working with secrets).
How exactly would I do this with a Vault container? Using the same steps for a Vault server doesn't work, so I'm guessing that I'm missing some step along the way that's necessary for containers but not servers.
Do I have to create a shell script or use docker-compose, or is there any way I could create/start a Vault container and save secrets in it all with terminal commands?


text:
Q: How to import libraries that are not on npm registry in a webpack-built application? I have a react application written in typescript that uses webpack to compile. So far, I could import libraries through the import keyword from node_modules.
However, there are a few libraries I would like to use that are not on the npm registry. So I can't do a npm install of these libraries. For example, Papa Parse is one of those that I can't quite find its npm package. They usually only provide a minified js file which I can't just import into my Typescript file.
For applications that uses webpack to build, how can I use libraries that are not on the npm registry in my code?

A: For anything that doesn't have an npm package, you'll have to download the file and put it somewhere in your project - I'd recommend putting it in a directory called vendor or lib.
The import statement can use a relative path to the module you want to use, so it should be straightforward, e.g. if you put your third-party module in vendor/some-lib.js, you would import it with:
// src/foo.js
import './../vendor/some-lib';

If you want to get fancy, you can use resolve.alias in your webpack config so that you never have to work out the relative path.
// webpack.config.js
const path = require('path');

// ...
resolve: {
  alias: {
    vendor: path.resolve(__dirname, 'vendor')
  }
},

// src/foo.js
import 'vendor/some-lib';

A: You can install git-hosted libraries like this:
npm install git+ssh://git@github.com:mholt/PapaParse.git#4.3.0

Note that everything after the hash has to be either a commit hash or a tag. I got 4.3.0 from here: https://github.com/mholt/PapaParse/releases
If you omit the hash, you'll get the most recent version, but keep in mind every time someone does a fresh npm install in your codebase there's a chance of them pulling down a version with breaking changes.

A: If you cannot import them then you can use require on them and webpack will build them into bundle.
require("PapaParse");

Note:- if you are resolving js files from webpack then you can use simply
import "papaparse"


text:
Q: Similar Matrices of order 6 over $\mathbb{Q}$ Consider $M_2(\mathbb{Q})$. Two matrices $A,B$ from this domain are similar if $ A = CBC^{-1}$ for some $ C \in GL_2(\mathbb{Q})$. How would I go about finding representatives for the similarity classes of matrices $A$ of order 6?

A: If a matrix has order $6$, then it satisfies the polynomial $$t^6-1 = (t^3-1)(t^3+1) = (t-1)(t+1)(t^2+t+1)(t^2-t+1).$$ Hence the minimal polynomial, which must be of degree at most $2$, is either $t-1$, $t+1$, $t^2-1$, $t^2+t+1$, or $t^2-t+1$. It cannot be $t-1$,  $t+1$, or $t^2-1$ (that would mean the matrix has order $1$ or $2$).
Added. And as pointed out by Jyrki Lahtonen and Robert Israel (and overlooked by me), if the minimal polynomial is $t^2+t+1$, then the minimal polynomial divides $t^3-1$, so the matrix will have order $3$.
So you are looking for matrices with minimal polynomial $t^2-t+1$; this is also their characteristic polynomial.
So you just need to figure out the rational canonical form of matrices with characteristic polynomial $t^2-t+1$.


text:
Q: Router port forwarding using cling I'm currently developing an Match Maker for a game called GTA, the problem is that the game server uses 7777 port and I need to open this port to the world to allow players to join in the server, and I don't want the users to make any changes on their routers.
Note: The game server is not mine, I can not modify its source code, I just launch it.
So, I discovered that Cling can handle with port forwarding, but I can't make it to work!
Code I'm using:
public static void openports() throws UnknownHostException {
    InetAddress i = InetAddress.getLocalHost();
    System.out.println(i.getHostAddress());

    UpnpService upnpServiceTCP = new UpnpServiceImpl(new PortMappingListener(new PortMapping(7777, i.getHostAddress(), PortMapping.Protocol.TCP)));
    upnpServiceTCP.getControlPoint().search(new STAllHeader());

    UpnpService upnpServiceUDP = new UpnpServiceImpl(new PortMappingListener(new PortMapping(7777, i.getHostAddress(), PortMapping.Protocol.UDP)));
    upnpServiceUDP.getControlPoint().search(new STAllHeader());
}

anyone has any idea to make it work?

A: You can achieve your goal by using below code
private void doPortForwarding() {

        PortMapping[] desiredMapping = new PortMapping[2];
         desiredMapping[0] = new PortMapping(8123, InetAddress.getLocalHost().getHostAddress(),
                PortMapping.Protocol.TCP, " TCP POT Forwarding");

         desiredMapping[1] = new PortMapping(8123, InetAddress.getLocalHost().getHostAddress(),
                    PortMapping.Protocol.UDP, " UDP POT Forwarding");

         UpnpService upnpService = new UpnpServiceImpl();
         RegistryListener registryListener = new PortMappingListener(desiredMapping);
         upnpService.getRegistry().addListener(registryListener);

        upnpService.getControlPoint().search();

    }

A: Cling have a few problems when you want portforwad ports like this.
You should use this code:
UpnpServiceImpl upnpService = null;
PortMapping[] arr = new PortMapping[2];

    arr[0] = new PortMapping(7777, InetAddress.getLocalHost().getHostAddress(), PortMapping.Protocol.TCP,"My Port Mapping1");
    arr[1] = new PortMapping(7777, InetAddress.getLocalHost().getHostAddress(), PortMapping.Protocol.UDP,"My Port Mapping2");

    upnpService = new UpnpServiceImpl(new PortMappingListener(arr));

    upnpService.getControlPoint().search();

Do not forget to turn on UPnP on the router.
And when your communication ends you should turn it off like this:
upnpService.shutdown();


text:
Q: Attempt to present <> on <> whose view is not in the window hierarchy I'm using this code in AppDelegate where on some condition it either opens login screen or splash screen. like below
if (mobile != nil && keepMe == true) { // skip login

        let initialViewControlleripad : UIViewController = mainStoryboardIpad.instantiateViewController(withIdentifier: "SplashController") as UIViewController
        self.window?.rootViewController = initialViewControlleripad
        self.window?.makeKeyAndVisible()
    }
    else {// Show login

        let initialViewControlleripad : UIViewController = mainStoryboardIpad.instantiateViewController(withIdentifier: "LoginScreen") as UIViewController
        self.window?.rootViewController = initialViewControlleripad
        self.window?.makeKeyAndVisible()
        print("Login!")
    }

when it open splash screen first: from splash screen it goes to main Menu screen like this
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
    let vc = self.view.window?.rootViewController
    let ViewController = storyBoard.instantiateViewController(withIdentifier: "toMenu")
   vc?.present(ViewController, animated:true, completion:nil)

and it is opened fine.
BUT, when from app delegate it open the login screen first and from login screen on a button click it moves to splash and then to main menu it keeps giving this warning,
 Warning: Attempt to present <SWRevealViewController: 0x7faac8839000> on <AppPhaseOne.Splash: 0x7faac7529530> whose view is not in the window hierarchy!

code of login screen:
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
                let ViewController = storyBoard.instantiateViewController(withIdentifier: "SplashController")
                self.present(ViewController, animated:true, completion:nil)

So the construction of viewControllers are like this:
app delegate: Splash -> mainMenu (working fine)
app delegate: Loign -> Splash -> mainMenu (giving the warning)

I know there are many solutions available for this problem, i have tried many solutions available and none of it worked.


text:
Q: Create new row for every 3 items Vue.js Basically the code works fine but I am not able to change the order of the elements.  At the moment the result looks like this:

But actually I would like it like this:

My code Looks like this:
<template>

    <el-container>
      <el-row v-for="story of chunkedItems" :key="story.id">
        <el-col v-for="item of story" :key="item.id">
          <el-card>

{{ item.title }}

{{ item.text }}

          </el-card>
        </el-col>
      </el-row>
    </el-container>

</template>

computed: {
    chunkedItems() {
      return this.$_.chunk(this.stories, 3);
    },
  },

Any suggestion is appreciated.

A: Remove the chunk and use :span="8" instead.
<template>

    <el-container>
      <el-row>
        <el-col :span="8" v-for="item of stories" :key="item.id">
          <el-card>

{{ item.title }}

{{ item.text }}

          </el-card>
        </el-col>
      </el-row>
    </el-container>

</template>

computed: {
},


text:
Q: Apply same Margin-Left value from one class to another I have two div's, classes parallax-slider and parallax-bg.
parallax-bg has a margin-left class associated with it that changes depending on window resize or browser size.
I'm looking to apply replicate this to parallax-slider and make it so that it has the same margin-left css element as parallax-bg
Here's what I have so far:
$(document).ready(function(){
  $(".parallax-slider").css({
       'margin-left': ($(".parallax-bg").css("marginLeft").replace('px', ''))
    });
  $(window).resize(function(){
 $(".parallax-slider").css({
      'margin-left': ($(".parallax-bg").css("marginLeft").replace('px', ''))
   });
 });
});

But this is not working, and only adding a margin-left: 0px; attribute to parallax-slider
What am I doing wrong so that I may get the margin-left attribute of parallax-bg to apply it to parallax-slider?

A: try removing replace('px', '') and it works.
$(document).ready(function() {
  $(".parallax-slider").css({
    'margin-left': $(".parallax-bg").css("marginLeft")
  });

  $(window).resize(function() {
    $(".parallax-slider").css({
      'margin-left': $(".parallax-bg").css("marginLeft")
    });
  });
});

https://jsfiddle.net/x0aderjj/1/


text:
Q: Spherical Coordinates to Cartesian conversion according to the viewing angle (FOV, zoom) I have a spherical projection of the sky texture made in WebGL which takes CameraAngleX, CameraAngleY and CameraZoom parameters to calculate the coordinates by ray direction function:
vec3 GetRayDirection(vec2 uv, vec3 ro, float zoom) {
  vec3  cf = normalize(-ro);
  vec3  cr = normalize( cross( vec3(0,1,0), cf ));
  vec3  cu = cross(cf,cr);
  vec3  c = ro + cf * zoom;
  vec3  i = c + uv.x*cr + uv.y*cu;
  vec3  rd = normalize(i - ro);
  return rd;
}

I need to bind some JavaScript elemnts on the top of this projection, so when Zoom = 1.0 and there is no distortion, biding with standard spherical-to-cartesian formula works well:
x = r * sin(θ) * cos(φ);
y = r * sin(θ) * sin(φ);
x = r * cos(φ);

But when Zoom is getting smaller than 1.0 and wide angle field of view distortion appears, it doesn't work because. according to distorted FOV projection, elements in the center of the screen should move much slower than in the corners of the screen.
I am looking for a formula which can do the same binding on the wide-angle FOV. Please, advise me some formulas or articles pointing to the conversion of wide-angle spherical coordinates to Cartesian! Thanks.


text:
Q: javascript custom event bind delegation like jQuery.on() I am trying to imitate jQuery.on("click", ".target", handler) by utilizing addEventListener() method. My research on Stackoverflow end up with this: Native addEventListener with selector like .on() in jQuery.
So, before some one mark my question as DUPLICATE  please read carefully my requirements and my demo.
Here is my Plunker demo https://plnkr.co/edit/so8Sur?p=preview ( I am running chrome when testing it ). Following is the explanation for it:

*

*At purple box which is "jQuery way" is running as my expectation which should be show Message popup no matter i am clicking on .target box or it children which is .target-child.

*But for green box which is my custom event binding, with custom function: customOn(selector, type, filter, handler), it will only show popup when click on .target box only, but it will not show popup when i click on .target-child.

So, my question is, I wonder what kind of magic used by jQuery to make event to be triggered when click on the .target-child on my demo, while the actual selector filter is .target. Will jQuery traverse up on DOM trees to check any selector match every time it needs to handle delegated event? If yes, i feel it will take enough computation resource ( maybe RAM ), is that right? I hope there will be much efficient way rather than doing traverse up like that.
Any answer and comment will be highly appreciated. Thanks in advance.

A: Jquery use css selectors as crawling system.
So if you click on something, it will "crawl" the parents until it match (or not) the target.


text:
Q: Sonar Server in Debug Modus - Do not stop at Breakpoint For the development of my own sonar plugin i want to be able to debug.
after quite a while I found out how to run the sonarqube server in debug mode. Therefore I followed the instruction of the following website. enter link description here
When I started the server in debug modus an connect eclipse by using the debug configuration, the server starts but it do not not stop at the breakpoints that I have been set. I have set breakpoints to extension point (classes) like the one which extends the SonarPlugin class or the one which extends the RuleRepository class. The logs of these classes are part of the server log file, so I'm pretty sure that this classes are executed. Nevertheless it doesn't stop at the breakpoints.
Anyone ideas whats the problem?

A: The server runs as three process - a parent application, the web server and a search server. Plugins are loaded into the web server so you need to start this with debug arguments. The options for this seem to have changed and are not yet reflected in the documentation. To debug the web server put:
sonar.web.javaAdditionalOpts=-agentlib:jdwp=transport=dt_socket,suspend=y,server=y,address=9001

into your sonar.peroperties file and start sonar using the StartSonar script. This will launch all three applications, but with the web server suspended. Attach your debugger to port 9001 and you should find your plugin main class and rules definition breakpoints are hit.


text:
Q: Loop through a list of Elements by Partial Link Text Selenium I'm stuck and need help on investigation and improvement.
I am trying to gather all the <a> tags with Annual Report as their partial text then loop through them since they're originally located inside a table(2nd column per row).
Below is the process that I'm planning to execute:

*

*After clicking an <a> tag, a new window would pop up

*find and get specific values in the new window

*close the window

*move to the next element (<a> tag) and repeat

The code below is my current progress, but it is completely not working. I am still unable to click the very first element.
var reportLinks = driver.findElements(By.partialLinkText('Annual Report'));

for(var i = 0; i < reportLinks.length; i++){
    reportLinks[i].click();
}

A: This is how I would accomplish this
//This will get you how many elements are present
var reportLinks = driver.findElements(By.xpath('//tr/td/a[contains(text(),'Annual Report')]'));

//This will click on each element
for(var i = 0; i < reportLinks.length; i++){
driver.findElement(By.xpath('//tr[' + i + ']/td/a[contains(text(),'Annual Report')]')).click();
}

The reason for this is the Annual Report element is not the parent container the  element is.

A: I was able to make it work using the code below:
for (var i = 1; i < 51; i++) {

    var element = driver.findElement(By.xpath('//*[@id="dataList"]/table/tbody/tr[' + i + ']/td[1]/a'));
    driver.executeScript("arguments[0].click();", element);

}

I just copied the xpath on the page through Google Chrome's Inspect Element feature and passed an argument via executeScript.
You could find out how via this link: Is there a way to get the xpath in google chrome?
Thank you very much!


text:
Q: How can I get the country (or its ISO code)? What is the best way to get the country code?
As of now, I know two ways. One is to get by TelephonyManager and another by Locale. Which is another best and unique way to find the country code on Android?

A: I solved it by IP Address. You can get the IP address of your phone. If you are using Wi-Fi then it will be the IP address of the Wi-Fi hotspot or IP address of your mobile service provider server, so from that IP address you can send to a web service or something to track the country of that IP address.
There are some sources (database) available if Internet which provides the country of IP address.
Here is the example http://whatismyipaddress.com/ip-lookup.

A: I think the IP address is the best way because it will give you the country where the phone is at the moment.
If you do it by
Locale.getDefault().getCountry();

you get the country where the user select the country, so you can have selected England, and you can be in Spain and maybe you need to know where he/she is at the moment.
Example: imagine that your app can buy something only in England. The user is from Spain, but he/she is on holidays in England and he/she wants to buy your product ... if you use
Locale.getDefault().getCountry();

that user won't be able to buy your product, so the IP address is the best way I think.

A: There is an excellent article by Reto Meier:
http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html
It describes different techniques to get the location of an Android device, including source code.
Next, when you have the location, it's easy to get the country for it - you can use an online web-service or offline database.

A: There are always huge discussions about this, and I never understand why developers and companies go for the complex way.
The language selected by the user, means the language he/she wants to see always in his/her phone. They don't intend to have apps in a different language than others or the system.
The choice is very straight forward: Use Locale (to get the language the user selected as preferred), or make your best to piss them off showing them information in a language they already said they don't want to see things in.
To get the country code use:
Locale.getDefault().getCountry();

A: It's very hard to find the country without GPS and Google Services (China). TelephonyManager won't work if there isn't any SIM card in your phone.
And Locale won't work if a user in China set his/her language as English (the country you will be getting will be US or UK).
If your app requires an Internet connection then there is an option. You could use this API called ip-api. Please go through their documentation first if you are planing to use this.
There are other APIs like this freegeoip API.

A: Use:
TelephonyManager tm = (TelephonyManager)getSystemService(getApplicationContext().TELEPHONY_SERVICE);
String countryCode = tm.getNetworkCountryIso();

It is better than getSimCountryIso because getSimCountryIso depends on the operator to burn the country ISO into the SIM and it also supports CDMA networks.

A: You can use this code to get ISO 2:
Locale.getDefault().getCountry()

And this to get ISO 3:
Locale.getDefault().getISO3Country()

A: Here is a complete example. Try to get country code from TelephonyManager (from a SIM card or CDMA devices), and if not available, try to get it from the local configuration.
private static String getDeviceCountryCode(Context context) {
    String countryCode;

    // Try to get the country code from the TelephonyManager service
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    if(tm != null) {
        // Query first getSimCountryIso()
        countryCode = tm.getSimCountryIso();
        if (countryCode != null && countryCode.length() == 2)
            return countryCode.toLowerCase();

        if (tm.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
            // Special case for CDMA devices
            countryCode = getCDMACountryIso();
        } else {
            // For 3G devices (with a SIM card), query getNetworkCountryIso()
            countryCode = tm.getNetworkCountryIso();
        }

        if (countryCode != null && countryCode.length() == 2)
            return countryCode.toLowerCase();
    }

    // If the network country is not available (tablets maybe), get the country code from the Locale class
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        countryCode = context.getResources().getConfiguration().getLocales().get(0).getCountry();
    } else {
        countryCode = context.getResources().getConfiguration().locale.getCountry();
    }

    if (countryCode != null && countryCode.length() == 2)
        return  countryCode.toLowerCase();

    // General fallback to "us"
    return "us";
}

@SuppressLint("PrivateApi")
private static String getCDMACountryIso() {
    try {
        // Try to get country code from SystemProperties private class
        Class<?> systemProperties = Class.forName("android.os.SystemProperties");
        Method get = systemProperties.getMethod("get", String.class);

        // Get homeOperator that contain MCC + MNC
        String homeOperator = ((String) get.invoke(systemProperties,
                "ro.cdma.home.operator.numeric"));

        // First three characters (MCC) from homeOperator represents the country code
        int mcc = Integer.parseInt(homeOperator.substring(0, 3));

        // Mapping just countries that actually use CDMA networks
        switch (mcc) {
            case 330: return "PR";
            case 310: return "US";
            case 311: return "US";
            case 312: return "US";
            case 316: return "US";
            case 283: return "AM";
            case 460: return "CN";
            case 455: return "MO";
            case 414: return "MM";
            case 619: return "SL";
            case 450: return "KR";
            case 634: return "SD";
            case 434: return "UZ";
            case 232: return "AT";
            case 204: return "NL";
            case 262: return "DE";
            case 247: return "LV";
            case 255: return "UA";
        }
    }
    catch (ClassNotFoundException ignored) {
    }
    catch (NoSuchMethodException ignored) {
    }
    catch (IllegalAccessException ignored) {
    }
    catch (InvocationTargetException ignored) {
    }
    catch (NullPointerException ignored) {
    }

    return null;
}

Also another idea is to try an API request like in this answer, or to use fine location.
References are here and here.


text:
Q: When I float the div to the right the screen messes up...I've tried clear and some other options I'm having an issue in general when it comes to floats. I'll be doing fine with the layout but once I start floating the whole page does weird stuff. I think I need a better understanding of the concept of what goes on. Here is my code for html and css.

* {
 margin: 0;
}
#heading {
 background-color: black;
 height: 150px;
}
#navigation {
 background-color: green;
 height: 30px;
}
#leftSide {
 background-color: blue;
 width: 400px;
 height: 700px;
}
#rightSide {
 background-color: red;
 width: 400px;
 height: 700px;
 float: right;
}
#footer {
 background-color: black;
}

Heading

Navigation

Left Side

Right Side

Footer

A: Use display:inline-block; for your id leftSide

#heading {
 background-color: black;
 height: 150px;
}
#navigation {
 background-color: green;
 height: 30px;
}
#leftSide {
 background-color: blue;
 width: 50%;
 height: 700px;
  display:inline-block;
}
#rightSide {
 background-color: red;
 width: 50%;
 height: 700px;
 float: right;
}
#footer {
 background-color: black;
}
<!DOCTYPE html>

 <title>This is it</title>
 <link rel="stylesheet" type="text/css" href="style.css">

Heading

Navigation

Left Side

Right Side

Footer

A: Floating elements create a new block formatting context and so it must be cleared before your footer if you expect it to come below the preceeding contents.
If I guess right, you need to float: left your leftSide div.
I placed your clear: right div above the footer and made it clear: both.
Snippet below:

* {
  margin: 0;
}
#heading {
  background-color: black;
  height: 150px;
}
#navigation {
  background-color: green;
  height: 30px;
}
#leftSide {
  background-color: blue;
  width: 400px;
  height: 700px;
  float: left;
}
#rightSide {
  background-color: red;
  width: 400px;
  height: 700px;
  float: right;
}
#footer {
  background-color: black;
}

Heading

Navigation

Left Side

Right Side

Footer


text:
Q: Adding scope to constantized string in Rails I am trying to send a scope to an action that creates an instant variable. Here is my attempt:
foo_controller.rb

    define_method(:generate_index) do |string, scope|
        instance_variable_set( "@#{string}", (string.camelize.constantize).public_send scope )
    end

   def index
      generate_index("foo", "all")
   end

In the above instance, would expect the following to be created:
def index
    @foo = Foo.all
end

Instead, I am presented with an error stating:
unexpected tSYMBEG, expecting ')'

Could anybody perhaps assist in pointing out where I'm going wrong?
Thanks

A: Just add some brackets.
define_method(:generate_index) do |string, scope|
    instance_variable_set( "@#{string}", string.camelize.constantize.public_send(scope))
end


text:
Q: Binding to media keys, block iTunes OS X I've been using the methods described here: http://weblog.rogueamoeba.com/2007/09/29/
and read this thread: Binding to Media keys on Apple keyboards under OSX 10.5
I've overridden the sendEvent class, and can detect media key input. The problem is that iTunes launches when the Play button is pressed. The above mentioned thread states that iTunes hooks into the event somewhere else (unknown), so there isn't a way to block it from getting the Play/Pause(F8) event.
As a workaround, I've been leaving Quicktime Player open with no file. However, on Mountain Lion, Quicktime closes itself after a certain period of inactivity apparently, thus rendering this workaround unviable.
I know applications such as Spotify and MPlayerX have been able to achieve this somehow. They appear to block the event completely, not just for iTunes.
More googling, I found this discussions.apple.com/thread/2122639?start=210&tstart=0 which tracks it down to the Remote Control Daemon making the calls via Applescript. There are some work arounds which removes the execution permission on the rcd daemon (requires sudo, has to be re-run anytime OSX is updated). nomitsu.com/contents/MMFix_src.tgz
Does anyone have any insight as to how they (MPlayerX, Spotify) have been able to do this is a less hacky way?
Thanks for any advice.

A: I found a pre-existing class that will do this: http://overooped.com/post/2593597587/mediakeys
Wow, that took some looking to find! Hope it helps someone else!


text:
Q: Ruby in `gem_original_require': no such file to load -- CloudyScripts (LoadError) On Ubuntu and Ruby 1.8.7, I installed CloudyScripts via:
gem install gem install CloudyScripts

When I try to execute this:
require 'rubygems'
require 'CloudyScripts'

I get the following error:
/usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- CloudyScripts (LoadError)
        from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
        from /home/ubuntu/copyami.rb:3

$ gem list
*** LOCAL GEMS ***

amazon-ec2 (0.9.17)
CloudyScripts (1.9.40)
net-scp (1.0.4)
net-ssh (2.2.1)
xml-simple (1.1.0)

The gem is installed in /var/lib/gems/1.8/gems, the contents of which are
drwxr-xr-x 6 root root 4096 2011-08-31 17:39 amazon-ec2-0.9.17
drwxr-xr-x 3 root root 4096 2011-08-31 18:39 CloudyScripts-1.9.40
drwxr-xr-x 4 root root 4096 2011-08-31 17:39 net-scp-1.0.4
drwxr-xr-x 5 root root 4096 2011-08-31 17:39 net-ssh-2.2.1
drwxr-xr-x 3 root root 4096 2011-08-31 17:39 xml-simple-1.1.0

And $LOAD_PATH is
    /usr/local/lib/site_ruby/1.8
    /usr/local/lib/site_ruby/1.8/x86_64-linux
    /usr/local/lib/site_ruby
    /usr/lib/ruby/vendor_ruby/1.8
    /usr/lib/ruby/vendor_ruby/1.8/x86_64-linux
    /usr/lib/ruby/vendor_ruby
    /usr/lib/ruby/1.8
    /usr/lib/ruby/1.8/x86_64-linux
    .
Why am I getting the load error?

A: You should try
gem "CloudyScripts"
require "cloudyscripts"

Only the gem name is camelcased, but not the ruby files in it.

A: I had a similar problem when I was trying to run the rng(release notes generator command). The error is shown below.
/Ruby193/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in require': cannot load such file -- thor (LoadError)
from C:/Ruby193/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:inrequire'
        from ./rng:6:in `'
After lot of searching around I found the above post helpful. I just had to run
C:\mydirectory>gem install thor
The rng command works perfectly now


text:
Q: hotmail/live mail missing document attachments like bank statements I am using windows hotmail for the past few years, and recently the layout of hotmail is changed. along with the layout, now i am not able to see the documents in the mail attachments which are received from banks/credit cards. Don't know if anyone else is facing this issue. See the image below which is showing documents but the actual attachment is missing from the mail

A: I had the same problem and just found out what caused it. In my case I am using Google Chrome and use Adblock. After excluding the outlook.live.com domain from Adblock the attachment returned. I hope this helps you too.


text:
Q: why jquery dialog is not working for below code? I having idea how to open jquery dialog, but what's wrong with below code, please suggest.
here is fiddle link,
Fiddle Link......
Open Dialog

A: Why do you have your dialog inside a load call?
That's not necessary, and you have not defined dialogTitle which will throw an error on initialization.
Try this
jQuery(document).ready(function () {
    $('.dialogLink').live('click', function () {
        $("#popId").dialog({
            modal: true,
            resizable: false,
            title: '', // Set this to an actual variable or string
            minWidth: 800,
            minHeight: 300,
            closeOnEscape: false,
            buttons: {
                "Cancel": function () {
                    $(this).dialog('close');
                }
            }
        });
    });
});

A: To elaborate on the previous answer, you do not need to call the load method
at all.  Instead, you will want to call the .dialog method using the $("#popId")
selector instead of $(this).
Here is a working example:
jQuery(document).ready(function () {
$('.dialogLink').live('click', function () {
    $("#popId").dialog({
        modal: true,
        resizable: false,
        title: "This is my test title",
        minWidth: 800,
        minHeight: 300,
        closeOnEscape: false,
        buttons: {
            "Cancel": function () {
                $(this).dialog('close');
            }
        }
    });
});
});


text:
Q: What does "Shift:=" mean in this VB6 code? I've run across the following line in a VB6 application.
mobjParentWrkBk.ExcelWorkBook.Application.Selection.Insert Shift:=xlToRight

Unfortunately Google and other search engines have not been very useful as they seem to omit the := part.
What would be a C# equivalent?

A: Just to clarify John Rudy's response.
The sytax is optional (small 'o'), meaning you don't have to use it. In my experience, most VB6 coders don't use the syntax and instead prefer regular 'unnamed' parameters.
If you do choose to use it, all subsequent paramters in the sub procedure call must be named.
The named paramter syntax can be used on all parameters, whether or not the corresponding argument was declared using the VBA keyword Optional (capital 'O'). Consider, for example, this (slightly daft) VBA function with two parameters, one required and one Optional:
Private Function TimesTen( _
    ByVal Value As Long, _
    Optional ByVal Factor As Long = 10 _
) As Long
  TimesTen = Value * Factor
End Function

In VBA, I can call it using named parameters for the required parameter (the Optional paramter can simply be omitted in VBA, unlike in C#.NET for which Type.Missing must be used for all omitted Optional parameters):
  MsgBox TimesTen(Value:=9)

If I wanted to call it with the parameters in the 'wrong' order (why??) I can achieve this using named parameters:
  MsgBox TimesTen(Factor:=11, Value:=9)

Trying to use a regular 'unnamed' parameter call after a named one causes a compile error:
  MsgBox TimesTen(Value:=9, 11)

So why do VBA coders use named parameters if VB6 coders rarely do, even though they use essentially the same language? I think it is because the VBA generated by the MS Office applications' macro recorder tends to (always?) generate named parameters and many VBA coders learn programming this way.

A: VB6 and VB.net has optional parameters in method.
c# has the option to do method overloading.
VB6/VB.net way of saying Shift:=xlToRight allows passing value of a specific parameter by name.
e.g.
public sub mymethod(optional a as integer = -1, optional b as integer=1)
...
end sub
I can call this method with mymethod(b:=10)
For c#, there could be 2 methods for this

void Shift()
{
defaultDirection = directionEnum.Left;
Shift(defaultDirection);
}

void Shift(directionEnum direction)
{
}

1 more thing.
Although you can call method just by passing parameters, adding parameter name when calling makes code a little more readable.
e.g. DoSomethingWithData(CustomerData:= customer, SortDirection:=Ascending)
Hope that helps.

A: This is Visual Basic syntax for optional named parameters. The Insert function has a parameter named Shift, which is being specified.
C#, as far as I know, doesn't have an equivalent for optional named parameters. Instead, you'd need to call the Insert method, specifying Type.Missing for all parameters other than Shift.
See also the following StackOverflow question: VB.NET := Operator
UPDATE (2008-10-29):
C# 4.0 is set to introduce optional and named parameters. See this blog entry on codebetter.com.

A: It's really all about Excel and how it handles inserts.  If you select a range of cells and right-click Insert you will be asked which direction to shift the cells.  This is from the Excel Help:
=======
Insert Method on Range Object
Inserts a cell or a range of cells into the worksheet or macro sheet and shifts other cells away to make space.
expression.Insert(Shift, CopyOrigin)
expression    Required. An expression that returns a Range object.
Shift   Optional Variant. Specifies which way to shift the cells. Can be one of the following XlInsertShiftDirection constants: xlShiftToRight or xlShiftDown. If this argument is omitted, Microsoft Excel decides based on the shape of the range.
CopyOrigin   Optional Variant. The copy origin.
===========
If you don't have the constants defined you can subsitute the following numbers
xlShiftDown: -4121
xlShiftToLeft: -4159
xlShiftToRight: -4161
xlShiftUp: -4162


text:
Q: Save stored prodeure result as file i have a Stored Procedure , in proc  Print certain result like
Print '-- Start Transection--'
Print 'Transection No = ' + @TransectionId
...
...
Print 'Transection Success'
Print '-- End Transection--'

is it possible to Save printed result in a file while call it from UI. after that we have to mail that file to user also ask for download that file

A: PRINT is for logging and debugging purposes and shouldn't be used to return anything to the caller.
Here's a suggestion: instead of PRINTing, write into a logging table and return a loggingID. Then, query this table from your app and write to a file.
Example: create two tables
CREATE TABLE Logging
(
    LoggingID int IDENTITY(1,1) PRIMARY KEY,
    Created datetime
)

CREATE TABLE LoggingDetail
(
    LoggingDetailID int IDENTITY(1,1) PRIMARY KEY,
    LoggingID int FOREIGN KEY REFERENCES Logging,
    LoggingText varchar(500)
)

At the beginning of a transaction, create a new loggingID:
INSERT INTO Logging (Created) VALUES (GETUTCDATE())
DECLARE @loggingID INT = @@IDENTITY

Instead of PRINTing the logging messsages, do something like
INSERT INTO LoggingDetail (LoggingID, LoggingText) VALUES (@loggingID,
'-- Start Transection--')

At the end of your sproc, return @loggingID to the caller. You can now get retrieve the log messages from the LoggingDetail table and write them to a file:
SELECT LoggingText FROM LoggingDetail WHERE LoggingID=<loggingID> ORDER BY LoggingDetailID

Might be a good idea to encapsulate the INSERTs in separate sprocs. Those sprocs then can write to the log tables and PRINT the log messages.


text:
Q: Dimensions must be equal, but are 15 and 1 for 'MatMul_1' (op: 'MatMul') with input shapes: [1,15], [1,500] I cannot understand the dimension part. Is it about the shape [1,15]I set?
import tensorflow as tf
import numpy as np
import pandas as pd

with open('train.CSV', 'r') as f:
    data0 = f.readlines()

    for line in data0:
        odom = line.split()
        numbers_float0 = map(float, odom)

with open('trainY.CSV', 'r') as f:
    data1 = f.readlines()

for line in data1:
    odom = line.split()
    numbers_float1 = map(float, odom)

with open('test.CSV', 'r') as f:
    data2 = f.readlines()

    for line in data2:
        odom = line.split()
        numbers_float2 = map(float, odom)

with open('Test Y.CSV', 'r') as f:
    data3 = f.readlines()

    for line in data3:
        odom = line.split()
        numbers_float3 = map(float, odom)

train_x,train_y,test_x,test_y =             ('numbers_float0','numbers_float1','numbers_float2','numbers_float3')
n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 2
batch_size = 100
hm_epochs = 10

x =tf.placeholder('float',[1,15])
y = tf.placeholder('float',[1,1])

hidden_1_layer = {'f_fum':n_nodes_hl1,
                  'weight':tf.Variable(tf.random_normal([len(train_x[0]),         n_nodes_hl1])),
                  'bias':tf.Variable(tf.random_normal([n_nodes_hl1]))}

hidden_2_layer = {'f_fum':n_nodes_hl2,
                  'weight':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
                  'bias':tf.Variable(tf.random_normal([n_nodes_hl2]))}

hidden_3_layer = {'f_fum':n_nodes_hl3,
                  'weight':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
              'bias':tf.Variable(tf.random_normal([n_nodes_hl3]))}

output_layer = {'f_fum':None,
            'weight':tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])),
                'bias':tf.Variable(tf.random_normal([n_classes])),}

# Nothing changes
def neural_network_model(data):

    l1 = tf.add(tf.matmul(data,hidden_1_layer['weight']),     hidden_1_layer['bias'])
    l1 = tf.nn.relu(l1)

    l2 = tf.add(tf.matmul(l1,hidden_2_layer['weight']),     hidden_2_layer['bias'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2,hidden_3_layer['weight']), hidden_3_layer['bias'])
    l3 = tf.nn.relu(l3)

    output = tf.matmul(l3,output_layer['weight']) + output_layer['bias']

    return output

def train_neural_network(x):
    prediction = neural_network_model(x)
    cost =     tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
    #tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(prediction,y) )

    optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)

    with tf.Session() as sess:
        sess.run(tf.initialize_all_variables())

        for epoch in range(hm_epochs):
            epoch_loss = 0
            i=0
            while i < len(train_x):
                start = i
                end = i+batch_size
                batch_x = np.array(train_x[start:end])
                batch_y = np.array(train_y[start:end])

                _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
                                                          y: batch_y})
                epoch_loss += c
                i+=batch_size

            print('Epoch', epoch+1, 'completed out of',hm_epochs,'loss:',epoch_loss)
        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))

        print('Accuracy:',accuracy.eval({x:test_x, y:test_y}))

train_neural_network(x)

Here is the trace error:enter image description here
Here is the Data train.CSV
enter image description here
The Y data I use is only one column .

A: Technically the placeholder doesn't need a shape at all. It can be defined as such.
x = tf.placeholder('float', shape=[])

In this case the place holder itself has no shape information to it. If you know the dimensions of the tensor but not it's actual numerical shape we replace the numerical value of that dimension with None because it can have a variable size.
 x = tf.placeholder('float', shape=[None, None, None])

This affects some down stream static shape analysis that tensorflow does to get the shape information but otherwise it should still work as intended.


text:
Q: Update only necessary states in useContext hook In the following example, a click on the first button re-renders both of the child components (ComponentOne and ComponentTwo), although the state of the second number does not change (because the whole useContext array value changes). I would like to know how we can detect multiple individual values, or any other method to only render states that changed.
const TwoNumbers = createContext();

function ComponentOne(){
  const number = useContext(TwoNumbers)[0];

  return(

{number}

  )
}

function ComponentTwo(){
  const number = useContext(TwoNumbers)[1];

  return(

{number}

  )
}

function App() {

  const [numberOne, setNumberOne] = useState(0);
  const [numberTwo, setNumberTwo] = useState(0);

  return (
    <TwoNumbers.Provider value={[numberOne, numberTwo]}>

        <ComponentOne/>
        <ComponentTwo/>
        <button onClick = {()=>{setNumberOne(numberOne+1)}}>First+1</button>
        <button onClick = {()=>{setNumberTwo(numberTwo+1)}}>Second+1</button>

      </TwoNumbers.Provider>
  );
}

In real scenario the two numbers will represent the view count and other real-time data I would like to update after the backend updated. I see Stack Overflow is not doing this. Is real-time state matching an expensive move? Does it extensively add more time for page loading?

A: One solution is to create two Contexts and use two context providers. Then each of the child components (ComponentOne and ComponentTwo) consumes its own respective context. Finally in order to prevent a child component from being updated by its parent (App) due to the changes on the context value of the other sibling component, you can use React.memo.
const ContextNumberOne = createContext();
const ContextNumberTwo = createContext();

React.memo(function ComponentOne(){
  const number = useContext(ContextNumberOne);

  return(

{number}

  )
})

React.memo(function ComponentTwo(){
  const number = useContext(ContextNumberTwo);

  return(

{number}

  )
})

function App() {

  const [numberOne, setNumberOne] = useState(0);
  const [numberTwo, setNumberTwo] = useState(0);

  return (
    <ContextNumberOne.Provider value={numberOne}>
       <ContextNumberTwo.Provider value={numberTwo}>

                <ComponentOne/>
                <ComponentTwo/>
                <button onClick = {()=>{setNumberOne(numberOne+1)}}>First+1</button>
                <button onClick = {()=>{setNumberTwo(numberTwo+1)}}>Second+1</button>

        </ContextNumberTwo.Provider>
     </ContextNumberOne.Provider>
  );
}

A: Look into using Redux instead, it specially solves this problem. You can use useSelector to subscribe to the particular bit of state that you care about, and only rerender when that changes.


text:
Q: Will simultaneity bias occur if I use VAR to test the linkages between monetary shocks, interest rates, and inflation? I am writing an undergraduate paper and my goal is to investigate the liquidity effect. That is, I want to determine if expansions in monetary policy reduce interest rates.
Initially, I wanted to create a SEM because economic theory says that monetary aggregates (such as M1) are jointly determined with interest rates. However, in studying the literature for this paper, I've discovered that many researchers estimate a VAR with interest rates, economic output, money supply, and inflation as dependent variables.
Many of these authors also do not mention anything about simultaneity bias.
So, my question is: do we need to worry about simultaneity bias when studying interest rates? If not, then why?


text:
Q: Using Cobertura produces a NoClassDefFoundError we are using Cobertura (defined in a gradle build). When I deploy the application and click around in the swing client, there appears a NoClassDefFoundError from cobertura.
java.lang.NoClassDefFoundError: net/sourceforge/cobertura/coveragedata/HasBeenInstrumented
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at com.sun.jnlp.JNLPClassLoader.findClass(JNLPClassLoader.java:345)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)

I have no clue where this is coming from. There is nothing from cobertura in my java code. The only place where cobertura is defined is in the gradle build files as dependencies:
testCompile "net.sourceforge.cobertura:cobertura:1.9.4.1"

I made a grep over the two main projects:
find -type f -name "*gradle*" -exec grep -Hn cobertura {} \;

Here the result:
./BigTableDataProvider/ext-test/build.gradle:7:def cobSerFile = "$buildDir/cobertura.ser"
./BigTableDataProvider/ext-test/build.gradle:24:    testCompile 'net.sourceforge.cobertura:cobertura:1.9.4.1'
./BigTableDataProvider/ext-test/build.gradle:34:    codeCoverageRun 'net.sourceforge.cobertura:cobertura:1.9.4.1'
./BigTableDataProvider/ext-test/build.gradle:42:    jvmArgs = sampleJvmArg.split(" ").toList() << "-Dnet.sourceforge.cobertura.datafile=$cobSerFile"
./BigTableDataProvider/ext-test/build.gradle:50:        'cobertura-instrument'(datafile: cobSerFile) {
./BigTableDataProvider/ext-test/build.gradle:63:    ant.'cobertura-report'(destdir: "${project.buildDirName}/reports/codeCoverage",

./BigTableExplorer/sample/server/build.gradle:10:    testCompile 'net.sourceforge.cobertura:cobertura:1.9.4.1' // Add this if sample module has inherited classes from server.
./BigTableExplorer/ext-server/build.gradle:20:    testCompile "net.sourceforge.cobertura:cobertura:1.9.4.1"
./BigTableExplorer/ext-test/build.gradle:7:def cobSerFile = "cobertura.ser"
./BigTableExplorer/ext-test/build.gradle:22:    testCompile 'net.sourceforge.cobertura:cobertura:1.9.4.1'
./BigTableExplorer/ext-test/build.gradle:34:    codeCoverageRun 'net.sourceforge.cobertura:cobertura:1.9.4.1'
./BigTableExplorer/ext-test/build.gradle:42:    jvmArgs = sampleJvmArg.split(" ").toList() << "-Dnet.sourceforge.cobertura.datafile=$cobSerFile"
./BigTableExplorer/ext-test/build.gradle:50:        'cobertura-instrument'(datafile: cobSerFile) {
./BigTableExplorer/ext-test/build.gradle:63:    ant.'cobertura-report'(destdir: "${project.buildDirName}/reports/codeCoverage",

A: You are accidentally deploying the Cobertura-instrumented code. The Gradle build must be using some third-party Cobertura plugin or Cobertura Ant task, and apparently it is configured incorrectly.


text:
Q: Saturated subsets of quotient map. From an example in Munkres Topology:
Consider the projection map $\pi_{1}: \mathbb{R} \times \mathbb{R} \to \mathbb{R}$ onto the first coordinate; it is continuous and surjective. It is also open which tells us it is a quotient map. Given the subset: $$C = \{(x, y) \text{ | } xy=1 \}$$ We construct: $$A = C \cup \text{{(0,0)}}$$
$A$ is a subspace of $\mathbb{R} \times \mathbb{R}$ and the map $\pi_{1}$ restricted to $A$ is not a quotient map because even though $\text{{(0,0)}}$ is saturated with respect to the restriction, it's image is closed in $\mathbb{R}$.
Is $A$ saturated with respect to $\pi_{1}$? From what I have understood, saturation means that for all $r \in \mathbb{R}$, if $\pi_1^{-1}{({r})}$ intersects $A$, then $\pi_1^{-1}{({r})} \subset A$. What exactly is $\pi_1^{-1}{({r})}$ here? Is it $(\{r\} \times \mathbb{R})$?

A: Another equivalent way to define saturated sets: $f:X \to Y$ and $A \subseteq X$ is saturated wrt $f$ iff $f^{-1}[f[A]]=A$ or $\forall x \in X: f(x) \in f[A] \implies x \in A$.
We consider the map $\pi'_1: A \to \mathbb{R}$, the restricted projection (which is of course still continuous).
The only point that maps to $\{0\} = \pi'_1[\{(0,0)\}]$ is $(0,0)$ (because the domain is $A$!) and that already lies in $\{(0,0)\}$. So $\{(0,0)\}$ is saturated wrt $\pi'_1$. If you think about it, $\pi'_1$ is in fact 1-1 so all subsets are saturated.


text:
Q: Null POJO in @FormParam I am developing RESTful services with Jersey and I have had a few problems since I updated the version from 2.6 to the latest.
I have a @BeanParam object containing @formParam parameters :
public class UpdateBeanParam {

    @FormParam
    private Area area;

    ...
}

When I submit a POST request (url-form-encoded) without defining an area parameter, I get a BadRequestException, caused by a NullPointerException in the default converter. With the old version it used to create an UpdateBeanParam with a null area.
This problem does not occur with String types (or other common types) as converters for those handle null values well.
Anyone knows how to allow null values for custom objects ?
Thanks for your help !


text:
Q: How do I plot elements of a list? I have imported yahoo data into a list of lists so that each list has all the data for each day.  I want to use the first entry (date entry) of the list for the abscissa.  I have gone through a lot of examples and many use dictionaries which I am unfamiliar with.  I figured something like this:
chart.plot(data[:][0], data[:][1])
would work but it doesn't.  Apparently, data[:][0] will just give you the first list as opposed to the first element of every list.  I know, I could just make 2 new lists of all the dates and say stock prices with a for loop but that seems wrong.

A: To get nth elements of every list in list, you can use list comprehension:
#nth_elements = [l[n] for l in data]
#for example:
x_list = [l[0] for l in data]
y_list = [l[1] for l in data]

Now you can call chart.plot(x_list, y_list).

If you don't like the "extra" variables, you can use list comprehension directly in the function call:
chart.plot([l[0] for l in data], [l[1] for l in data])

However a simple for loop does the same in one loop, so no need to loop twice over your data list:
x_list = []
y_list = []
for l in data:
    x_list.append(l[0])
    y_list.append(l[1])

Even if it's not that pythonic, it works and is original. It shouldn't feel "wrong" at all.

A: Does this interest you ? :
li = [["GLD","SPDR Gold Trust",
       '161.57','161.47','162.02','161.20','0.00','N/A'],

      ["SLV","iShares Silver Trust",
       '30.29','30.65','25.34','36.44','0.00','N/A'],

      ["GDX","Market Vectors Gold Miners ETF",
       '42.31','42.77','39.08','57.91','0.00','N/A']]

from itertools import izip

for el in zip(*li):
    print el

displays
('GLD', 'SLV', 'GDX')
('SPDR Gold Trust', 'iShares Silver Trust', 'Market Vectors Gold Miners ETF')
('161.57', '30.29', '42.31')
('161.47', '30.65', '42.77')
('162.02', '25.34', '39.08')
('161.20', '36.44', '57.91')
('0.00', '0.00', '0.00')
('N/A', 'N/A', 'N/A')

A: data[:] only gets all elements of data in a list. This is the same as doing data[1:4] which gets elements starting from 1 and ending to 4: [1, 2, 3].
To do something for every element of the list, you need to use for loop.
list1, list2 = [], []
for list in data:
    list1.append(list[0])
    list2.append(list[1])


text:
Q: LINQ to Entities: query example Can someone show me how to get a user's usergroup relation in LINQ to Entities from this model?
I need get a list to be able to loop it after ward in such way:
foreach (QASModel.UserGroup usergroup in ...)

Bonus points if you can provide some examples on how to :

*

*get a user's role permission "path" based on the user ID

*get a user's role  based on it's ID

*get a all user(s) of a specific role based on the role ID
that would also help.

A: I think that this is what you're looking for:
int uID = 55;    //The user ID that you're looking for

//Assumption for the data context name
QASDataContext ctx = new QASDataContext();

//--(1)--
//Get the user's user groups
var user = (from u in ctx.Users
 where u.ID == uID
 select u).FirstOrDefault();

if(user != null)
{
    foreach(UserGroup in user.UserGroups)
    {
        //do your thing
    }

    //--(2)--
    //Get User's Role Permission Path(s)
    List<string> PermissionPaths = new List<string>();

    foreach(UserRole role in user.UserRoles)
    {
        foreach(UserRolesPer perPath in role.UserRolesPers)   //Can't see the whole table name
        {
            PermissionPaths.Add(perPath.Path);
        }
    }

    //You can use the PermissionPaths object now

    //--(3)--
    //Get a User's Role based on the User ID
    //Use the same user object from above
    UserRole uRole = user.UserRole;
}

//--(4)--
//Get a all user(s) of a specific role based on the role ID
int myRoleID = 43;

var role = (from r in ctx.UserRoles
    where r.ID == myRoleID
    select r).FirstOrDefault();

if(role != null)
{
    foreach(User u in role.Users)
    {
        // do something
    }
}

Please note that I didn't run this through a complier, but this should give you the basic idea of what you're looking for.

A: IEnumerable<UserGroup> userGroups = from ug in context.UserGroups
                                    from u in ug.Users
                                    where u.ID == [userID]
                                    select ug;

IEnumerable<string> userRoles = from ur in context.UserRoles
                                from rps in ur.UserRolesPermissions
                                where ur.UserId == id
                                select rps.Path;

IEnumerable<User> usersFromSpecificRole = from u in context.Users
                                          where u.UserRole.ID == [roleID]
                                          select u;

Didn't have time to check so if there are any problems please let me know and I'll try and fix them.


text:
Q: Not able to import classes from jar (already downloaded) using custom maven nexus repository I am able to successfully upload my jar to custom nexus repository. Now when i try to use this jar as dependency in another project, i see its downloaded but not able to import classes from it. As i type the name of class, it gives suggestion but as soon as it auto populates it gives error in red as below.

CurrencyExchange entity class which is downloaded, i can see it in maven jars. Attaching screenshot below for reference.

Below is my pom.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>TestIstio</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <java.version>17</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.intelliswift</groupId>
            <artifactId>currency-exchange-service</artifactId>
            <version>1.0.4</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>nexus-deployment-repo</id>
            <url>http://localhost:8081/repository/currency-exchange-release/</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
    </repositories>

</project>

Below is my settings.xml
<?xml version="1.0" encoding="UTF-8"?>

<settings xmlns="http://maven.apache.org/SETTINGS/1.2.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.2.0 https://maven.apache.org/xsd/settings-1.2.0.xsd">

  <proxies>

  </proxies>

  <servers>
    <server>
      <id>nexus-deployment-repo</id>
      <username>admin</username>
      <password>admin</password>
    </server>
  </servers>

  <mirrors>

  </mirrors>

  <profiles>

    <profile>
    <id>currency-exchange-release</id>
    <repositories>
    <repository>
        <id>nexus-deployment-repo</id>
        <url>http://localhost:8081/repository/currency-exchange-release/</url>
    </repository>
    </repositories>
    </profile>

  </profiles>

</settings>

I am new to nexus and not able to understand what am i doing wrong here. Can anyone please help in resolving this error. Thank you.


text:
Q: Configuring Spring OAuth2 expression handler methods for authorization server endpoints using java config In our app we would like to lock down the check_token endpoint so that only clients authenticated using client credentials can check the validity of tokens.
The documentation states that an expression handler is enabled by default when @EnableResourceServer is used, and has some instructions on how to set expression handling up using xml.
What do I need to do do have spring the evaluate the expression below using java config?
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    ...

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.checkTokenAccess("#oauth2.isClient()");
    }

    ...
}

A: The following isn't pretty, but it appears to work.
@EnableGlobalAuthentication
@Configuration
//@EnableAuthorizationServer
@Import({OAuth2AuthorizationServerConfiguration.SecurityConfiguration.class, AuthorizationServerEndpointsConfiguration.class})
public class OAuth2AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Configuration
    public static class SecurityConfiguration extends AuthorizationServerSecurityConfiguration {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().expressionHandler(new OAuth2WebSecurityExpressionHandler());
            super.configure(http);
        }
    }

AuthorizationServerSecurityConfiguration provides access to the HttpSecurity object, which is where the expression handler needs to be inserted.
steps:

*

*subclass AuthorizationServerSecurityConfiguration and set the expression handler

*drop the @EnableAuthorizationServer annotation (because it also imports AuthorizationServerSecurityConfiguration)

*import the new subclass of AuthorizationServerSecurityConfiguration

*import AuthorizationServerEndpointsConfiguration (it was initially imported by @EnableAuthorizationServer


text:
Q: Changing a value declared in a DIV using VB.Net I have the following code line which puts a progress bar on the screen. I found the code on CodePen website and I'm still learning so please bear with me. If I change the value in data-cp-percentage then the progress bar changes to that percentage. There's obviously CSS and Java too but I simply need to change the value in this line programatically in VB. I have tried giving the DIV an ID and but then still unsure how to change it.

So I tried..

And in VB I tried..
consistency.data-cp-percentage="22"
but I get error BC30456: 'data' is not a member of 'System.Web.UI.HtmlControls.HtmlGenericControl'.

A: Front-end

Code-behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    ' only setting the value once on initial load.
    If Not Page.IsPostBack Then
        Me.myDiv.Attributes("data-cp-percentage") = "1234"
    Else
        ' this would be where you could set a new value only on postbacks if you wanted
    End If
End Sub


text:
Q: Spring Data, how to merge entity before save? Suppose i have following classes:
@Entity
class Person {
    @Id
    private Integer id;

    @JoinColumn
    private Job job;
//getters.. . setters

@Entity
class Job {
    @Id
    private Integer id;

    @Column
    private String name;

    @Column
    private String description;
//getters... setters

If i will create Person objects, that looks like
{ id:0, job: {id: 1, name: "newName", description: null}}

Then it will be saved as is, i mean that column description will be owerwrited, and become null, how can i tell it, to update only fields that are not null, and merge old values into null fields?

A: no this is not possible, spring will assume that you have set the properties to null because you want to delete them, beacause of that you have to come up with your own solution
ex: -
you can read the previous object and set those details to the current object.


text:
Q: Troubleshooting using a function in a DataWindow computed field PB 6.5 I've written a function that accepts a string, looks up a value, and replies a string - and for some reason, I can't use it in our DataWindow that's a printed report. I've run the debugger and I see that it's walking through my function and is returning a string. I've done some searching that it's possible to use functions, but I'm stuck - we don't typically work on this application as it's  a bit "legacy" in the organization, so this might be something easy that I'm overlooking.
My computed field is "Suggested case: " + string(f_get_case_size(SKU)) and I'm seeing it go through the function - but nothing seems to work.