text:
Q: recursion binary search in a list of names I am trying to build a function that gets the index of an item form a list
names = [('Daisy','Fox'),('Josh','Belluga'),('Elin','Grosefield'),('Mike','Levinsan')]

this is the code
def find_name(lst,name,low,high):
if low >= high:
    return None
middle = (low + high) / 2
if lst[middle] == name:
    return middle
elif name < lst[middle]:
    return find_name(lst, name, low, middle)
else:
    return find_name(lst, name, middle + 1, high)

it works fine and all but the only problem that im having is when I define the low and high values to be equals for the index I want to get
for example
print find_name(names,('Josh','Belluga'),0,1)

returns none when it should return 1 for some reason

A: def find_name(lst,name,low,high):
    if high is None:
         high = len(lst) - 1

    if low > high:

         return False

    middle = (low + high) / 2
    if lst[middle] == name:
         return middle
    elif name < lst[middle]:
        return find_name(lst, name, low, middle-1)
    else:
         return find_name(lst, name, middle + 1, high)

names = [('Daisy','Fox'),('Josh','Belluga'),('Elin','Grosefield'),('Mike','Levinsan')]

print find_name(names, ('Josh','Belluga'), 0, 1)

Here is what you are looking for. Just compare your original code with this and you will see what you did wrong.


text:
Q: jquery function for images created dynamically I added images to the page dynamically now i need to add some function for this images.
I need to add click event for each image.
this is the code that adds the images (its inside a table that is also created dynamically):
for (var i = 0; i < numOfCandidates; i++) {
    var url = "/images/user"+(i+1) + ".png";
    cell23 = $('	').html( '');
    row23.append(cell23);
}

is there a way to add a click event with jquery for the images added?

A: Give images a class when you create them and use event delegation .on()
$(document).on('click','.myClass',function(){
     //function
});

Documentation

A:  for (var i = 0; i < numOfCandidates; i++) {
      var url = "/images/user"+(i+1) + ".png";
      cell23 = $('	').html( '');
      row23.append(cell23);
      $('#img'+(i+1)).click(function(){})
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do i multiply 2 columns on each row and sum all the results using Sequelize? I want to do something similar to:
  SELECT SUM(columnA*columnB)
  FROM someTable
  WHERE randomCondition = true

If i do this raw query using Sequelize.query() method it works. Problem is that i have been having another issue with SQLite and because of that i must avoid using raw queries.
When i do Model.sum('columnA*columnB') i get a syntax error. How is this supposed to be done using Sequelize?
How do i multiply 2 columns on each row and sum all the results using Sequelize?

A: As far as I know, the only way to do this is with Sequelize.literal. For example:
Sequelize.Model.findAll({
      attributes: [[db.sequelize.literal('SUM(col_a * col_b)'), 'result']],
    })


text:
Q: MySQL Search for words and its variations My Database tables are InnoDB and I am running MySQL 5.6.
I need to run a query on the database that returns more of a natural language result.
For example if I were to do a search like:
SELECT * FROM products WHERE MATCH (productName) AGAINST ('rose');

As expected I get all the products that contain the word rose.
BUT I need to be able to use variations of the word rose and get the same result. ex: roses
examples of rose results:

*

*Cabaret Rose

*Dbl. Madness Rose White

*New Day Rose Stripe


text:
Q: Ionic OpenStreetMap Integration with Leaflet I am integrating Ionic App with OSM using Leaflet. I have  inside page.html file and the rest of the code is inside my page.ts file. So, I am not using @ViewChild() in order find that div. As, Leaflet's L.map('map') should find it. I am initializing my map on ionViewDidLoad and making heavy work in ionViewDidEnter such as converting osm data which is retrieved from post request to geoJSON data, then putting a lot of Markers on the map. I am kind of trying to release the resources in ionViewDidLeave making this.map = null;. Is this a right implementation? Who can advise something in terms of implementation. Because the page is kind of freezing when I scroll.
ionViewDidLoad() {
    this.map = L.map('map').setView([41.0131, 28.9641], 18);
    L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
      maxZoom: 18
    }).addTo(this.map);
}

ionViewDidEnter() {
    this.filterProvider.getData(resource).subscribe(data => {
      if (this.map !== null) {
        L.geoJSON(osmtogeojson(data), {
          style: function(feature) {
              return {
                color: "#0288D1"
              };
          },
          pointToLayer: function(feature, latlng) {
            return L.marker(latlng, {
              icon: L.icon({
                iconUrl: 'assets/map/' + resource.toLowerCase() +'.png'
              })
            });
          },
          onEachFeature: function(feature, layer) {
            layer.bindPopup(JSON.stringify(feature.properties));
          }
        }).addTo(this.map);
      }
    });
}

ionViewDidLeave() {
   this.map = null;
   this.selectedResource = null;
}

A: some time ago I published in codigo200 blog, an example of Ionic3 + Leaflet that solves your problem. The code is in github, you can read the explanation here.
// atributes

map: L.Map;
center: L.PointTuple;
tempIcon: any;

ionViewDidLoad() {

this.center = [23.03, -81.57]; //a place in Cuba

this.map = L.map('map', {
center: this.center,
zoom: 13
});

//Adicionamos la ruta de OSM.
L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: '© Código 200'
})
.addTo(this.map);

this.mensaje("Pulse sobre un punto en el mapa para añadir un nuevo lugar");

this.tempIcon = L.icon({
iconUrl: 'assets/imgs/marker.png',
shadowUrl: '',
iconSize: [32, 32], // size of the icon
shadowSize: [0, 0], // size of the shadow
iconAnchor: [32, 32], // point of the icon which will correspond to markers location
shadowAnchor: [0, 0], // the same for the shadow
popupAnchor: [32, 20] // point from which the popup should open relative to the iconAnchor
});

this.map.on('click', (e) => { this.onMapClick(e) });

}

onMapClick(e) {
let tempMarker = L.marker(e.latlng, { icon: this.tempIcon })
.on('click', this.showMarkerMenu, this)  // Al hacer click, ejecutamos this.showMarkerMenu y le pasamos el contexto (this)
.addTo(this.map);

this.mensaje("Coordinate: " + e.latlng);

}

So, I hope that solves your problem, remember that you need link leaflet in index.html.


text:
Q: remove gibberish prefix from a string a = "aajfkdfvf_valid_name0"
b = "gdhdhsdsdeeeeex_valid_name1"

How do I remove the gibberish from my string before valid so that I have something like this -
valid_name0
valid_name1

A: If your strings always contains valid word, then you can try something like -
a = "aajfkdfvf_valid_name0"
b = "gdhdhsdsdeeeeex_valid_name1"
for s in (a, b):
    print(s[s.rfind('valid'):])

So, even if the prefix contains _ or substring valid in it, the output will be correct. Though if your valid substring contains the word valid multiple times, then this will not work

A: You can use a split join approach for this.
Try this:
a = "aajfkdfvf_valid_name0"
valid_a = '_'.join(a.split('_')[1:])
# 'valid_name0'
# can use maxsplit to split only once at the first _ and then take the remaining part of the string
another_valid_a = a.split('_',1)[1]
# valid_name0

Basically what this is doing is that it is splitting the original string at the _, then ignoring the first element and joining the remaining part again using _.

A: We can try using re.sub here:
a = "aajfkdfvf_valid_name0"
b = "gdhdhsdsdeeeeex_valid_name1"
inp = [a, b]
output = [re.sub(r'^[^_]+_', '', i) for i in inp]
print(output)  # ['valid_name0', 'valid_name1']

A: The other approaches seem a bit too over-engineered for this task, at least in my opinion.
If you already know that the gibberish comes before the first underscore _  character, you can just do a single str.split and discard the first split result:
a = "aajfkdfvf_valid_name0"
b = "gdhdhsdsdeeeeex_valid_name1"

def clean_string(s: str) -> str:
    return s.split('_', 1)[1]

print(clean_string(a))  # valid_name0
print(clean_string(b))  # valid_name1

A: If you're sure that just a '_' is your need, a string split will help:
fixed_a = '_'.join(a.split('_')[1:])

The worst case is that this pattern is not the only one you're looking at. Then, check this:
You need to know exactly what your 'valid_name' looks like, you could make a REGEX to achieve your need.
Check for standards, patterns and all those.
I'm pretty sure if is there a pattern, a Regex can handle.
I recommend this site to do so.


text:
Q: How to add next button to Java Selenium code Here is my code:
    private final static String tablelast   = "(//table[contains(@class,'datatable')])[last()]";
    private final static String next        = "(//span[text()='Next']/following::table[last()]";
    private static String scrape() throws Exception {
         int row_num = 1;
         String rows = "";

         WebElement table_element = driver.findElement(By.xpath(tablelast));
         List<WebElement> rowsList = table_element.findElements(By.tagName("tr"));
         List<WebElement> columnsList = null;

         while (!next.contains("disabled")) {
             driver.findElement(By.xpath(next)).click();
             Thread.sleep(1000);
             for (WebElement row : rowsList) {
                 columnsList = row.findElements(By.tagName("td"));
                 for (WebElement column : columnsList) {
                    rows += column.getText() + ", ";
                 }
                 rows = rows + "\n";
             }
         }
    return rows;
    }

This throws the following error:
Exception in thread "main" org.openqa.selenium.InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression (//span[text()='Next']/following::table[last()] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '(//span[text()='Next']/following::table[last()]' is not a valid XPath expression.

I am trying to test second data table of this WEBSITE.

*

*The error seems to incorrect NEXT button xpath

*The Next button code is also require attention. I am afraid its wrong

Please help me to fix these two issues
UPDATE-1
while(count ==3) {

                 for(WebElement trElement : tr_collection){
                 List<WebElement> td_collection = trElement.findElements(By.xpath("td"));
                 col_num++;
                   for(WebElement tdElement : td_collection){
                       rows += tdElement.getText()+"\t";
                       col_num++;
                    }
                 rows = rows + "\n";
                 System.out.println("rows-->"+rows);
                 row_num++;
                }

                 driver.findElement(By.xpath(next)).click();
                 count++;
         }

A: It is an 'a' tag, not span
//a[text()='Next']/following::table[last()]

A: To get the next button and disabled next button which is for the last table you can identify xpath for that and then check size of the disabled next if 0 then continue and click next else break. use infinite loop. hope this helped.
code:
private final static String tablelast   = "(//table[contains(@class,'datatable')])[last()]";
private final static String next        = "(//table[contains(@class,'datatable')])[last()]/preceding::a[text()='Next'][1]";
private final static String disablednext        ="(//table[contains(@class,'datatable')])[last()]/preceding::span[contains(@class, 'disabled') and text()='Next'][1]";

private static String scrape() throws Exception {
         int row_num = 1;
         String rows = "";

         WebElement table_element = driver.findElement(By.xpath(tablelast));
         List<WebElement> rowsList = table_element.findElements(By.tagName("tr"));
         List<WebElement> columnsList = null;

         while (true)
         {   Thread.sleep(1000);
             if (driver.findElements(By.xpath(disablednext)).size()==0)
             {
                 ((JavascriptExecutor) driver).executeScript("arguments[0].click();",driver.findElement(By.xpath(next)));
                 Thread.sleep(1000);
                 for (WebElement row : rowsList) {
                   columnsList = row.findElements(By.tagName("td"));
                   for (WebElement column : columnsList) {
                      rows += column.getText() + ", ";
                 }
                 rows = rows + "\n";
             }
             }
                 else
                 {
                     break;
                 }
             }
         return rows;
    }


text:
Q: Django - Add rows to MySQL database So I already have a database setup with a few columns and a few rows already inserted in.  I'm trying to create a view that you would just input information into a form and press Submit, then a row would be added to the MySQL database with the information you just typed in.
I believe you can do this with admin, but I would like to try without admin and I'm not sure if this is possible?  I've been using the MySQL commandline to add rows as of now..

A: Of coures this is possible this is a building block for data driven websites.  You can use a ModelForm as Daniel suggested (they offer built in validation and HTML markup for FREE) to easily map your model to a front end form.  It would probably be beneficial to start with django tutorial or documentation first.
At the the very basic, all you have to do is instantiate your model
new_entry = YourModel(name='me', age='222', about='stackoverflow')

then save it
new_entry.save()

This adds it as a new row to your db.
https://docs.djangoproject.com/en/dev/topics/db/models/

A: Why would it not be possible?
You probably want a modelform (but see the general form introduction first).

A: Try out this example of Generic Views: http://postneo.com/2005/08/17/django-generic-views-crud (assumes a model named Task)
With Generic Views you get Insert, Update and Delete for free without any real work. give it a try and let me know what you think.
from django.conf.urls.defaults import *

info_dict = {
    'app_label': 'tasks',
    'module_name': 'tasks',
}

urlpatterns = patterns('',
    (r'^tasks/create/?$', 'django.views.generic.create_update.create_object', info_dict ),
    (r'^tasks/update/(?P<object_id>\d+)/?$', 'django.views.generic.create_update.update_object', info_dict),
    (r'^tasks/delete/(?P<object_id>\d+)/?$', 'django.views.generic.create_update.delete_object', info_dict ),
)

Django Docs: https://docs.djangoproject.com/en/1.2/ref/generic-views/#create-update-delete-generic-views


text:
Q: How to search for and report IP in all files using Linux shell script I am very new at this:
This Linux script currently works as designed.
I would like to alter or rewrite it to continue to search all 3 files for the IP and report accordingly i.e., "IP is in group 1 and 3" or
"IP is in group 1
IP is in group 3"
Looking for some help understanding how to structure it to do so. Thanks.
clear
echo -n "Enter the IP address"
read ip
echo ""
echo "Searching for $ip"
sleep 1
echo ""
if grep -wq $ip /system/config/channels/group1.yml; then
    echo "IP is in group1"
    echo ""
elif grep -wq $ip /system/config/channels/group2.yml; then
    echo "IP is in group2"
    echo ""
elif grep -wq $ip /system/config/channels/group3.yml; then
    echo "IP is in group3"
    echo ""
else
    echo "IP not found. Exiting..."
    echo ""
fi

A: As @tink said just remove elif
Add a var for the not found message
clear
echo -n "Enter the IP address"
read ip
echo ""
echo "Searching for $ip"
sleep 1
echo ""
not_found=true
if grep -wq $ip /system/config/channels/group1.yml; then
    echo "IP is in group1"
    echo ""
    not_found=false
fi
if grep -wq $ip /system/config/channels/group2.yml; then
    echo "IP is in group2"
    echo ""
    not_found=false
fi
if grep -wq $ip /system/config/channels/group3.yml; then
    echo "IP is in group3"
    echo ""
    not_found=false
fi
if $not_found; then
    echo "IP not found. Exiting..."
    echo ""
fi


text:
Q: Implement loop in the SQL query, not in PHP? Is it possible to write the loop in the SQL query?
Or is it only possible in PHP? (write loop in php, where I execute the query at every iteration)
Example:
Is it possible for a query, to contain a loop like this:
LOOP(50) { UPDATE Table SET X=X+1 }

Or I have to write it in php, and call the single query at every iteration?

A: You can create a table that contains sequential numbers. Then you can use a JOIN with this table to make the query loop.
UPDATE Table
CROSS JOIN Numbers AS n
SET X = X + 1
WHERE n.number BETWEEN 1 AND 50

A: You could create a stored procedure that accepts a parameter for the number of loops.
MSSQL syntax:
DECLARE @cnt INT = 5;
DECLARE @i INT = 0;
DECLARE @x INT = 0;

WHILE @i < @cnt
BEGIN
 SET @x = @x + 2;
 SET @i = @i + 1;
END

MySql syntax:
WHILE i < cnt DO
...
END WHILE


text:
Q: What are $a$ and $b$ when the zeropoints of $f(z)=(a+bi)z+2-i=0$ is at $1-i$? $f(z)=(a+bi)z+2-i$.
What are the values of a and b when $1-i$ is the zeropoint of f?
$f(z)=(a+bi)z+2-i=0$
$(a+bi)(1-i)+2-i=0$
$a+bi-ai-bi^2+2-i = 0$
$(a+b+2)+(-a+b-1)i=0$
I don't know what the next steps are.

A: So far, so good!  The next step is to realize the real and imaginary parts must each be $0$, and solve the resulting linear system, which is
$a + b + 2 = 0, \tag{1}$
$-a + b - 1 = 0; \tag{2}$
it is easy to see that
$a = \dfrac{-3}{2}; \; b = \dfrac{-1}{2} \tag{3}$
is the solution.
And it's as simple as that!
Hope this helps.  Cheerio,
and as always,
Fiat Lux!!!


text:
Q: gcc warning in pointer to function (incompatible pointer type) I need help with gcc warning,looks like im doing something wrong here
unsigned long convert_syslog(char *date,int year) {
    char withyear[1024];
    struct tm tm;
    time_t epoch = (time_t) NULL;

    snprintf(withyear,sizeof(withyear),"%s %i",date,year);
    if(strptime(withyear,"%b %d %H:%M:%S %Y",&tm)) {
            epoch = mktime(&tm);
            printf("%u\n",epoch);
    }
    return epoch;
}

unsigned long convert_tai64(char *date,int year) {
    char hex[16];
    unsigned long u;
    strcpy(hex,"0x");
    strcat(hex,strndup(date+8,8));
    return strtoul (hex,NULL,16);
}

unsigned long convert_nagios(char *date,int year) {
    return strtoul(date,NULL,10);
}

unsigned long convert_clf(char *date,int year) {
    struct tm tm;
    time_t epoch = (time_t)NULL;

    if(strptime(date,"%d/%b/%Y:%H:%M:%S",&tm)) {
            epoch = mktime(&tm);
    }
    return epoch;
 }

typedef unsigned long (*func)(char *data,int year);

func *convert_date(int pos) {
    switch(pos) {
            case 0: return &convert_syslog;
            case 1: return &convert_tai64;
            case 2: return &convert_clf;
            case 3: return &convert_nagios;
            default: return NULL;
    }
}

gives me warnings in convert_date
pcre_search.c:57: warning: return from incompatible pointer type  (case 0)
pcre_search.c:58: warning: return from incompatible pointer type   (...)
pcre_search.c:59: warning: return from incompatible pointer type   (...)
pcre_search.c:60: warning: return from incompatible pointer type   (default)

A: You should return func not func*.

A: The func typedef is already a pointer to a function so convert_date can be declared like this:
func convert_date(int pos) { ...

Function names (in C) are already pointers so no need for the & in the return statements. Just do this:
func convert_date(int pos) {
       switch(pos) {
           case 0: return convert_syslog;
           case 1: return convert_tai64;
           case 2: return convert_clf;
           case 3: return convert_nagios;
           default: return (func)NULL;
       }
   }


text:
Q: Resize terminal and scrolling problem with ncurses I'm programming in C using ncurses libraries (it's the first time) and I've two problems. I'm on ubuntu with the default terminal (gnome terminal).
1) I need to resize the terminal. I used resizeter() and resize_term(), but they fail.
2) I use scrollok() function and the problem is that I lose scrolled lines (when I get back with wscrl(), there are blank lines).
#include <ncurses.h>

int main() {

WINDOW *win, *win2;

int i;
char c;

initscr();
cbreak();
noecho();

win=newwin(8,20,1,1);
box(win,0,0);
win2=newwin(6,18,2,2);
scrollok(win2,1);
wrefresh(win);
wrefresh(win);

for(i=0;i<15;i++){
    c=wgetch(win2);
    if(c=='u'){
        wscrl(win2,-1);
        wrefresh(win2);
    }
    else{
        wprintw(win2,"%c\n",c);
        wrefresh(win2);
    }
}

delwin(win);
delwin(win2);
endwin();

return 0;
}

A: *

*You can't resize the terminal window from ncurses. The functions you mention resize the part of the terminal window that is painted on by curses. The idea is you catch the SIGWINCH signal and call resizeterm in the handler when the user resizes the window from outside the application (using the mouse, probably).

*This is intended behavior, though poorly documented in ncurses and in the Unix standard/POSIX. NetBSD's curses docs state it explicitly:

If n is positive then stdscr
  is scrolled up.  n lines are lost
  from the top of stdscr and n blank
  lines are inserted at the bottom.  If
  n is negative then stdscr is scrolled down.  n blank lines are
  inserted at the top of stdscr and
  n lines are lost from the bottom.

So you'll have to manually save input and reprint it when scrolling.

A: POSIX does not cover this case, because the curses document is not part of POSIX.  The Open Group happens to maintain documentation for both:

*

*X/Open CURSES Issue 4 Version 2 (overview)

*X/Open Curses, Issue 4 Version 2 (documentation)

*The Open Group Base Specifications Issue 7
IEEE Std 1003.1, 2013 Edition (aka "POSIX")

*signal.h (note that SIGWINCH is absent)

As noted in the manual page for resizeterm, you should not call that function from within a signal handler, because it calls "unsafe" functions.  The topic of "unsafe" functions is discussed in several places; that in gcc's documentation would do for a start.
Regarding documentation, @larsmans appears to be quoting from scroll(3), but not citing comparable links for ncurses and "POSIX".  For what it's worth:

*

*ncurses (seems to address the points implied to be unique to NetBSD)

*X/Open (is necessarily more general, as it is intended to cover different implementations)

Back to OP's question:

*

*the sample program does not show OP's use of resizeterm nor of resize_term.  It is not stated, but presumably OP resized the terminal window and the program did not respond. The manual page for resizeterm is clear enough that ncurses does not cause the terminal to resize.  For that (on some terminals), one can use the -s option of resize (a utility program for xterm).  If successful, that resizes the terminal, which in turn sends a SIGWINCH.
ncurses has a predefined signal handler for that, but at the application level, handling KEY_RESIZE is the recommended way.  There are several programs in ncurses-examples which do this.

*moving the lines up in a window necessarily moves some out of the window.  That implies that lines are shifted into the window to replace those which have left. A "window" is just that: a limited-size view of data.  For views with different size, the developer is advised to use "pads" (see manual page).  The notes in the scroll manual page mention some issues with the color of blanks (the replacement lines).  It is up to the application whether to leave the replacements blank or fill them with the application's data.  Curses does not do that automatically (not even for pads).

A: You can't resize the terminal window from ncurses but you can resize the terminal which the resize system call.
#include <ncurses.h>
#include <stdlib.h>

int main(int argc, char *argv[]){
    WINDOW *ventana1;
    system("resize -s 30 80");
    initscr();
    start_color();
    ventana1 = newwin(15, 50, 0, 0);
    init_pair(1,COLOR_YELLOW,COLOR_BLUE);
    init_pair(2,COLOR_BLUE, COLOR_YELLOW);
    wbkgd(ventana1,COLOR_PAIR(1));
    wprintw(ventana1, "POLLO");
    wrefresh(ventana1);
    wgetch(ventana1);
    wgetch(ventana1);
    system("resize -s 20 60");
    wbkgd(ventana1,COLOR_PAIR(2));
    wprintw(ventana1, "POLLO");
    wrefresh(ventana1);
    wgetch(ventana1);
    wgetch(ventana1);
    system("resize -s 35 85");
    system("clear");
    wbkgd(ventana1,COLOR_PAIR(1));
    wprintw(ventana1, "POLLO");
    wrefresh(ventana1);
    wgetch(ventana1);
    wgetch(ventana1);
    delwin(ventana1);
    endwin();
    system("resize -s 25 75");
}


text:
Q: Generalized wave equation I asked this question here:
https://math.stackexchange.com/questions/1160134/generalized-wave-equation
but did not get any response. I hope it is more suitable on mathoverflow.
I am interested in understanding as much as I can about the following partial differential equation, which is a generalization of the 1D wave equation:
$$\frac{\partial^2 u(x,t)}{\partial t^2} + \zeta(t)\frac{\partial u(x,t)}{\partial t}= \alpha(t)\frac{\partial^2 u(x,t)}{\partial x^2} + \beta(t)\frac{\partial u(x,t)}{\partial x} + \gamma(t)u(x,t) + \alpha(t)f(x),\quad x\in(-\infty,\infty),\quad t\geq 0$$
where $\zeta(t)\geq 0$, $\beta(t)\geq 0$, and $\alpha(t)\geq 0$. This equation has initial data $u(x,0)$ and velocity $\partial_t u(x,0)$. Here are a few examples:

*

*When $\zeta(t) = \beta(t) = \gamma(t) = f(t) = 0$, it is the standard 1D wave equation. Thus, the influence of the initial data travels at a speed $\alpha(t)$.

*When $\zeta(t) = \gamma(t) = f(t) = 0$, it is the 1D Klein-Gordon equation. Thus, the influence of the initial data travels at a speed $\leq\alpha(t)$. Should I be thinking about dispersion relations in this case?

*When $\beta(t) = \gamma(t) = f(t) = 0$, it is the 1D wave equation with dampening. Should I be thinking about lack of energy conservation in this case?

*When $\zeta(t) = \beta(t) = \gamma(t) = 0$ and $f(x) = \delta_0(x)$ ($\delta_0 =$ delta function at origin), it is the 1D wave equation with plucking at $x = 0$?
I would like to understand properties of the solution for any choice of $\alpha, \beta,\gamma,\zeta,f$. What tools are there to help me? When is there a conservation of energy statement?  Thank you very much in advance.

A: Using your coordinates, we can define a Lorentzian metric $g = - dt^2 + \frac{1}{\alpha(t)} dx^2$. Then your equation takes the form
\begin{equation}
  \square u + v^i \partial_i u + \gamma u = h ,
\end{equation}
where $\square = \frac{1}{\sqrt{-\det g}} \partial_i \sqrt{-\det g} g^{ij} \partial_j$ is the (d'Alambert) wave operator for the metric $g$, $v^i \partial_i = -(\zeta(t) - \alpha'(t)/2\alpha(t))\partial_t + \beta(t)\partial_x$ is a vector field, $\gamma = \gamma(t)$ and $h = \alpha(t) f(t)$. If the Lorentzian metric $g$ and the coefficients $v$, $\gamma$ and $h$ are arbitrary functions, you have the most general form of a linear inhomogeneous second order normally hyperbolic equation. You have simply chosen very special kinds of coefficients that depend only on time.
These kinds of equations have been extensively studied and you can find lots of information about them, for instance, in the thorough monographs

*

*Bär, Ginoux & Pfäffle, Wave Equations on Lorentzian Manifolds and Quantization (EMS, 2007).

*Waldmann, Geometric Wave Equations (2012).


text:
Q: Problem with DirectionsApiRequest and apiRequest.setCallback Wrote a method for creating and overlaying a route between two points. The problem is that when it's triggered in normal mode (without breakpoints), it causes NullPointerException or IllegalStateException, but when I run my app in Debug-mode it throws nothing and works correctly.
I'm sorry for my english (i'm from Russia) and I apologize for formulation of the question, I'm still not really familiar with stackoverflow.
Here is my method:
    List<com.google.maps.model.LatLng> path;
    DirectionsRoute[] routes;
    DisplayMetrics metricsB = new DisplayMetrics();
    int width = metricsB.widthPixels;
    int heith = metricsB.heightPixels;
    PolylineOptions line = new PolylineOptions();
    LatLngBounds.Builder latLngBuilder = new LatLngBounds.Builder();
    String dist;

    public void TravelCost(LatLng startGeoPoint, LatLng stopGeoPoint) throws InterruptedException,
ApiException, IOException {

        GeoApiContext geoApiContext = new GeoApiContext.Builder()
                .apiKey(maps_api_key)
                .build();

        DirectionsApiRequest apiRequest = DirectionsApi.newRequest(geoApiContext);

        apiRequest.origin(new com.google.maps.model.LatLng(startGeoPoint.latitude, startGeoPoint.longitude));
        apiRequest.destination(new com.google.maps.model.LatLng(stopGeoPoint.latitude, stopGeoPoint.longitude));
        apiRequest.mode(TravelMode.DRIVING); //set travelling mode

        apiRequest.setCallback(new com.google.maps.PendingResult.Callback<DirectionsResult>() {
            @Override
            public void onResult(DirectionsResult result) {
                routes = result.routes;
                path = routes[0].overviewPolyline.decodePath();
                dist = routes[0].legs[0].distance.humanReadable;
                for (int i = 0; i < path.size(); i++) {
                    line.add(new com.google.android.gms.maps.model.LatLng(path.get(i).lat, path.get(i).lng));
                    latLngBuilder.include(new com.google.android.gms.maps.model.LatLng(path.get(i).lat, path.get(i).lng));
                }
            }

            @Override
            public void onFailure(Throwable e) {
                Toast.makeText(MapsActivity.this, "Error!", Toast.LENGTH_SHORT).show();
            }
        });

        line.width(16f).color(R.color.purple_500);
        map.addPolyline(line);
        LatLngBounds latLngBounds = latLngBuilder.build();
        CameraUpdate track = CameraUpdateFactory.newLatLngBounds(latLngBounds, 1080, 1920, 25);
        map.moveCamera(track);
    }

Here are errors from log:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.plukash.travelcost, PID: 19561
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
        at android.view.View.performClick(View.java:7448)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
        at android.view.View.performClickInternal(View.java:7425)
        at android.view.View.access$3600(View.java:810)
        at android.view.View$PerformClick.run(View.java:28305)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
        at android.view.View.performClick(View.java:7448)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
        at android.view.View.performClickInternal(View.java:7425)
        at android.view.View.access$3600(View.java:810)
        at android.view.View$PerformClick.run(View.java:28305)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.IllegalStateException: no included points
        at com.google.android.gms.common.internal.Preconditions.checkState(Unknown Source:29)
        at com.google.android.gms.maps.model.LatLngBounds$Builder.build(Unknown Source:21)
        at com.plukash.travelcost.MapsActivity.TravelCost(MapsActivity.java:305)
        at com.plukash.travelcost.MapsActivity.onMapSearch(MapsActivity.java:142)
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
        at android.view.View.performClick(View.java:7448)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
        at android.view.View.performClickInternal(View.java:7425)
        at android.view.View.access$3600(View.java:810)
        at android.view.View$PerformClick.run(View.java:28305)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

This is XML-layout file.
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/bottom_sheet_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:orientation="horizontal">

            <EditText
                android:id="@+id/LocSearch"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="4"
                android:hint="Куда поедем?"
                android:inputType="text"
                tools:ignore="Autofill,HardcodedText" />

            <Button
                android:id="@+id/search_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="0.5"
                android:onClick="onMapSearch"  <------- OnClick Method
                android:text="Search"
                tools:ignore="HardcodedText" />

        </LinearLayout>

        <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MapsActivity"
            tools:ignore="FragmentTagUsage" />
    </LinearLayout>

    <include layout="@layout/bottom_sheet" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="15dp"
        android:src="@drawable/go_px"
        app:layout_anchor="@+id/bottom_sheet"
        app:layout_anchorGravity="top|end"
        tools:ignore="ContentDescription" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

And here is a On-click method for Search-button that calls for "TravelCost" method.
public void onMapSearch(View view) throws InterruptedException, ApiException, IOException {
        boolean bool = TrafficJam();
        try {
            Button search = findViewById(R.id.search_button);

            String location = locationSearch.getText().toString();
            List<Address> addressList;

            Geocoder geocoder = new Geocoder(this);
            try {
                addressList = geocoder.getFromLocationName(location, 1);

            } catch (IOException e) {
                e.printStackTrace();
                Toast toast = new Toast(this);
                toast.setText("Введите корректный адрес!");
                toast.show();
                return;
            }
            if (addressList != null) {
                Address address = addressList.get(0);
                latLng = new LatLng(address.getLatitude(), address.getLongitude());
                map.addMarker(new MarkerOptions().position(latLng).title("Marker"));
                map.animateCamera(CameraUpdateFactory.newLatLng(latLng));
                //Убирать ли текст в поисковом поле?
                //locationSearch.setText("");
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(search.getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            } else {
                Toast toast = new Toast(this);
                toast.setText("Введите адрес!");
                toast.show();
            }
        } catch (Exception e) {
            Toast toast = new Toast(this);
            toast.setText("Введите корректный адрес!");
            toast.show();
            return;
        }
        if (checker == 1) {
            startpoint = latLng;
            checker += 1;
            locationSearch.setText("");
            locationSearch.setHint("Куда поедем?");
        } else if (checker == 2) {
            LatLng endpoint = latLng;
            locationSearch.setText("Откуда поедем?");
            checker = 1;
            TravelCost(startpoint, endpoint); <-------------- Method call
        }
    }

UPD
Need to return values from other Thread.
DirectionsRoute[] routes;
    public void TravelCost(LatLng startGeoPoint, LatLng stopGeoPoint) {
        GeoApiContext geoApiContext = new GeoApiContext.Builder()
                .apiKey("AIzaSyA9qY28oZ-4TTdDt1jgxdCKLYh9T8Kh0Ss")
                .build();

        DirectionsApiRequest apiRequest = DirectionsApi.newRequest(geoApiContext);
        apiRequest.origin(new com.google.maps.model.LatLng(startGeoPoint.latitude, startGeoPoint.longitude));
        apiRequest.destination(new com.google.maps.model.LatLng(stopGeoPoint.latitude, stopGeoPoint.longitude));
        apiRequest.mode(TravelMode.DRIVING);
        apiRequest.language("Russian");//set travelling mode

        AppExecutors.getInstance().networkIO().execute(() -> {
            apiRequest.setCallback(new com.google.maps.PendingResult.Callback<DirectionsResult>() {
                @Override
                public void onResult(DirectionsResult result) {
                    routes = result.routes;
<---- **routes here contains values**
                }

                @Override
                public void onFailure(Throwable e) {
                    Toast.makeText(MapsActivity.this, "Error!", Toast.LENGTH_SHORT).show();
                }
            });
        });
<---- **Here routes is nullarray.**
        List<com.google.maps.model.LatLng> path = routes[0].overviewPolyline.decodePath();
        dist = routes[0].legs[0].distance.humanReadable;
        for (int i = 0; i < path.size(); i++) {
            line.add(new com.google.android.gms.maps.model.LatLng(path.get(i).lat, path.get(i).lng));
            latLngBuilder.include(new com.google.android.gms.maps.model.LatLng(path.get(i).lat, path.get(i).lng));
        }

        line.width(16f).color(R.color.purple_500);
        map.addPolyline(line);
        LatLngBounds latLngBounds = latLngBuilder.build();
        CameraUpdate track = CameraUpdateFactory.newLatLngBounds(latLngBounds, 1080, 1920, 25);
        map.moveCamera(track);
    }

A: Your problem seems to be with the android:onClick the system is not finding the method and it's throwing an error because of it.
My hypothesis is that this is happening because you are running the app with proguard enabled, proguard may be changing the method name, and this will cause this exception.
I would advise using a click listener since it's considered to be bad practice to use the android:onClick
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Button button = findViewById(R.id.search_button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onMapSearch(v);
            }
        });

        // implementation of an onclick listener using a lambda instead
        button.setOnClickListener(v -> onMapSearch(v));
    }

Also, you may consider deleting the view parameter in onMapSearch since it's not used anymore
EDIT
To fix the android.os.NetworkOnMainThreadException you need to run the network call outside of the main thread, note that it's not advisable to use AsyncTask since it's has been deprecated for a long time now.
Worker example
public class AppExecutors {

    private static final Object LOCK = new Object();
    private static AppExecutors sInstance;
    private static Executor processor;
    private final Executor diskIO;
    private final Executor networkIO;
    private final Executor mainThread;

    private AppExecutors(Executor diskIO, Executor networkIO, Executor mainThread){
        this.diskIO = diskIO;
        this.networkIO = networkIO;
        this.mainThread = mainThread;
    }

    public static AppExecutors getInstance(){
        if(sInstance == null){
            synchronized (LOCK){
                sInstance = new AppExecutors(Executors.newSingleThreadExecutor(),
                        Executors.newFixedThreadPool(3),
                        new MainThreadExecutor());
            }
        }
        return sInstance;
    }

    public Executor diskIO() {
        return diskIO;
    }

    public Executor networkIO() {
        return networkIO;
    }

    public Executor getMainThread() {
        return mainThread;
    }

    private static class MainThreadExecutor implements Executor {
        private final Handler mainThreadHandler = new Handler(Looper.getMainLooper());

        @Override
        public void execute(@NotNull Runnable command) {
            mainThreadHandler.post(command);
        }
    }
}

Usage
AppExecutors.getInstance().networkIO().execute(() -> {
    // Network call goes here
});


text:
Q: How do I stop one pivot table from affecting a chart created from a different pivot table? I am working on processing average CPU loads on some of my servers in Excel 2013. I have my raw data in a table named RawData which contains the CPU load and a timestamp in each row. From RawData I created two pivot tables (loadDaily and loadHourly). In loadDaily, I set the timestamp as a row lable, and set it to group by Days, Hours, Minutes and created a nice chart of my CPU load from it. Now the problem I am having is when I try to group the timestamp field in loadHourly by Hours only, it also applies the grouping to my other pivot table (loadDaily) and my pivot chart linked to that. How do I make the grouping on the timestamp field only apply to loadHourly?

A: Okay, I answered my own question after toying with it some more. I noticed that after creating my initial groups, in the Pivot Table field list there were new fields (Hours and Days). In my second table, instead of adding the raw timestamp field to it I found out I can use the Hours field that was created when I made my group for the first time.


text:
Q: Wouldn't remove for a non dynamic unsorted array list be O(n)? This falls under "a software algorithm" from stackoverflow.com/help/on-topic, in this case, a software algorithm to remove an item from an unsorted array list
This is from my class when we discussed big oh runtime for different data structures

My question is about remove value for unsorted non dynamic array. Shouldn't this be O(n) based on how we implemented it(see below)
 public void remove(E value) {
    int index = getIndex(value);
    elementData[index] = elementData[size - 1];
    elementData[size - 1] = null;
    size--;
}
public int getIndex(E value) {
   for (int i = 0; i < size; i++) {
       if (elementData[i].equals(value)) {
           return i;
       }
   }
   return -1;
}

While I would agree with the fact that this code segment
elementData[index] = elementData[size - 1];
    elementData[size - 1] = null;
    size--;

would run in O(1). What I learned from my other question Why is clear an O(n) operation for linked list? was that Big Oh "conciders everything that has to be done to run the code", which in this case includes the getIndex function which is bound by O(n).
Because the remove method consists of O(n) and O(1), it will run in O(n) time.
Does everyone agree with my assessment or did I miss something?

A: Yes you are right. Your getIndex function runs in O(n) (O(1/2 * n) on average, but we generally aren't interested in constants).  The other code in your remove function runs in constant time, so the total runtime is O(n + c), where c is a constant, meaning the total run time is O(n).


text:
Q: Override the default Add/Edit site forms of the Network Panel in custom plugin My requirement is to add couple of custom fields in the add/edit a site forms without touching the WordPress core. I tried to copy the site-new.php from /wp-admin/network and paste it into my custom plugin but it fails due to many dependencies. I dont think so it is good exercise to copy and paste the whole network folder inside the plugin.
I also tried to callout this hook but instead of override, it just show me the fields underneath of the form. I guess I need to add hook when users submit the form. but couldn't find the hook that I need to callout to save additional fields data in DB.
 add_action('network_site_new_form',  array($this, 'add_extra_new_site_fields'));

Added this function
function add_extra_new_site_fields()
{
    ?>
    <form method="post" action="<?php echo network_admin_url( 'site-new.php?action=add-site' ); ?>" novalidate="novalidate">
        <?php wp_nonce_field( 'add-blog', '_wpnonce_add-blog' ); ?>

                <?php _e( 'Site s Address (URL)' ); ?> *

                    <?php if ( is_subdomain_install() ) { ?>
                        <input name="blog[domain]" type="text" class="regular-text" id="site-address" aria-describedby="site-address-desc" autocapitalize="none" autocorrect="off" required />.<?php echo preg_replace( '|^www\.|', '', get_network()->domain ); ?>
                        <?php
                    } else {
                        echo get_network()->domain . get_network()->path
                        ?>
                        <input name="blog[domain]" type="text" class="regular-text" id="site-address" aria-describedby="site-address-desc" autocapitalize="none" autocorrect="off" required />
                        <?php
                    }
                    echo '
' . __( 'Only lowercase letters (a-z), numbers, and hyphens are allowed.' ) . '
';
                    ?>

                <?php _e( 'Site Title' ); ?> *
                <input name="blog[title]" type="text" class="regular-text" id="site-title" required />

            <?php
            $languages    = get_available_languages();
            $translations = wp_get_available_translations();
            if ( ! empty( $languages ) || ! empty( $translations ) ) :
                ?>

                    <?php _e( 'Site Language' ); ?>

                        <?php
                        // Network default.
                        $lang = get_site_option( 'WPLANG' );

                        // Use English if the default isn't available.
                        if ( ! in_array( $lang, $languages ) ) {
                            $lang = '';
                        }

                        wp_dropdown_languages(
                            array(
                                'name'                        => 'WPLANG',
                                'id'                          => 'site-language',
                                'selected'                    => $lang,
                                'languages'                   => $languages,
                                'translations'                => $translations,
                                //'show_available_translations' => current_user_can( 'install_languages' ) && wp_can_install_language_pack(),
                            )
                        );
                        ?>

            <?php endif; // Languages. ?>

                <?php _e( 'Admin Email' ); ?> *
                <input name="blog[email]" type="email" class="regular-text wp-suggest-user" id="admin-email" data-autocomplete-type="search" data-autocomplete-field="user_email" aria-describedby="site-admin-email" required />

<?php _e( 'A new user will be created if the above email address is not in the database.' ); ?>
<?php _e( 'The username and a link to set the password will be mailed to this email address.' ); ?>

                <?php _e( 'Account ID' ); ?> *
                <input name="blog[account_id]" type="input" class="regular-text" id="admin-account_id" required />

        <?php
        /**
         * Fires at the end of the new site form in network admin.
         *
         * @since 4.5.0
         */
        //do_action( 'network_site_new_form' );

        submit_button( __( 'Add Site' ), 'primary', 'add-site' );
        ?>
    </form>
    <?php
}

give me your suggestions.

A: Adding Markup To The Add New Site Form
You can add HTML markup to that form like this:
add_action(
    'network_site_new_form',
    function() {
        ?>

Hello World

        <?php
    }
);

Adding Markup To The Edit Site Forms
No. This cannot be done via PHP.
For the site edit info screen, no hooks exist to do this.
However, you might be able to add a new tab however via the network_edit_site_nav_links filter, allowing you to create a custom network admin page that's passed the site ID as a URL parameter. However you would need to recreate the tabs via network_edit_site_nav and do all the saving and displaying yourself.
What About Saving Extra Inputs When Creating a Site?
Sort of..

*

*No dedicated hook is available to save those fields

*The hook for adding the HTML is not a part of the table the existing fields are in, they will not be aligned

*There is a hook for before and after a user is created if no user exists with the chosen administrator email, but it happens before the site is created

You can use the wp_insert_site hook to do work on the site after its creation, however you should check your fields are present, it may not even be a web request, or the network admin:
do_action( 'wp_insert_site', $new_site );

Also be wary, WP will be in installation mode when this happens, things that are normally available may not be available. What those things are is unclear.

My advice is don't do this. The best way to customize areas of the network admin, is to remove them completely, then re-implement them using brand new network admin pages via the admin menu API.
The network admin APIs weren't intended for extension, and the network admin was not built to be extensible in the way's you're wanting. Something that would normally be trivial to develop should be considered top tier super hard.
Additionally, even if you could store those values, there is no UI for viewing them, and the existing UI's cannot be extended. You will have to build it from scratch.


text:
Q: Linking in MathOverflow account with the others? I have my SO, Meta and Area 51 accounts 'linked', but not my MathOverflow, even though I used the same OpenID account for all of them?  Why isn't MathOverflow also 'part of the family' ?

A: MathOverflow is a Stack Exchange 1.0 site, which is not technically linked to The Stack Overflow Trilogy, nor Stack Exchange 2.0.


text:
Q: Suppose there are k points, no 3 of which are collinear. What is the upper bound on the number of quadrilaterals we can form? We understand that the number of triangles possible is given by kC3, since any selection of 3 points uniquely determine a triangle.
This is not true for quadrilaterals though, since for selections where 1 of the points lie within the other 3, we can obtain 3 quadrilaterals. The value kC4 merely gives us a lower bound, which occurs whenever all k points lie on a circle (or whenever none of the k points lie within any possible triangle, but this condition is guaranteed by a placing them on a circle).
Now, my question is: what is the upper bound on the number of quadrilaterals we may form? Under what configuration of the k points will this value be the actual answer? Even more generally, is there an explicit formula in k and n giving us the upper bound for an n-gon and is there a rule which will help us determine how these k points should be placed?
Thank you in advance.

A: Your question is equivalent to determining the rectilinear crossing number of the complete graph on $k$ vertices. This is an open problem! I don't know much about it, so I'll refer you to a survey article from 2011: http://www.csun.edu/~ba70714/survey.pdf
Edit: Here's the explicit connection. For every four vertices, consider the three pairs of rectilinear edges between them. Either exactly one pair crosses, in which case there is only one simple quad that passes through the vertices, or no pairs cross, in which case there are three simple quads that pass through the vertices. So if there are $c$ crossings, then the number of simple quads is
$$3\binom k4-2c.$$
For example, the rectilinear crossing number of $K_6$ is $3$, so the maximum number of simple quads formed by $6$ points is
$$3\binom 64-2\times3 = 45-6=39.$$
Here's a drawing of $K_6$ with only $3$ crossings, which I stole from this PDF:

I guess if you're patient enough, you can actually count $39$ simple quads in there. I haven't tried this myself. :)


text:
Q: Pass object by reference to Node module I cannot seem to pass an object by reference to a Node module. For example, in my main server.js, I have:
var test = {};
var ctrlFiles = require('./app/controllers/files')(test);

Further down in server.js, I intercept a HTTP request, and change the test object:
app.use(function(req, res){
    console.log('2. updating test');
    test.name = 'some value';
    next();
});

Even further down in server.js I define the route and pass the request to my files controller:
app.get('/files', function(req, res) {
    console.log('3. in files route, test is ', test);
    ctrlFiles.getUserFiles(req, res);
});

And the files controller is:
module.exports = function(testReference) {

    var test = testReference;

    console.log('1. test is ', test);

    return {

        getUserFiles: function(req, res) {

            console.log('4. in getUserFiles and test is ', test);

        }
    };
}

The logs looks like:
1. test is  {}
2. updating test
3. in files route, test is  { cookie:
   { name: 'some value' }
4. in getUserFiles and test is  {}

test is always empty when I do a GET request to "/files". How do I pass test by reference so when it gets updated outside of my files controller, its updated within the controller too?


text:
Q: html data tables and headers misaligned when using ajax query In my flask application I've switched from having a logtable built by flask and served to the page on reload to an ajax call.
The ajax is working fine but for some reason the headers and data are misaligned and have different fonts (as below)

The html that gets built in flask is built this way:
def htmlbuild(data):
    html="
Time	Username	Action	"
    for line in data:
        html+= "
%s	%s	%s
" % (line[1], line[2], line[3])
    html+="
"
    return html

and in JavaScript/JQuery the table is built this way.
(function ajaxLogCalls(){    $.ajax({ url: "{{ url_for('.ajaxLogGrab') }}", dataType: 'json',
    success: function(data, textStatus, xhr){
        $("#logtable").empty();
        $("#logtable").append("
Time	Username	Action	");
        $(data.logs).each(function(i, el) {
            var listem = el.datestamp + "	" + el.username + "	" + el.action;
            $("#logtable").append("
" + listem + "
");
        });
        $("#logtable").append("
");
    }
    });
    setTimeout(ajaxLogCalls, 2000)
    })();

functionally, they're basically identical.
I've had to create a new div for the table but I can't see any css that would be fighting against this. Plus, as I was targetting by ID I tried as a form and ul rather than a div and got the same result.
The CSS that applies to tables is:
th {
background-color: #006099;
color: white;
 }
tr:nth-child(even) {background-color: #f2f2f2}
th, td {
border-bottom: 1px solid #ddd;
padding: 5px;
text-align: left;
}
table {
width: 100%;
}

Interestingly when I tried applying something to the new div to change the font size it changed the data but not the headers.. As i said this only seems to happen with the data that's built by ajax.
 #logtable {
font: 70px Georgia, sans-serif;
}

Can anyone point me in the right direction as to what might have happened?

A: Found out the difference but still not sure why. The flask output had no carriage return but the javascript append did, so I made it all into one long string instead and now it renders properly.
(function ajaxLogCalls(){    $.ajax({ url: "{{ url_for('.ajaxLogGrab') }}", dataType: 'json',
    success: function(data, textStatus, xhr){
        $("#logtable").empty();
        var output1 = "

Time	Username	Action
"
        $(data.logs).each(function(i, el) {

            var output2 = "
" + el.datestamp + "	" + el.username + "	" + el.action + "
";

            output1 += output2;
        });
        $("#logtable").append(output1 + "
");
    }
    });
    setTimeout(ajaxLogCalls, 2000)
    })();

Still weird though.


text:
Q: Groupby and smallest on more than one index I have a data frame as follows
REG LOC DATE        SUM
1   A1  19-07-20     10
1   B1  19-07-20     25
1   C1  19-07-20     20
2   A2  19-07-20     25
2   B2  19-07-20     30
2   C3  19-07-20     45
1   A1  20-07-20     15
1   B1  20-07-20     20
1   C1  20-07-20     30
2   A2  20-07-20     10
2   B2  20-07-20     15
2   C3  20-07-20     30
1   A1  21-07-20     25
1   B1  21-07-20     35
1   C1  21-07-20     45
2   A2  21-07-20     20
2   B2  21-07-20     30
2   C3  21-07-20     40

I want to find LOC with smallest 2 value of SUM for each region and date combination. For example for Date 19-7-20 and region 1, smallest is Loc A1 and C1 and for region 2 is A2 and B2. I am able to do it for one level with following code but not able to introduce another level in the code.
groupby(level=0,group_keys=False).apply(lambda x: x.nsmallest())

How can I do it for 2 levels not just one level up when I want n smallest values for a combination.
Thanks


text:
Q: Computing an 'odd' determinant I'm wondering how to compute an 'odd' determinant:
${D_n} = \det \left[ {\begin{array}{*{20}{c}}
  {{a_n}}&x&x& \cdots &x \\
  y&{{a_{n - 1}}}&x& \cdots &x \\
  y&y&{{a_{n - 2}}}&x& \vdots  \\
   \vdots & \vdots &y& \ddots &x \\
  y&y& \cdots &y&{{a_1}}
\end{array}} \right]$
I tried Laplace expansion but still couldn't get a clue...
Also I wonder if there is a 'neat' expression for the result...
Any help will be appreciated:)


text:
Q: Google TV change pointer click sound programmatically I'm working on a game for Google TV (Sony NSZ-GS7) which uses the touchpad to move things around.
AFAIK it is not possible (yet) to change or disable the pointer Arrow-bitmap programmatically, which is pretty shitty from game design perspective, is it at least possible to disable the default click-sound played by the device on every click so i can replace it with my own?

A: Try to disable the standard onClick noise using setSoundEffectsEnabled(false);


text:
Q: GraphicsMagick zoom and sample function performance difference We use GM to do image compressing, and observe a significant performance difference between zoom and sample functions, which we suppose to do the same thing.
When using zoom function for a 68k image, a process could consume all the cpu time for all cores(12 core, 2.4G Hz machine), the throughput is 65/seconds, response time is 469 ms on average, load by top command is around 11, cpu usage is close to 100%
When using sample function in the same environment, 24 process work together providing throughput close to 1000/seconds, response time is 37 ms on average, load by top command is around 3, cpu usage fluctuates between 50% and 80%
the official document for these two functions is very simple as below:
sample
Resize image by using pixel sampling algorithm:
void            sample ( const Geometry &geometry_ )
zoom
Zoom (resize) image to specified size:
void            zoom ( const Geometry &geometry_ )
the effects after the image processing are similar, but the difference is huge.

*

*Could anyone explain the different circumstances of using these two functions, since we might choose sample over zoom because of the performance issue

*Further, could anyone tell me why zoom is so cpu-time-consuming.

A: Since there was less performance with GraphicsMagick, perhaps there was some system-dependent issue like cache line thrashing.  The -sample option uses simple point sampling in which each point in the output image selects one point from the input image.  The -zoom option does horizontal/vertical filtering using a specified filter (-filter) so it provides high quality (depending on the filter).  For really large images I recommend using -scale which is a windowed filter which produces results almost as good as -zoom but using only one CPU core and still quite fast.


text:
Q: AngularJS, clear input text with button Using AngularJS, what is the proper way to clear the value of a text field? I have an input field with a button next to it. The user types in it and hits the button to clear or reset it.
I know I can add an ng-click event on the button itself and call a function, but I am not sure that is the correct way to do it.
Right now all I have is:
<input type="text" ng-model="searchQuery" />
<button class="btn" <!--do something here maybe?-->>
  <i class="icon-search" ng-class="{'icon-refresh': searchQuery.length}"></i>
</button>

A: ng-click is the "Angular" way to do it
just declare a function in your scope and attach it to the button's ng-click
If you wanted something more advanced, then the "Angular way" suggests creating a directive to wrap the functionality you want in it and attach it somehow to your button (depending on how you implement your directive)
If you want an example, let me know in the comments

A: I had the same problem. Maybe simple is best?
No need for calling a method in the controller. No need for a directive either. Just a brief statement to clear the model that you declared in the input tag. Like this:
<input ng-model="searchQuery">
<button class="btn" ng-click="searchQuery = ''"></button>

You may also hide the clear button when there is no text in the input, like this:
<button class="btn" ng-show="searchQuery.length" ...></button>

By the way, maybe a directive that would put the clear button inside of the input box would be nice. Something like you see on the iPhone.


text:
Q: Closing the edge of Table in latex I have a table a latex table that simply won't close in the top right of the table (see picture). Not sure what the issue is but I appreciate your help.
\begin{tabular}{|l|c|c|c|llll|llll|}

\hline
              &            & Age & Income & \multicolumn{4}{c}{Temperature (F$^\circ$)} &  \multicolumn{4}{c}{Trip Miles (miles)}   \\
              \hline
MSA          & Population & Avg & Avg    & Med.   & Avg  & 10\%  & 90\%  & Med.  & Avg  & 10\%  & 90\%   \\

\hline
New York      & 9,821,147    & 50  & 106    & 57       & 56   & 32    & 77    & 2.9     & 6.2  & 0.3   & 17.1  \\
Los Angeles   & 6,434,177    & 47  & 101    & 67       & 64   & 57    & 69    & 2.9     & 6.0  & 0.4   & 16.4  \\
Chicago       & 4,653,591    & 48  & 98     & 52       & 50   & 22    & 73    & 2.9     & 6.1  & 0.4   & 16.9  \\
Dallas        & 3,654,402    & 47  & 96     & 67       & 64   & 44    & 85    & 3.6     & 6.9  & 0.6   & 18.4  \\
Washington    & 3,320,895    & 46  & 122    & 59       & 57   & 35    & 79    & 2.8     & 5.9  & 0.3   & 16.4  \\
Houston       & 3,198,729    & 47  & 102    & 70       & 68   & 52    & 84    & 3.6     & 7.0  & 0.6   & 19.1  \\
Philadelphia  & 2,915,178    & 50  & 91     & 57       & 56   & 32    & 78    & 3.4     & 6.3  & 0.4   & 16.5  \\
Miami         & 2,912,751    & 52  & 84     & 79       & 77   & 68    & 84    & 3.2     & 5.9  & 0.5   & 15.1  \\
Atlanta       & 2,868251    & 47  & 89     & 63       & 61   & 43    & 80    & 4.0     & 7.2  & 0.6   & 18.8  \\
Boston        & 2,572,454    & 48  & 102    & 54       & 51   & 29    & 74    & 2.6     & 5.8  & 0.3   & 15.7  \\
San Fran. & 2,371,803    & 47  & 128    & 61       & 58   & 49    & 63    & 2.4     & 5.7  & 0.3   & 15.9  \\
Phoenix       & 2,182,537    & 51  & 87     & 75       & 72   & 54    & 93    & 3.5     & 6.9  & 0.6   & 19.1 \\
Seattle       & 1,997,545    & 47  & 108    & 51       & 52   & 40    & 68    & 3.2     & 5.9  & 0.4   & 15.4 \\
Detroit       & 1,980,465    & 49  & 87     & 52       & 51   & 25    & 74    & 4.0     & 7.3  & 0.6   & 19.9  \\

\hline \hline

\end{tabular}
\end{table}

A: You're missing a | from last multicolumn, replace it with \multicolumn{4}{c|}{Trip Miles (miles)}.

\documentclass[a4paper]{article}
\begin{document}
\begin{table}
\begin{tabular}{|l|c|c|c|llll|llll|}
\cline{3-12}
              \multicolumn{2}{c|}{}            & Age & Income & \multicolumn{4}{c}{Temperature (F$^\circ$)} &  \multicolumn{4}{c|}{Trip Miles (miles)}   \\
              \hline
MSA          & Population & Avg & Avg    & Med.   & Avg  & 10\%  & 90\%  & Med.  & Avg  & 10\%  & 90\%   \\

\hline
New York      & 9,821,147    & 50  & 106    & 57       & 56   & 32    & 77    & 2.9     & 6.2  & 0.3   & 17.1  \\
Los Angeles   & 6,434,177    & 47  & 101    & 67       & 64   & 57    & 69    & 2.9     & 6.0  & 0.4   & 16.4  \\
Chicago       & 4,653,591    & 48  & 98     & 52       & 50   & 22    & 73    & 2.9     & 6.1  & 0.4   & 16.9  \\
Dallas        & 3,654,402    & 47  & 96     & 67       & 64   & 44    & 85    & 3.6     & 6.9  & 0.6   & 18.4  \\
Washington    & 3,320,895    & 46  & 122    & 59       & 57   & 35    & 79    & 2.8     & 5.9  & 0.3   & 16.4  \\
Houston       & 3,198,729    & 47  & 102    & 70       & 68   & 52    & 84    & 3.6     & 7.0  & 0.6   & 19.1  \\
Philadelphia  & 2,915,178    & 50  & 91     & 57       & 56   & 32    & 78    & 3.4     & 6.3  & 0.4   & 16.5  \\
Miami         & 2,912,751    & 52  & 84     & 79       & 77   & 68    & 84    & 3.2     & 5.9  & 0.5   & 15.1  \\
Atlanta       & 2,868251    & 47  & 89     & 63       & 61   & 43    & 80    & 4.0     & 7.2  & 0.6   & 18.8  \\
Boston        & 2,572,454    & 48  & 102    & 54       & 51   & 29    & 74    & 2.6     & 5.8  & 0.3   & 15.7  \\
San Fran. & 2,371,803    & 47  & 128    & 61       & 58   & 49    & 63    & 2.4     & 5.7  & 0.3   & 15.9  \\
Phoenix       & 2,182,537    & 51  & 87     & 75       & 72   & 54    & 93    & 3.5     & 6.9  & 0.6   & 19.1 \\
Seattle       & 1,997,545    & 47  & 108    & 51       & 52   & 40    & 68    & 3.2     & 5.9  & 0.4   & 15.4 \\
Detroit       & 1,980,465    & 49  & 87     & 52       & 51   & 25    & 74    & 4.0     & 7.3  & 0.6   & 19.9  \\

\hline \hline

\end{tabular}
\end{table}

\end{document}


text:
Q: Static analysis: 2 errors were found during analysis. SQL Error Static analysis:
2 errors were found during analysis.
An opening bracket followed by a set of values was expected. (near "ALTER" at position 571)
Unexpected token. (near "ALTER" at position 571)
MySQL said: Documentation
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''eyecolor', 'flag') VALUES
(1, 'Иван', 'Петров', '173', 'Кафяв', ' at line 5
-- phpMyAdmin SQL Dump
-- version 5.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time:  7 апр 2020 в 09:51
-- Версия на сървъра: 10.4.11-MariaDB
-- PHP Version: 7.4.3

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `personbase`
--

-- --------------------------------------------------------

--
-- Структура на таблица `persons`
--

CREATE TABLE `persons` (
  `id` int(11) NOT NULL,
  `name` varchar(25) COLLATE utf32_bin NOT NULL,
  `family` varchar(25) COLLATE utf32_bin NOT NULL,
  `height` varchar(30) COLLATE utf32_bin NOT NULL,
  `haircolor` varchar(30) COLLATE utf32_bin NOT NULL,
  `eyecolor` varchar(30) COLLATE utf32_bin NOT NULL,
  `flag` tinyint(4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf32 COLLATE=utf32_bin;

--
-- Схема на данните от таблица `persons`
--

INSERT INTO `persons` (`id`, `name`, `family`, `height`, `haircolor`, 'eyecolor', 'flag') VALUES
(1, 'Иван', 'Петров', '173', 'Кафяв', 'Син', 0),
(2, 'Стефан', 'Петров', '173', 'Кафяв', 'Син', 1),
(3, 'Калин', 'Петров', '173', 'Кафяв', 'Син', 0),
(4, 'Димитър', 'Петров', '173', 'Кафяв', 'Син', 1),
(5, 'Алекс', 'Петров', '173', 'Кафяв', 'Син', 0),
(6, 'Иван', 'Петров', '173', 'Кафяв', 'Син', 1),
(7, 'Мартин', 'Петров', '173', 'Кафяв', 'Син', 0),

--
-- Indexes for dumped tables
--

--
-- Indexes for table `persons`
--
ALTER TABLE `persons`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `persons`
--
ALTER TABLE `persons`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text:
Q: Methods of characteristics? The function $u(x, t)$ satisfies $\frac{du}{dt} $ + $\frac{du}{dx}$ = $0$ in $x > 0, t > 0$
Subject to the initial conditions $u(x, 0) = sin(x)$, $x > 0$ and the boundary condition $u(0, t) = sin(t)$, $t > 0.$
Determine the values of $u$ in the whole of the quarterplane $x > 0, t > 0$
What i did:
$\frac{dt}{ds} = 1$ -------> t = s + a, but $t=0$ means $s=o$ so $t=s$
$\frac{dx}{ds} = 1$ -------> $x = s + b$ subject to $x(0) = \xi $. This leads to $\xi = x - t$
$\frac{du}{ds} = 0$ -------> $u(s)= c = f(\xi)$  = $f(x-t)$ = $u(x,t)$
Then using the inital condition:
$u(x,0) = f(x) = sin(x) $
Now of course when i use the boundary condition it doesn't make sense :/
So i was just wondering where i went wrong and if my general technique is right?
Many thanks!

A: Your general technique is correct - the equation $u_t + u_x = 0$ means that $u$ is constant along the characteristic curves $x-t = \mathrm{const}$. In other words, $u(x,t) = f(x-t)$ for some function $f$.
As far as I understand, you only consider the characteristic curves starting at points $(0,x)$ with $x>0$. This is of course not sufficient, as it only determines $f$ for positive arguments and $u$ in the region $\{ (x,t): 0 < t < x \}$.
If you also consider starting points $(t,0)$ with $t>0$, you end up with $u(x,t) = \sin(|x-t|)$. This is not a $C^1$ function (only Lipschitz), but it satisfies the equation in the weak sense.
Note that in this case, the distinction between initial conditions and boundary conditions is immaterial - variables $x$ and $t$ play exactly the same role.


text:
Q: How can I access ddev's database with external database browsers or similar tools? As far as I know, DDEV provides configuration options for phpMyAdmin to comfortably work with containered MySQL/MariaDB databases. But I would rather like to use a different tool like e.g. phpStorm or DBeaver or such. Is there a way to make my wish come true?
Supplementing the docker-compose configuration I exposed port 3306, accordingly.
version: '3.6'

services:
  web:
    ports:
      - 3306:3306

Trying to connect to a containered MariaDB database from my client host looks like the following.
$ mariadb --host=foo.ddev.site --user=db --password=db --database=db
ERROR 2013 (HY000): Lost connection to MySQL server at 'handshake: reading initial communication packet', system error: 11

A: The database port is already exposed in ddev, so can easily be used with many, many external tools.
For example, ddev mysql gives you direct access, and there are also ddev sequelpro and ddev sequelace and ddev tableplus, and there's an example in the custom commands showing how to do it with mysqlworkbench (See ~/.ddev/commands/host/mysqlworkbench.example).
All of those grab the already-exposed db port.
ddev describe on any project tells you how to access the port.
The host_db_port setting in your project's .ddev/config.yaml can be used to lock down the exposed port so you can easily use it with PhpStorm.
This article also goes through some of the many ways you can access the database using ddev, https://ddevhq.org/ddev-local/ddev-local-database-management/


text:
Q: Why Shiny app does not work when app.R from another app is saved in a new one? I have noticed that whenever I want to create a new shiny app I have to create a new app.R file in the new app folder. If I 'save as' the app.R from another shiny app in the new folder and modify it for the current usage, the UI is created but server doesn't seem to work. Why is that?

A: Look at what happens when you press the "Run App" button -- the command that gets executed in the console is shiny::runApp(appDir). It doesn't run specifically the app.R file, but it runs the whole directory. This is the first hint at why you're seeing this behaviour - Shiny expects to run an app as a directory rather than as a file, so when you have a different app file in the same folder, the original one is probably still getting run.
This lead me to look into the runApp function. If you look at the documentation for runApp you'll see the first parameter is appDir:

The directory of the application. Should contain server.R, plus,
  either ui.R or a www directory that contains the file index.html.
  Alternately, instead of server.R and ui.R, the directory may contain
  just app.R. Defaults to the working directory. Instead of a directory,
  this could be a list with ui and server components, or a Shiny app
  object created by shinyApp.

So there you have it - runApp (and therefore the "Run App" button) uses a directory as the parameter for the Shiny app. Shiny expects this directory to either have server.R and ui.R OR  just app.R, but it doesn't say what the behaviour is when you have a combination of that or more than one app or non of the above, so you should avoid that.


text:
Q: In React, how can I get the value of Element's attribute using Ref? I want to do
function MyComponent () {

    const myRef = useRef(null)

    const myValue = useMemo(() => (myRef.current.someKey), [])

    return

}

But it doesn't work because sometimes myRef is not loaded yet when setting myValue (so myRef.current is null), and I have no idea what should I do to reset  myValue when the loading is done.

A: function MyComponent() {
  const [myValue, setMyValue] = useState("Loading...");
  const myRef = useRef(null);

  useEffect(() => {
    setMyValue(myRef?.current.dataset.value);
  }, [myRef]);

  return (

      {myValue}

  );
}


text:
Q: Dynamically fetch messages published to a Google pub/sub topic in android I am building a app with in-app subscriptions. I have implemented Real Time developer notifications as recommended by Google by properly configuring as mentioned over there. Whenever I purchase or cancel a subscription, SubscriptionNotification is published to the Pub/Sub topic as expected. But I am not able to get that message in the app. My requirement is that whenever message is published to the topic same message must be received inside app without any explicit request. And I have a pull subscription of Google's Pub/Sub api. So does pull suit here or should I go for push? So any kind of help would be highly appreciated.

A: You would not want to receive the Cloud Pub/Sub message in the application itself. In order to accomplish this, you would need to have a subscription per application instance and Cloud Pub/Sub is not designed to scale that way: the limit is 10,000 subscriptions per topic. Additionally, each instance of the application would receive all notifications for all users, which is likely not what you want.
The purpose of the real time developer notifications is for your service to receive notifications of changes to users' entitlements. Then, when users make requests to your service from the application, it can respond appropriately based on the subscription features that should be enabled. If you want an application instance to be notified when entitlements change, you'd have to implement that separately in the service in response to the Cloud Pub/Sub notifications. You could use something like Firebase Cloud Messaging to send the appropriate messages to individual application instances. However, you would still need to have a service that acts as a subscriber to Cloud Pub/Sub and gets the messages from the topic for developer notifications and then passes these along to Firebase Cloud Messaging.


text:
Q: Number of sectors in my sda1 After running bootinfoscript, I read on the log:

sda1: __________________________________________________________________________

File system:       ntfs
Boot sector type:  Windows XP: NTFS
Boot sector info:  According to the info in the boot sector, sda1 has
                   78124992 sectors, but according to the info from
                   fdisk, it has 81920000 sectors.
Operating System:  Windows XP
Boot files:        /boot.ini /bootmgr /Boot/BCD /ntldr /NTDETECT.COM

Windows and Linux boot fine on my system. Should I worry about this discrepancy?
Is there a way to fix this?
I've already tried using Boot Repair, and I also followed this guide about TestDisk, but I didn't solve.

A: Chances are the discrepancy is the result of a partition- or filesystem-resizing operation that changed one of those things but not the other.
To elaborate, partitions are simple data structures that define a range of sectors on the disk that may be used for a particular purpose. Filesystems, OTOH, are much more complex data structures that help you store files. Filesystems are often stored on partitions, and partitions often hold filesystems, but this linkage isn't absolute. A partition, by its nature, defines a size -- 81,920,000 sectors, in your case. Filesystems also have sizes, which are defined independently of the partition -- 78,124,992 sectors, in your case. The two can get out of whack if a partition is resized without resizing the contained filesystem or if a filesystem is resized without resizing the containing partition. Tools to do both tasks exist in Linux, although some tools create or resize both partitions and filesystems simultaneously.
I'm not 100% positive, but I think that the following command, typed in Linux as root or using sudo, should fix the discrepancy:
ntfsresize /dev/sda1

This command resizes NTFS. The ntfsresize man page is a little unclear, but these tools usually resize to the size of the containing partition if no size is specified.
Note, however, that resizing filesystems is inherently dangerous. Given that there's only about a 5% discrepancy, and it's of a filesystem that's smaller than its partition, it's probably safer to just leave it be. A filesystem that's smaller than its partition poses no danger to the system; you're just losing a little disk space. If the filesystem were larger than its partition, that would pose a risk of data loss, but that's not the case for you.


text:
Q: Javascript and forms This is my html:
<form id="questions">

Answer: <input type="text" name="textbox1" size="30" />
<button onclick="answers()">Submit</button>

</form>

This is my javascript:
function answers () {
   var x = document.getElementById("questions");
   var y = x.elements["textbox1"].value;
   document.write("Hello " +y);
}

My issue is when I click the button, it flashes the document.write string for a split second. I'm not sure why it's only happening for a split second.

A: try putting
type="button"

in your button element

A: *

*Don't use document.write(); it will replace the page.
Instead, use the DOM APIs.

*You need to return false from the handler to prevent the default action of submitting the form.

A: Even though there is no action on your form, some browsers still reload the page on submission, and my guess is this is what's happening.
If you return false on the onclick event, it will stop the default behaviour. You should add an action to the form too, to comply with standards.
<form id="questions" action="#">

Answer: <input type="text" name="textbox1" size="30" />
    <button onclick="return answers()">Submit</button>

</form>

function answers () {
   var x = document.getElementById("questions");
   var y = x.elements["textbox1"].value;
   document.write("Hello " +y);
   return false;
}

A: return false to avoid the form to be submited
  function answers () {
  var x = document.getElementById("questions");
   var y = x.elements["textbox1"].value;
  document.write("Hello " +y);
  return false;
 }


text:
Q: How do I use compiler intrinsic __fmul_? I am writing a massively parallel GPU application using CUDA. I have been optimizing it by hand. I received a 20% performance increase with __fdividef_(x, y), and according to The Cuda C Programming Guide (section C.2.1), using similar functions for multiplication and adding is also beneficial.
The function is stated as this: __fmul_[rn,rz,ru,rd](x,y).
__fdividef(x,y) was not stated with the arguments in brackets. I was wondering, what are those brackets?
If I run the simple code:
int t = __fmul_(5,4);

I get a compiler error about how __fmul_ is undefined. I have the CUDA runtime included, so I don't think it is a setup thing; rather it is something to do with those square brackets. How do I correctly use this function? Thank you.
EDIT: I should clarify, the compiler is the CUDA-compiler NVCC.

A: You should specify rounding mode with ru (rounding up) or rd (rounding down). There is no function __fmul_ but available function signatures are __fmul_rd or __fmul_ru.

A: CUDA Programming Guide explains the suffixes:

*

*_rd: round down.

*_rn: round to nearest even.

*_ru: round up.

*_rz: round towards zero.

See CUDA's Single Precision Intrinsics documentation for details on these functions.


text:
Q: understanding constant pools in Javassist I am using Javassist to extend certain classes at runtime .
In a couple of places (in the generation code) I need to create instances of the Javassist ConstPool class.
For example, to mark a generated class as synthetic, I wrote something like this:
CtClass ctClassToExtend = ... //class to extend
CtClass newCtClass = extend(ctClassToExtend, ...); //method to create a new ctClass extending ctClassToExtend
SyntheticAttribute syntheticAttribute = new SyntheticAttribute(ctClassToExtend.getClassFile().getConstPool()); //creating a synthetic attribute using an instance of ConstPool
newCtClass.setAttribute(syntheticAttribute.getName(), syntheticAttribute.get()); //marking the generated class as synthetic

This is working as expected, but I have certain doubts about this being entirely correct. Concretely, my main question is:
Is the call to CtClass.getClassFile().getConstPool() the correct way to get a constant pool in this example?. If not, what is the general proper way to get the right instance of a constant pool when creating a new class at runtime using Javassist?
Also, I am a bit lost regarding what is happening behind the curtains here: Why do we need a constant pool to create a instance of a synthetic attribute ?, or in general, of any other kind of class attributes ?
Thanks for any clarification.

A: Don't know if you're still interested in the answer, but at least might help others that
find this question.
First of all, a small suggestion to everyone that starts creating/modifying bytecode
and needs more in-depth information on how the JVM internals works, the JVM's specification documentation might look bulky and scary at first but it's invaluable help!

Is the call to CtClass.getClassFile().getConstPool() the correct way to get a constant pool in this example?.

Yes, it is. Each Java Class has a single constant pool, so basicaly every time you need to access the constant
pool for a given class you can do ctClass.getClassFile().getConstPool(), although you must keep in mind the
following:

*

*In javassist the constant pool field from CtClass is an instance field, that means that if you have two CtClass objects
representing the same Class you'll have two diferrent instances of constant pool (even though they represent
the constant pool in the actual class file). When modifying one of the CtClassinstances you must use the
associated constant pool instance in order to have the expected behaviour.

*There are times where you might not have the CtClass but rather a CtMethod or a CtField which don't let you backtrace to the CtClass instance, in such cases you can use ctMethod.getMethodInfo().getConstPool() and ctField.getFieldInfo().getConstPool() to retrieve the correct constant pool.
Since I've mentioned CtMethod and CtField, keep in mind that if you want to add attributes to any of these, it can't be through the ClassFile Object, but through MethodInfo and FieldInfo respectively.

Why do we need a constant pool to create a instance of a synthetic attribute ?, or in general, of any other kind of class attributes ?

To answer this question, I'll start quoting section 4.4 regarding JVM 7 specs (like I said, this documentation is quite helpful):

Java virtual machine instructions do not rely on the runtime layout of classes, interfaces, class instances, or arrays. Instead, instructions refer to symbolic information in the constant_pool table.

With this in mind, I think the best way to shed some light on this subject is to look at a class file dump. We can achieve this by running the following command:
javap -s -c -p -v SomeClassFile.class

Javap comes with the java SDK and it's a good tool to analyse classes at this level, the explanation of each switch

*

*-s : Prints internal type signature

*-c : Prints byte code

*-p : Prints all class members (methods and fields, including the private ones)

*-v : Be verbose, will print tack information and class constant pool

Here's the output for test.Test1 class that I modified via javassist to have the synthetic attribute both in the class and in the injectedMethod
Classfile /C:/development/testProject/test/Test1.class
Last modified 29/Nov/2012; size 612 bytes
MD5 checksum 858c009090bfb57d704b2eaf91c2cb75
Compiled from "Test1.java"
public class test.Test1
SourceFile: "Test1.java"
Synthetic: true
minor version: 0
major version: 50
flags: ACC_PUBLIC, ACC_SUPER

Constant pool:
#1 = Class              #2             //  test/Test1
#2 = Utf8               test/Test1
#3 = Class              #4             //  java/lang/Object
#4 = Utf8               java/lang/Object
#5 = Utf8               <init>
#6 = Utf8               ()V
#7 = Utf8               Code
#8 = Methodref          #3.#9          //  java/lang/Object."<init>":()V
#9 = NameAndType        #5:#6          //  "<init>":()V
#10 = Utf8               LineNumberTable
#11 = Utf8               LocalVariableTable
#12 = Utf8               this
#13 = Utf8               Ltest/Test1;
#14 = Utf8               SourceFile
#15 = Utf8               Test1.java
#16 = Utf8               someInjectedMethod
#17 = Utf8               java/lang/System
#18 = Class              #17            //  java/lang/System
#19 = Utf8               out
#20 = Utf8               Ljava/io/PrintStream;
#21 = NameAndType        #19:#20        //  out:Ljava/io/PrintStream;
#22 = Fieldref           #18.#21        //  java/lang/System.out:Ljava/io/PrintStream;
#23 = Utf8               injection example
#24 = String             #23            //  injection example
#25 = Utf8               java/io/PrintStream
#26 = Class              #25            //  java/io/PrintStream
#27 = Utf8               println
#28 = Utf8               (Ljava/lang/String;)V
#29 = NameAndType        #27:#28        //  println:(Ljava/lang/String;)V
#30 = Methodref          #26.#29        //  java/io/PrintStream.println:(Ljava/lang/String;)V
#31 = Utf8               RuntimeVisibleAnnotations
#32 = Utf8               Ltest/TestAnnotationToShowItInConstantTable;
#33 = Utf8               Synthetic
{
public com.qubit.augmentation.test.Test1();
Signature: ()V
flags: ACC_PUBLIC

Code:
  stack=1, locals=1, args_size=1
     0: aload_0
     1: invokespecial #8                  // Method java/lang/Object."<init>":()V
     4: return
  LineNumberTable:
    line 3: 0
  LocalVariableTable:
    Start  Length  Slot  Name   Signature
           0       5     0  this   Ltest/Test1;

protected void someInjectedMethod();
Signature: ()V
flags: ACC_PROTECTED

Code:
  stack=2, locals=1, args_size=1
     0: getstatic     #22                 // Field java/lang/System.out:Ljava/io/PrintStream;
     3: ldc           #24                 // String injection example
     5: invokevirtual #30                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
     8: return
RuntimeVisibleAnnotations:
  0: #32()
Synthetic: true
}

Notice that both the class and the method have the attribute Synthetic: true which mean they are Synthetic but, you the synthetic symbol must also be present in the constant pool (check #33).
Another example regarding the use of constant pool and class/method attributes is the annotation added to someInjectedMethod with runtime retention policy. The method's bytecode only has a reference to the constant pool #32 symbol, and only there you learn that
the annotation is from the type test/TestAnnotationToShowItInConstantTable;
Hope things got a bit more clear for you now.


text: Q: How to activate the "nofollow" property of htmlpurifier on Trsteel's Ckeditor Bundle (symfony2)? Using Trsteel's Ckeditor Bundle for SYMFONY 2, I am looking to add rel="nofollow" to link tags. Technically, that can be done using a custom config file for Ckeditor, but I would rather use the native nofollow attribute provided by htmlpurifier. Unfortunately, I can not find any way to access the configuration option of htmlpurifier ! Any idea ?


text:
Q: Holder continuity of power function I need to compute the coefficient for the Holder continuity of $x^p$ with $x > 0$, that is
$$
  H(p) := \sup_{x\neq y}\frac{|x^p - y^p|}{|x - y|^p}.
$$
I am actually going to apply this in numerical scheme, so I am interested in finding $H(p)$ itself, rather than upper bounds, or at least an upper bound which is not extremely conservative. I am also interested in case of $H(p,M)$ which is the Holder coefficient over a bounded interval $[0, M]$. Any hints how to do that?

A: Taking $y=0$ shows that $H(p)\ge1$. If $0<p\le1$, the inequality $1-z^p\le(1-z)^p$ for $0\le z\le1$ shows that $H(p)=1$. If $p>1$, choosing $x=y+1$ shows that $H(p)=\infty$. The same happens on a bounded interval $[0,M]$.
As an aside, observe that if
$$
|f(x)-f(y)|\le C\,|x-y|^r
$$
with $r>1$, then $f$ is constant.


text:
Q: Does Ubuntu support Radeon HD 6750M or 6490M? Looking at a Samsung Series 7 laptop.. Anyone know if Ubuntu supports AMD Radeon HD 6490M or 6750M?

A: The question is not if Ubuntu supports your hardware or not, it is more if your hardware builder has made any drivers for your hardware to be usable in Linux.
The Radeon HD 6750 is officially supported by ATI's Catalyst drivers and the xserver-xorg-video-ati open source drivers.
The Radeon HD 6750M will work even tough you will find your self with a watermark on the right bottom corner of the screen saying your hardware is not supported. That can be fixed following some simple steps.
The Radeon HD 6490 or the 6490M are not officially supported by ATI's Catalyst drivers but the open source xserver-xorg-video-ati driver should work without a problem.
The xserver-xorg-video-ati open source driver will be installed by default once your card is detected, the performance in not au pair with the closed driver but really big improvements are done with each release so its definitely an option.
You can easily toogle between the open source xserver-xorg-video-ati driver and the closed driver by following these steps.

A: [EDIT BELOW, it works!]
Short note to say that I never got my Chronos 7 working with fglrx drivers.  I've tried Oneiric and Precise, with catalyst 11.2 and more recently 12.1.  Currently I have the drivers installed, but I have to delete my xorg.conf in order to get a desktop, which dumps me to a Unity-2d session.  My driver, according to my system settings, is blank, which I presume means that I'm on Intel.
If I uninstall the drivers, I get a Unity 3D session using the Intel driver, but then the ATI card runs at full speed constantly, driving the fans at full speed.
Other issues - no control over the backlit keyboard (it's always on), screens brightness resets to full on startup, ignoring your choice/amendments in the display settings and finally, as it's a buttonless trackpad, you'll need to make some tweaks (https://bugs.launchpad.net/ubuntu/+source/linux/+bug/582809) in order to get it working.  It's also incredibly insensitive, so you'll have to tweak it again with
synclient FingerLow=3
synclient FingerHigh=8

every login to make it usable without pressing the full pad of your finger in order to move the mouse.
Suspend/resume, WIFI, sound and 1600x900 resolution, however, all work fine.
This laptop is NOT a good choice for Ubuntu. Unity-2d is startlingly poor - no customisation options, so you'll get the whole "FisherPrice" experience - but necessary unless you can put up with the noise of the fans blasting full time.
EDIT :
I did eventually get this laptop working reasonably well. FGLRX did install in the end.  Despite the multi-arch status of Precise, I ended up doing a sudo apt-get install ia32-libs which then installs a multitude of "redundant" packages. Can't tell if that's really what did the trick, but un-installing FGLRX after that, then re-installing (using the "additional drivers" in system settings and choosing the stable drivers) appeared to do the trick. You also have to link /usr/lib64 to /usr/lib, or the sudo amdconfig --px-dgpu command will fail.
So, what's wrong now? The trackpad still needs the synclient changes and doesn't support click-n-drag although two-finger scrolling is good, as is two-finger tap for right-click. The keyboard backlight is always on and unconfigurable. The brightness of the screen will often reset on boot up to full power. There was also an issue with Pulseaudio, but I think that will be resolved now - certainly the fix on that bug report got me working, as you can see on comment 24.
So conversely then, it's fast, quiet (unless you're playing a game), high resolution, light (for its size), and the battery lasts around 4 hours with light usage (mid-brightness, WIFI on, Bluetooth on, web browsing mainly).
In summary, it's hard work, but a cracking laptop once you get it working. And perhaps the finished 12.04 will work around some of these issues generally.

A: Yes and you have 3 main options for the ATI video cards under Ubuntu:

*

*the radeon package, which is for the really old video card and only provide a basic support for 2D acceleration

*the fglrx package from the official repository, which contains the official closed source driver for the latest ATI video card but is outdated compared to the third option

*the official closed source driver from the AMD ATI website and this is your best option http://support.amd.com/us/gpudownload/Pages/index.aspx
for references and documentations you can follow this link http://wiki.cchtml.com/index.php/Main_Page