text:
Q: Prove $e_A$ is an Extreme point of $B_A = \{a\in A: \|a\| \leq 1\} $ in a Banach algebra $A$ Let $A$ be a  Banach algebra with identity  $e_A$

prove that $e_A$ is an  extreme point of $B_A = \{a\in A: \|a\| \leq 1\} $

Recall that $x$ is an extreme point of $B_A$ if $x = \frac{1}{2}(x_1+x_2)$ for some $x_1,x_2\in B_A$ implies that $x= x_1=x_2.$
My attempt:
let $x,y \in  B_A$, $t\in (0,1)$ and  $e_A=tx+(1-t) y$
it is easy to see that
$$\|x\|=\|y\|=1$$
therefore $$\|e_A-tx\|=\|(1-t) y\|<1  {\text{and }}\|e_A(1-t) y\|=\|tx \|<1$$
this implies that $$tx, (1-t) y \in Inv A$$
where $Inv A$ is the set of all invertible elements of $A$
I can't continue from here
Can I get some hints?

A: Suppose $1=\frac{1}{2}x_1 +\frac{1}{2}x_2$ with $x_1,x_2\in B_A$ where $1$ denotes the unit of $A$. Let $B_{A^*}$ denote the unit ball in $A^*$ and consider the set $Y=\{\psi \in B_{A^*}: \psi(1-x_1)=||1-x_1||\}$. It is convex and compact in the weak*-topology so by Krein-Milman $Y$ has an extremal point $\phi$. $\phi$ must be extremal even in $B_{A^*}$: if $\phi=\frac{1}{2}\phi_1+\frac{1}{2}\phi_2$ for $\phi_1, \phi_2 \in B_{A^*}$, the equation $||1-x_1||=\phi(1-x_1)=\frac{1}{2}\phi_1(1-x_1)+\frac{1}{2}\phi_2(1-x_1)$ along with $|\phi_1(1-x_1)|, |\phi_2(1-x_1)|\leq ||1-x_1||$ already implies that $\phi_1(1-x_1)=\phi_2(1-x_1)=||1-x_1||$ so $\phi_1, \phi_2\in Y$, which by extremality in $Y$ implies that $\phi_1=\phi_2=\phi$.
Now consider the decomposition $\phi=\frac{1}{2}\phi(\cdot x_1)+\frac{1}{2}\phi(\cdot x_2)$. Clearly $\phi(\cdot x_1),\phi(\cdot x_2)\in B_{X^*}$ so by extremality $\phi=\phi(\cdot x_1)$. In particular $\phi(1)=\phi(x_1) \rightarrow ||1-x_1||=\phi(1-x_1)=0$. Hence $x_1=x_2=1$.


text:
Q: Mysql update using php variable giving error I hope someone can help me with this one
I have a page displaying different members of a sports team when user clicks on a specific player a new page opens 'edit.php' where the selected(clicked) players info is displayed in a form. (Information such as name, lastname, phone nr and email is contained within the form)
Lets say the players name changed (very unlikely but just an example) the coach can update it. When he clicks the submit button the database should get updatated with the new information
However when I change the name to John and click submit I get the following error:
Query failed:Unknown column 'John' in 'field list'
Ive spend the last couple of hours debugging this with no luck, would greatly appreciate it if someone can point me in the right direction. Code follows:
    if(isset($_POST['submit'])){
$firstname = $_POST['firstname'];

$query = "UPDATE player_info SET name =".$firstname." WHERE player_id =".$selectedplayer;
mysql_query($query)
or die ("Query failed:" .mysql_error());
}//end if

else
{
echo '<form name="update" method="post">';
while($row =mysql_fetch_array($result)){

 $name = $row['name'];
 $surname = $row['surname'];
 $phone = $row['contact_number'];
 $email =$row['email'];
 $position = $row['position'];

echo "Name: <input type=\"text\" value= '$name' name='firstname' />
";
echo "Last Name: <input type=\"text\" value= '$surname' />
";
echo "Phone nr: <input type=\"text\" value= '$phone' />
";
echo "Email: <input type=\"text\" value= '$email' />
";
echo "Position: <input type=\"text\" value= '$position' />
";
} //end while
} //end else

echo'<input type="submit" name="submit">';
echo'</form>';

A: You need some quotes around your $firstname variable. (Where your field isn't an integer):
$querie = "UPDATE player_info SET name ='".$firstname."' WHERE player_id =".$selectedplayer;

I'm assuming you are using 'John' in your input. Because you've left out the quotes, your MySQL looks like SET name=John and since MySQL can't find 'John' as a field, it tells you.
Never-the-less:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

A: Try with quotes around the name like this
'".$firstname."'

$query = "UPDATE player_info SET name ='".$firstname."' WHERE player_id =".$selectedplayer;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mysql, changing file location to remote in local network I have 4 computers and 1 server in my local network, there is Xampp(with Mysql) installed on each computer, what I'd like to do, is to cofigure it the way  that all mysql data from all computers be saved on the server, so each computer will be talking to the server

A: you could install mysql on the server, and point all php development to access database on the server. instead of local host.
this should be as easy as changing the database configuration part of your php
just be sure to create user for remote access in the mysql server.
if each computer client have already data in their local database, then dump all databases and recreate on the server.


text:
Q: How to set debug flags correctly in a Cmake project compiled with Visual Studio I have a C++ CMake project that is compiled both on Linux and Windows. On Windows, this is done via Visual Studio/MSVCC.
In CMAKE and in VS, the build is set up as Debug, but it seems that no debug symbols are ever being made in the VS build - so debugging is impossible.
When looking over the Detailed output for VS, I saw this:
cl : command line warning D9002: ignoring unknown option '-g'
That suggests to me that it doesn't recognize the -g flag like GCC/Clang do.
Here is the CMake arguments:
SET(CMAKE_CXX_STANDARD 17)
SET(CMAKE_CXX_STANDARD_REQUIRED ON)
SET(BUILD_MODE Debug)
SET(CMAKE_CXX_FLAGS "-Wall")
SET(CMAKE_CXX_FLAGS_DEBUG "-g")
SET(CMAKE_CXX_FLAGS_RELEASE "-O3")

How do I make this compatible with Visual Studio? I've tried looking all over, but most related posts seem to be about C#/.net, or much older versions of VS.
The project does use the QT library if that matters.
UPDATE:
It turns out BUILD_MODE was something added by someone else so that each sub-project would not individually need to be set to release or debug, we could just set it once in the root level Cmakelists. They did all actually use CMAKE_BUILD_TYPE as intended.
Also, the answers here were correct. Setting the CMAKE_CXX_FLAGS directly was wiping away the defaults, causing the Debug build to not have options like /Zi in MSVCC, preventing debug symbols and all debugging. It also introduced an unrecognized flag "-g" which MSVCC couldn't understand.
I completely remove the SET_CXX_FLAGS from every Cmakelists.txt in the project, and everything is working perfectly.
Should I need to add to them, I will use the _INIT option as suggested.

A: You have to compile with a different mode set with CMAKE_BUILD_TYPE as in
cmake -DCMAKE_BUILD_TYPE=DEBUG <sourcedir>

You never set those flags directly. If you want to add a new flag to a debug mode like for example a stack protector, you should use the *_INIT variables.
You can further distinguish which OS you are running with the UNIX, WIN32 and MSVC cmake boolean predefined constants:
if ( UNIX )
set( CMAKE_CXX_FLAGS_DEBUG_INIT "-fstack-protector" )
elseif( WIN32 )
set( CMAKE_CXX_FLAGS_DEBUG_INIT "/GS" )
endif()

A: There should be no need to define -O3 and -g explicitly in cmake. Setting those may prevent the code from working with other compilers, as you've seen. Those 2 options are the default anyways.
To build one of the configurations using unix makefiles you simply set the CMAKE_BUILD_TYPE cache variable during configuration:
(I'm assuming the generators mentioned are the default generators below.)
cmake -D CMAKE_BUILD_TYPE=Debug -S ... -B buildDir

or
cmake -D CMAKE_BUILD_TYPE=Debug -S ... -B buildDir

and to build the project you use
cmake --build buildDir

The visual studio is differnet insofar that the generated project covers all configurations at once. You specify the configuration to work with when building (or installing) the project instead:
cmake -A x64 -S ... -B buildDir

cmake --build buildDir --config Release
cmake --build buildDir --config Debug

Alternatively you can simply open the generated solution in the IDE.
cmake --open buildDir

For compiler specific flags you may need to make a case distinction:
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
    add_compile_options(/Wall)
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
    add_compile_options(-Wall)
endif()


text:
Q: How multi processes bind to one udp port I have two applications, one is C-Based, one is NodeJs-Based.
Two apps need process UDP message from same port in one Centos machine.
Is it possible to have 2 programs that bind to same UDP port and take message simultaneously?
In NodeJs, I used dgram:
dgram.createSocket({type: "udp4", reuseAddr: true})

And in C, I use SO_REUSEADDR, SO_REUSEPORT parameter for the setting socket.
The problem is: I can not receive any UDP message in application started later. That means only one application can receive UDP message.
Any help is really appreciated. Thanks

A: Using SO_REUSEADDR or SO_REUSEPORT on a UDP socket only work for incoming  multicast or broadcast packets.
If a unicast packet comes in, whether it is delivered to all sockets or just one (and which one) is implementation defined.


text:
Q: R Nonlinear regression I need a help with a curve fitting problem. I am also quite new to R. I have some data ( 3 pairs of type (x,y)), and need to apply a Nonlinear regression.
Basically, I have  a function f(x,a,b,c,d,e,f) -  x and 6 other parameters. I want to find a set of (a,b,c,d,e,f) which minimizes
weighted sum of squared residuals (weights inversely proportional to squared standard deviations (though in other line it says inversely proportional to variances - maybe it is the same, don't know)).
Can this be done in a simple way on R? Or is there any other software which can do this in a simple manner?


text:
Q: Use UILabel in Class Method So I have this:
@interface ViewController : UIViewController{
    IBOutlet UILabel *Screen;
}

+(void)num:(int)number;

And I want to access Screen in another class in the num method like so:
+(void)num:(int)number{
    Screen.text = @"test";
}

But xCode says

"Instance variable 'Screen' accesses in class method"

Is there any way to do this?

A: Yes, the reason it is not letting you is because the + sign in the method denotes a class method aka to be called on ViewController class but you don't have a reference to your specific Screen outlet.
Change the + to a - and then you will be able to call the method like
[self num:7]

and access the Screen outlet in that method
Hope that helps!

A: You can do this if your ViewController is singleton. You have to store pointer to your viewcontroller and then you can access to its variables.
For a example:
(h file)
@interface ViewController : UIViewController{
    IBOutlet UILabel *Screen;
}

+(void)num:(int)number;

(m file)
+(ViewController*)instance
{
    static ViewController *inst = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        inst = [ViewController new];
    });

    return inst;
}

+(void)num:(int)number{
    [ViewController instance]->Screen.text = @"test";
}


text:
Q: Your API key is invalid in React Native I'm using @wedoogift/react-native-checkout-payment to integrate cards payments via checkout.com. Initialization is done successfully. When I tried to get access token by using following piece of code as written in the library description, I got the error Your API key is invalid.
Initialization
useEffect(() => {
    CheckoutModule.initialize('pk', 'sandbox')
      // or 'live' instead of 'sandbox' for production env.
      .then(() => {
        console.log('Initialization is done.');
      });
  }, []);

Access Token
CheckoutModule.generateToken({
    card: '4242424242424242',
    name: 'Card Owner',
    expiryMonth: '06',
    expiryYear: '25',
    cvv: '100'
}) // or 'live' for production env.
    .then((result) => {
        console.log('Card token is ' + result.id);
        // See CardTokenisationResponse in index.ts or index.d.ts
        // to see the data structure of the result.
    })
    .catch((error) => {
        console.warn('Failed because: ' + error.message);
    });

I don't know where to get it and where to place it. There is nothing in the library description about this API key.
How to resolve this thing.
Thanks

A: The API key should go where 'pk' (I guess this stands for public key) is in the example code.
For example if your API key is 0123456789
CheckoutModule.initialize('0123456789', 'sandbox')
...


text:
Q: Using LINQ changing database from SQL Server 2008 R2 to SQL Server 2008 I've completed my webpage on my home computer and ready to upload it.
However I'm getting this error:

A network-related or instance-specific
  error occurred while establishing a
  connection to SQL Server. The server
  was not found or was not accessible.
  Verify that the instance name is
  correct and that SQL Server is
  configured to allow remote
  connections. (provider: Named Pipes
  Provider, error: 40 - Could not open a
  connection to SQL Server)

I know the connection string is correct. And I run a few different pages so I can connect to the other databases without problem.
This is the fist time I have used LINQ and I thought perhaps there was a setting it made that I need to change? LINQ is used in my DAL which is separate to the database, its just stored as DLLs in my bin folder...
My development server uses SQL Server 2008 R2 Express and my live server uses SQL Server 2008
I created database scripts to create the database. so I just ran them to downgrade the webpage.
Also In my DAL I just do this:
AHDBcontext db = new AHDBcontext(connectionstring);

var whatever = from s in suppliers
               select s;

I always set connection string from the web.config file.
Any ideas?

A: *

*Check the connection string.

Another way is following.
Go to Start Up => Microsoft Sql server 2008 => Configuratiuon Tools => Sql Server Configuration Manager
Check the Enabled status for client protocol.

restart the Browsing and other necessary services.


text:
Q: Move Sprite to nearest Sprite When the user taps a button, I want to move a sprite to the next nearest ball (sprite), so they can move from place to place.
As there will only be a limited amount of balls on the screen at a time, I was thinking I should store them in an array, and then when they move offscreen (are destroyed by a function I have in place), they are removed from the array.
I have the current setup (not in a loop atm) :
ball = [[CCSprite spriteWithFile:@"ball.png"] retain];
ball.position = ccp(randX, randY);

NSMutableArray *myArray = [[NSMutableArray alloc] init];
[myArray addObject: ball];
[myArray addObject: ball];
[myArray addObject: ball];

for (int i = 0; i < 2; i++) {
    CCSprite *sprite = [myArray objectAtIndex:i];
    NSLog(@"%@", sprite.position.x);
}

Why is NSLog printing "(null)" to the console?

A: Haha woops! Was a simple case of changing @"%@" to @"%f". Lol!

A: It looks like you actually want to find the sprite with the lowest X position:
CCSprite *sprite = [myArray objectAtIndex:0];

for (CCSrpite *s in myArray)
{
    if (s.position.x < sprite.position.x)
        sprite = s;
}

// now 'sprite' will contain the sprite with the lowest X position


text:
Q: Having trouble applying stamens toner style to SQLite lines layer in QGIS I am an absolute QGIS/GIS beginner using 3.22 QGIS software.
My goal is to load a sector of the United States with the stamens toner lite style.
I downloaded my data from geofabrik.
I then used ogr2ogr to convert the pbf file to a SQLite database
I can navigate to the DB and load the lines and have them render on my project just fine.
The problem is when I go to Properties>styles and apply the toner-lite style from
Nothing seems to happen.
At first I thought maybe it takes longer to render, but even after it seems to do it's rendering the roads never showed up.
It renders the multipolygons fine, but the roads never show up.
I experimented on a smaller data set in the experiment presented by anita at this link, and loading the styles worked there without problems.
What could I be doing wrong?

A: By seemingly dumb luck I figured out the problem. For anyone else who is struggling with this in the future: changing the reference system to EPSG:3785 solved the problem (perhaps others may work, or likely the one I had selected was not adequate.)


text:
Q: How to receive data from firebase according to selected option? I developing an ionic 2 app where people can add their blood types to firebase.
Now I want to implement a search-page to receive that data from firebase, For instance, somebody wants to search for B Rh+ blood type, simply selects that radio button and when they click search I want to search B Rh+ bloods in Firebase and list them.
here is my search html:
  <ion-list>
  <ion-item>
    <ion-label>Blood Type</ion-label>
    <ion-select [(ngModel)]="bloodtype">
      <ion-option value="ap">A Rh+</ion-option>
      <ion-option value="an">A Rh-</ion-option>
      <ion-option value="bp">B Rh+</ion-option>
      <ion-option value="bn">B Rh-</ion-option>
      <ion-option value="abp">AB Rh+</ion-option>
      <ion-option value="abn">AB Rh-</ion-option>
      <ion-option value="zp">0 Rh+</ion-option>
      <ion-option value="zn">0 Rh-</ion-option>
    </ion-select>
  </ion-item>

  <ion-item>
  <ion-range [(ngModel)]="range">
    <ion-icon range-left small name>0km</ion-icon>
    <ion-icon range-right small name>100km</ion-icon>
  </ion-range>
</ion-item>

<button ion-button full icon-left (click)="presentLoading()">
  <ion-icon name="search"></ion-icon>
  Search
</button>
</ion-list>

and here is my search.ts:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { LoadingController } from 'ionic-angular';

@Component({
  selector: 'page-search',
  templateUrl: 'search.html'
})
export class SearchPage {

  constructor(public navCtrl: NavController,public loadingCtrl: LoadingController) {}

  ionViewDidLoad() {
    console.log('Hello SearchPage Page');
  }

  presentLoading() {
    let loader = this.loadingCtrl.create({
      content: "Please wait...",
      duration: 3000
    });
    loader.present();
  }

}

I tried to use search bar and receive data with this reference this.bloodRef = firebase.database().ref('/bloods'); but using search bar is not functional since people can type "brh+" or "b" etc.
my firebase hierarchy:
---bloods (id)

          ------ blood-type: "B Rh+"

A: You can filter items with orderBy and equalTo functions:
var results = [];
this.bloodRef.orderByChild('blood-type').equalTo(this.bloodtype).once("value")
  .then(function(snapshot) {
    //snapshot.val() is the object
  });


text:
Q: Strange behaviour when ggplotting line thickness depending on field of a sf "MULTILINESTRING" I have a simple feature collection (lines) with the geometry type "MULTILINESTRING" that i want to plot with ggplot2. The line thickness should represent the value of a field. Unfortunately I am not able to provide a reprex. But maybe there is an obvious mistake that can be easily identified.
lines

Output:
Simple feature collection with 171 features and 1 field
geometry type:  MULTILINESTRING
dimension:      XY
bbox:           xmin: 579649.7 ymin: 5801899 xmax: 625387 ymax: 5851019
projected CRS:  ETRS89 / UTM zone 32N
First 10 features:
   strahler                       geometry
1         1 MULTILINESTRING ((580016.3 ...
2         1 MULTILINESTRING ((582188.7 ...
3         1 MULTILINESTRING ((581499.9 ...
4         1 MULTILINESTRING ((586581.9 ...
5         1 MULTILINESTRING ((584296.4 ...
6         1 MULTILINESTRING ((583833.5 ...
7         1 MULTILINESTRING ((584608.8 ...
8         1 MULTILINESTRING ((583096.1 ...
9         1 MULTILINESTRING ((588869.2 ...
10        1 MULTILINESTRING ((587474.7 ...

I am plotting it with
lines %>%
  mutate(strahler = as.integer(strahler)) %>%
  ggplot() +
  geom_sf(aes(size = strahler))

The result looks really messy. It seems that using size this way affects the vertices of the lines.

Reprex
When I tried to provide a reprex, this messy look didn't occur
lines <-
  tibble(
    x = c(1, 2, 5, 2, 4),
    y = c(0, 3, 4, 3, 2),
    order = c(2L, 2L, 2L, 1L, 1L)
  ) %>%
  st_as_sf(coords = c("x", "y")) %>%
  st_sf(crs = 25832) %>%
  group_by(order) %>%
  summarise() %>%
  st_cast("MULTILINESTRING")

lines

Simple feature collection with 2 features and 1 field
geometry type:  MULTILINESTRING
dimension:      XY
bbox:           xmin: 1 ymin: 0 xmax: 5 ymax: 4
projected CRS:  ETRS89 / UTM zone 32N
# A tibble: 2 x 2
  strahler              geometry
     <int> <MULTILINESTRING [m]>
1        1          ((2 3, 4 2))
2        2     ((1 0, 2 3, 5 4))

Plotting it
lines %>%
  mutate(strahler = as.integer(strahler)) %>%
  ggplot() +
  geom_sf(aes(size = strahler))

I guess it has to do with the geometry field which looks different but I don't know how to convert it. I am happy about any hint!

A: Thanks to @mrhellmann: The proposed setting of the argument lineend = "round" in geom_sf() in combination with scale_size_identity() did solve this issue although it seems more like a work-around than a proper solution to me.
Using this code works:
lines %>%
  mutate(strahler = as.integer(strahler)) %>%
  ggplot() +
  geom_sf(aes(size = strahler)) +
  scale_size_identity()

However, a legend is not show using this solution!


text:
Q: Resize a banner in CSS I will wish to get a result like this for example in CSS.

Here is my result for now

How to do to have the same result that the first image?
Here is below my code.
.banner02{
  height: 100px;
  width: 100%;
  position: absolute;
  margin: 0px;

}

And my HTLM

Thanks

A: I don't know what you are written, But add the following styles to your element that have background-image:

header{
  width: 100%;
  height: 100px;
  background-image: url(http://trak.in/wp-content/uploads/2018/01/10-Rupees-Coins.jpg);
  background-size: cover;
  background-position: center;
}

And another way:

div {
  width: 100%;
  height: 100px;
  overflow: hidden;
}

div > img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}


text:
Q: A form submit returns {"error": "'action'"} I have a form submit that crashes in production with the following error {"error": "'action'"}, but for some weird reason does not happen in local way. The input with id="btnEditar" is the one that push the error. The error is displayed in a white page.
Nothing appears in the console of the browser and as far as the error doesnt ocurr in local no messages appears in the backend.
I have tried to reload js in several browsers but with the same results... running on Django local dev server the form is submitted OK and the data is updated as well, but in pythonanywhere prod server the error mentionated error comes up. hope you can help me to figure it out!!
Here is the template code:
      {% extends 'core/home.html' %}
      {% load static %}
      {% load bootstrap %}
      <!doctype html>

          {% block content %}
          <form method="post">
          {% csrf_token %}

{{ object.id }}

{{ object.start_time }}

                  Fecha de Reprogramación

                        {{form.start_time|bootstrap}}

                    Paciente

{{ object.paciente }}

                      {{form.paciente|bootstrap}}

                    Telefono

                      {{form.telefono|bootstrap}}

                    Accion

                      <input style="height: 2rem; margin-top: 1px;" type="submit" id="btnEditar" class="btn btn-secondary" value="Editar Turno" />

                  Turnos del Dia

14:00

14:30

15:00

15:30

16:00

16:30

17:00

17:30

18:00

18:15

18:30

18:45

19:00

19:15

19:30

19:45

          </form>
        {% endblock %}

And this is the js looks like:
$("#btnEditar").click(function(e){
    e.preventDefault(e);
    //
    //Validaciones
    fectur=document.getElementById("fecha").value;
    if (fectur.length<1){
            alert("Debe Seleccionar una Fecha Valida.");
        return false;
        }
    tele=document.getElementById("id_telefono").value;
        if (tele.length<1){
            alert("Debe Ingresar un Telefono.");
        return false;
        }
    resuldia=esdialaborale(fectur);
    console.log("este es el resultado de la funcion : " + resuldia)
    if (resuldia!=1){
            alert("Debe Seleccionar un Lunes, Martes o Miercoles.");
        return false;
        }
    elementos=document.getElementsByClassName("card border-primary mb-3");//Si ya hay un slot seleccionado ->sale
    console.log(" cantidad de slots marcados:" + elementos.length)
    if (elementos.length ===0){
        alert("Debe seleccionar una hora para el turno.")
        return false;
    }
    if(elementos.length>1){
        alert("Dos horas han sido seleccionadas. Vuelva a seleccionar la hora del turno.")
        do{
            for (x=0;x<elementos.length;x++) {
                document.getElementById(elementos[x].id).className="card bg-light mb-3";
            }
        }
        while (elementos.length>0)
        return false;
    }
    if (user!='Silvia'){
        if (user!=''){
            if (document.getElementById(elementos[0].id).id==='19:00'){
                alert("Los turnos de las 19 horas son gestionado por la Dra. Ulloa.")
                return false;
            }
            if (document.getElementById(elementos[0].id.id)==='19:15'){
                alert("Los turnos de las 19 horas son gestionado por la Dra. Ulloa.")
                return false;
            }
            if (document.getElementById(elementos[0].id).id==='19:30'){
                alert("Los turnos de las 19 horas son gestionado por la Dra. Ulloa.")
                return false;
            }
            if (document.getElementById(elementos[0].id).id==='19:45'){
                alert("Los turnos de las 19 horas son gestionado por la Dra. Ulloa.")
                return false;
            }
        }
    }

    //Confirma Editar
    if (confirm('Esta seguro que Desea Editar el Turno?')) {
        // Edit it!
            //Encabezado
            var codigos=[];
            var pac = document.getElementById("id_paciente").value;
            codigos.push(pac);
            var tel =  document.getElementById("id_telefono").value;
            if (document.getElementById("id_telefono").value.length==0){dir=""}
            codigos.push(tel);
            var fec =  document.getElementById("fecha").value;
            codigos.push(fec);
            codigos.push(hor);
            var idt =  document.getElementById("HiddenId").innerHTML;
            codigos.push(idt);//Id turno a editar
            var fecant= document.getElementById("HiddenFecAnt").innerHTML;
            codigos.push(fecant);//Fecha turno original antes de editar
            var token = '{{csrf_token}}';
            //var data = JSON.stringify({"codigos":codigos});
            data = {"codigos[]":codigos,"action":'reschedule'};
            console.log(data);
            $.ajax({
                headers: { "X-CSRFToken": token },
                //"url": '/turnos/edit/'+idt+'/',
                "url": '/turnos/edit/',
                "type": "POST",
                "dataType": "json",
                data: data,
                success: function(data){
                    if(data['success']){
                        //Manda a Imprimrir pdf
                        if (confirm('¿Desea Imprimir el Turno?')) {
                            window.open("/turnos/pdf/"+idt+"/", '_blank');
                            window.location="/turnos/list/"
                        }else{
                            window.location="/turnos/list/"
                        }
                        //alert("El turno se registro correctamente.");
                        ("/turnos/pdf/"+proxid+"/", '_blank');
                        window.location="/turnos/list/"
                        //location.reload(true);
                    }
                },
                error: function(a,b,c){
                alert(c);
                }
            });
    } else {
        // Do nothing!
        return false;
    }
});

This is the view:
class TurnosEditView(UpdateView):
    model=Turnos
    form_class=TurnosEditForm
    success_url = reverse_lazy('turnos:list')
    template_name="turnos/turnos_edit.html"

    @method_decorator(csrf_exempt)
    def dispatch(self, request,*args,**kwargs):
        return super().dispatch(request,*args,**kwargs)

    def sumar_hora(self,hora1,hora2):
        formato = "%H:%M:%S"
        lista = hora2.split(":")
        hora=int(lista[0])
        minuto=int(lista[1])
        segundo=int(lista[2])
        h1 = datetime.strptime(hora1, formato)
        dh = timedelta(hours=hora)
        dm = timedelta(minutes=minuto)
        ds = timedelta(seconds=segundo)
        resultado1 =h1 + ds
        resultado2 = resultado1 + dm
        resultado = resultado2 + dh
        resultado=resultado.strftime(formato)
        return str(resultado)

    def post(self,request,*args,**kwargs):
        data={}
        try:
            action=request.POST['action']
            if action == 'reschedule': #TurnoEdit
                print("adentro de Edit")
                codigos=request.POST.getlist("codigos[]")#Codigo/s de los turnos
                fecha=codigos[2]
                hora=codigos[3]
                fecha=fecha+ " " + hora
                fechaforma=datetime.strptime(fecha, '%Y-%m-%d %H:%M')
                #hora fin
                hora1=hora+":00"
                if hora1[0:2]== '14':
                    horafin= self.sumar_hora(hora1,"00:30:00")
                elif hora1[0:2]== '15':
                    horafin= self.sumar_hora(hora1,"00:30:00")
                elif hora1[0:2]== '16':
                    horafin= self.sumar_hora(hora1,"00:30:00")
                elif hora1[0:2]== '17':
                    horafin= self.sumar_hora(hora1,"00:30:00")
                else:
                    horafin= self.sumar_hora(hora1,"00:15:00")
                fecha=codigos[2]+ " " + horafin
                fechaformafin=datetime.strptime(fecha, '%Y-%m-%d %H:%M:%S')
                idte=codigos[4]
                #Edicion
                tu= Turnos.objects.get(pk=int(idte))
                usuario=tu.user
                tu.user=usuario
                paciente=tu.paciente
                tu.paciente=paciente
                tu.telefono=codigos[1]
                tu.start_time=fechaforma
                tu.end_time=fechaformafin
                ahora=datetime.now()
                date_time_ahora = ahora.strftime("%m/%d/%Y")
                #fecha orgiinal turno
                fecori=codigos[5]
                if tu.observaciones=="":
                    print("Es igual a comillascomillas")
                    tu.observaciones= "(R)" + date_time_ahora + "_" + str(self.request.user) + "- Original: " + fecori
                else:
                    print("Ya tiene algo escrito")
                    tu.observaciones= tu.observaciones + ". (R)" + date_time_ahora + "_" + str(self.request.user) + "- Original: " + fecori
                print(tu.observaciones)
                tu.save()
                data['success']=True
            elif action == 'getuser':
                data=[]
                print(self.request.user.username)
                data.append(self.request.user.username)
                print(data)
            else:
                data['error']='No ha ingresado ningún dato'
        except Exception as e:
            data['error'] = str(e)
        return JsonResponse(data, safe=False)

And Finally the url:
from django.urls import path
from . import views
from .views  import TurnosListView,TurnosCreateView,TurnosInvoicePdfView,TurnosEditView,TurnosRePrintListView

turnos_patterns = ([
    path('list/', TurnosListView.as_view(), name="list"),
    path('reprint/', TurnosRePrintListView.as_view(), name="reprint"),
    path('create/',TurnosCreateView.as_view(),name="create"),
    path('edit/<slug:pk>/',TurnosEditView.as_view(),name="edit"),
    path('pdf/<int:pk>/',TurnosInvoicePdfView.as_view(),name='pdf')
    ], 'turnos')

OH the last one, here is the form class code:
class TurnosEditForm(forms.ModelForm):
    class Meta:
        model = Turnos
        fields =  '__all__'
        widgets = {
        'start_time': forms.DateInput(format='%Y-%m-%d',attrs={'id':"fecha",'class':"form-control",'style':"height: 2rem; margin-top: -25px; text-align:right;",'type':'date','value':datetime.now().strftime('%d-%m-%Y')}),
        'paciente': forms.TextInput(attrs={'class':'form-control','style':"height: 2rem; margin-top: -25px;", 'placeholder':''}),
        'telefono': forms.TextInput(attrs={'class':'form-control','style':"height: 2rem; margin-top: -25px;", 'placeholder':'Ingrese un Telefono'}),
        }
        labels = {
            'start_time':'', 'telefono':'','paciente':'',
        }

A: I have found the issue.... I was working with non updated static files since I have never run collectstatic in production server :S
Now its working the same way as development environment. :)
Regards,


text:
Q: Finding the first non-repeated character of a string in O(n) using a boolean array? My question is related to this earlier question

Find the first un-repeated character in a string.

In one of my interviews I was asked to write a function to determine the first unique character in a string in time O(n) using as extra space only a boolean array of length n.  That is, find the first non repeating letter in a string using only O(n) complexity and a bool array of length n.  Can some suggest how to solve it with bool array?

A: Well, if the size of the character set is constant...  Say, for instance, 0-255...
Scan the string looking for character 0.
Then scan the string looking for character 1.
Then scan the string looking for character 2.
...
Finally, scan the string looking for character 255.
This takes 256*n operations which is O(n).
During each scan, if the character is unique, mark its position in the bitmap.  At the end return the character at the first marked position.  (Or just record the first unique character and its location using k + log(n) bits.  Use a hard-coded lookup table or whatever for very small n; otherwise, n bits is generous.)
Although somehow I suspect this is not what the interviewer had in mind.

A:     private static void FirstNonRepeatingCharacters()
    {
        string s = "abbazccdde";
        var result = from item in s
                     group item by item into groupedItems
                     where groupedItems.Count() == 1
                     select groupedItems.Key;
        Console.WriteLine(result.First());
    }

C# implementation

A: For Single Pass Solution
Maintain 2 data structures:

*

*Array / bitmap / hashtable for tracking the count of each character

*LinkedHashMap to track the characters which have occured only once so far.

LinkedHashMap has

*

*O(1) insertion

*O(1) deletion

*O(1) search
class Node
{
  char data;
  Node next;
  Node prev;
};

class LinkedHashMap
{
        // This will keep the insertion order intact
        Node listHead;
        Node currentTail = listHead;
        HashTable<char, Node> charExistsMap;

    void Add(char ch)
    {
        if(!charExistsMap.ContainsKey(ch))
        {
            // Add to both hashtable and linkedlist
            Node n = new Node(ch);
            n->next = null;
            n->prev = curentTail; // Added To List
            currentTail = n;
            charExistMap.Add(ch, n);
        }
        else
        {
            // Remove from both hashtable and linkedlist
            Node n = charExistMap.Remove(ch);
            if(n->prev != null)
            {
                n->prev->next = n->next
                listHead = n->next; // update head
            }
            if(n->next != null)
                n->next->prev = n->prev;
         }
    }

    char GetFirstNonRepeatingChar()
    {
        return listHead->data;
    }

}
After the original string is traversed, the head of the LinkedHashMap will contain the first character which is not repeated.

A: public class FirstUniqueChar {

  public static void main(String[] args) {

    String test = "ABxacd";

    test = test.toUpperCase();
    for (int i = 0; i < test.length(); i++) {
        int firstIndex = test.indexOf(test.charAt(i));
        int lastIndex = test.lastIndexOf(test.charAt(i));
        if (firstIndex == lastIndex) {
            System.out.println("First unique char of String " + test.charAt(i));
            break;
        }

    }

  }
}

A: Do that in two passes:
1st pass: create bool array of size 256 and for each char in the text mark the element of index int(that char). This takes O(n).
2nd pass: for each char in the text check if the corresponding array element is marked. If not then you found your answer. This also takes O(n).

A: Have two boolean arrays, seenOnce and seenMany.
Loop over the string populate the arrays.
Loop over the string again checking if the character is in seenFirst but not in seenMany. If it is thats your first non-repeating character.
Here's some example code in python.
subject = "ttojxxlma"

seenOnce = [False for i in range(256)]
seenMany = [False for i in range(256)]

for c in subject:
    index = ord(c)
    if seenOnce[index] == False:
        seenOnce[index] = True
    else:
        seenMany[index] = True

for c in subject:
    index = ord(c)
    if seenOnce[index]==True and seenMany[index] != True:
        print(c)
        break

Ok that still uses too boolean array (or python lists =P). To use only one array you can have one array thats double the amount of characters. Instead of accessing the second array double the index and access the big one. But thats just messy.
Not sure if it can be done with less space.


text:
Q: How can I connect my React Native application to MySQL database using JavaEE eclipse? I am super new to React Native and want to use MySQL database to display data on my mobile application. This I have created a web service on JAVAEE Eclipse to connect to the database and perform CRUD operations. I am not aware of how to use the JAVA webservice as a funtion method to perform the desirable task on a button interaction. I will not be using web scripting like php and would definitely like to stay away from firebase and meteor types. It's a strict learning curve which I want to achieve without using different technology at the moment.
My development stack is React Native + JAVA + MySQL

A: No you'll not need to use or create any java function for this.
Use fetch or axios to call your services.
Let say your service is running on localhost and on port 2000,
now make sure your 1.server and 2.android phone in which you are running RN app are in the same network.
let say you have one service which returns a list of data.
now in react-native use
fetch("your machine/server's ip address + :port/serviceRouter or other things")
e.g.
fetch("http://192.168.0.2:2000/getData")
This will work the same as a postman.
You can find official docs for other details of fetch here


text:
Q: Reduce fractions in C In c programming when I divide 2 numbers like 2/4 it gives output 0.5 but I want 1/2. So I want know how to perform division to get answer in fractions like numerator/denominator. I want in C.

A: What you really want is to reduce the fraction.. not compute the division.
Here's a quick sample that will yield the reduced fraction:
#include <stdbool.h>
#include <stdio.h>

//gcf function - return gcd of two numbers
int gcd(int n, int m)
{
    int gcd, remainder;

    while (n != 0)
    {
        remainder = m % n;
        m = n;
        n = remainder;
    }

    gcd = m;

    return gcd;
}//end gcd function

int main (int argc, const char * argv[]) {
    // insert code here...
    //--declarations
    int number1, number2;
    int newNumber1, newNumber2;

    //--get user input
    printf("Enter a fraction: ");
    scanf("%d/%d", &number1, &number2);

    //--calculations
    //find the gcd of numerator and denominator
    //then divide both the numerator and denominator by the GCD
    newNumber1 = number1 / gcd(number1, number2);
    newNumber2 = number2 / gcd(number1, number2);

    //--results
    printf("In lowest terms: %d/%d", newNumber1, newNumber2);
}

Sample taken from: http://snipplr.com/view/42917/

A: C does not have that ability built in. However, what you can do is, write a small function that takes fraction values (0.5 in your case) and returns the fraction the form your are looking for (ie, 1/2).
But remember, 1/2 is not a numeric; it is a string (char array). So, you can use it for display/print purpose only; you can not use in arithmetic expressions.

A: sorry that I can not adapt this to C, but you can for sure port back the code since is not soo complex
#include <iostream>
#include <string>

long GreatestCommonMultiple(long& a, long& b);
std::string SimplifyThis(long& a, long& b);

int main(int argC, char** argV)
{
    long n1 = 3;
    long n2 = 21;
    std::cout << "This as simplified fraction: " << n1 << "/" << n2 << " is "<<SimplifyThis(n1, n2)<<std::endl;
    return 0;
}

std::string SimplifyThis(long& a, long& b) {
    long gcm1 = GreatestCommonMultiple(a, b);
    return std::to_string(a / gcm1) + "/" + std::to_string(b / gcm1);
}

long GreatestCommonMultiple(long& a, long& b) {
    if (b==0)
    {
        return a;
    }
    long x = (a % b);
    return GreatestCommonMultiple(b, x);
}


text:
Q: Why does the null-conditional operator promote thread-safety in C#? There's a modern idiom in C# that utilizes the null-conditional operator to promote thread-safety when using delegates. Namely:
Update?.Invoke(this, theArgs);

Why does this work? Does the C# specification guarantee atomicity in the operation? Does the null-conditional operator make an underlying copy of its operand before executing the Invoke() method?

A: the Null-conditional operater is roughly equivalent to:
var handler = this.PropertyChanged;
if (handler != null)
{
    handler(…);
}

The part where it creates a local variable? That is what would help with thread safety.
However is is not 100% reliable. See, people have used this pattern before. It has been standing advise for events. But unless you mark handler as volatile, compiler or JiT compiler might cut it out due to being a underused variable. The compiler setting it in itself, might prevent that optimsiation.
But at the end of the day, the only reliable thing is a lock statement.


text:
Q: How to solve circuit problems with resistors in parallel then in series? A problem I am doing shows a circuit with one battery and one resistor. Then a switch is closed and two additional resistors are added in paralell and another in series as shown in the picture. (all $R = 2 \Omega$, $\Delta V=12$ V).
The book says that the current through the original resistor will NOT change despite change in the total resistance.
After diagraming it out i see that but i struggle to find the current in the other parts of the circuit
I would find total equivaent resistance.
Then using the voltage of the battery find the current of the original resistor.
Then for the other branch on the right, how do i handle the voltage drop becsuse i also have the resistor in series next downstream?

Additionally current starts from the big line/top and goes right! so up and right in my textbook.

A: Hints:
If you figure out the equivalent resistance of $R_V$, $R_{VI}$ and $R_{VII}$, you can figure out the current through $R_{VII}$.
If you know the current through $R_{VII}$, you can figure out the voltage across $R_{VII}$.
If you know the voltage across $R_{VII}$, you can figure out the voltage across $R_V$ and $R_{VI}$.
If you know the voltage across $R_V$ and $R_{VI}$, calculating the current through each of those is easy.

A: In problems like this (a closed, DC voltage, resistor network), the voltage supply is assumed to be able to supply any current necessary to meet the steady-state behavior. So, the following principles apply:

*

*1a) Circuit elements in parallel have the same voltage. So the $R_{V},R_{VI},R_{VII}$ combination has the same voltage as the supply.

*1b) Circuit elements in parallel may have different currents but the currents will add at the common connection point. So the currents through $R_{V}$ and $R_{VI}$ will add together.

*2a) Circuit elements in series have the same current. So the $R_{V},R_{VI}$ combination (parallel) has the same current as the $R_{VII}$ resistor.

*2b) Circuit elements in series may have different voltages, but each voltage drop will add to the previous drop.

There is no need to find the total resistance for this circuit, unless you are asked for it.


text:
Q: Is there a way to see answers with the most votes? A few minutes ago a found an answer that is definitely worth reading! It has 74 up-votes.
If I want to see questions with the most votes then I can see them by clicking on the 'votes' tab. Is there a way to see those questions whose answers have the most votes?

A: Here's a solution, Questions with highest rated answers.
The only downside is you have to append the ID manually to the end of http://stackoverflow.com/questions/
Update
As per Cletus' request, Top Posts in Questions NOT CC Wiki

A: Here's an updated version for the new data explorer: Questions with highest rated answers
. It ignores community wiki questions and answers.

A: As a workaround you can check users with Great Answer from the Badges page, then on the user profile page, answers are sorted by number of votes

A: God I wish there was.
It should also have the option to exclude CW answers since they're 90% noise.
I would love to see good programming related answers without all the Dilbert cartoons and wedding cakes.


text:
Q: python, tkinter: how all variables can be obtained by single button from all notebook tabs? I need to return all variables from all tabs by clicking on ok button.
I have two tabs. What I want is that when I enter some value in 2nd tab, it should automatically appear in first tab in 'height' entry.
Then if I click 'ok' in first tab, it should return all  variables(from first tab and 2nd tab) to my 'main' program for further use.
Thanks
from tkinter import *
from tkinter import ttk

class App1(ttk.Frame):
    def createWidgets(self):
        #text variables
        self.i_height = StringVar()
        self.i_weight = StringVar()
        self.o_bmi = StringVar()

        #labels
        self.label1 = ttk.Label(self, text="Enter your weight:").grid(row=0, column=0, sticky=W)
        self.label2 = ttk.Label(self, text="Enter your height:").grid(row=1, column=0, sticky=W)
        self.label3 = ttk.Label(self, text="Your BMI is:").grid(row=2, column=0, sticky=W)

        #text boxes
        self.textbox1 = ttk.Entry(self, textvariable=self.i_weight).grid(row=0, column=1, sticky=E)
        self.textbox2 = ttk.Entry(self, textvariable=self.i_height).grid(row=1, column=1, sticky=E)
        self.textbox3 = ttk.Entry(self, textvariable=self.o_bmi).grid(row=2, column=1, sticky=E)

        #buttons
        self.button1 = ttk.Button(self, text="Cancel/Quit", command=self.quit).grid(row=3, column=1, sticky=E)
        self.button1 = ttk.Button(self, text="Ok", command=self.calculateBmi).grid(row=3, column=2, sticky=E)

    def calculateBmi(self):
        try:
            self.weight = float(self.i_weight.get())
            self.height = float(self.i_height.get())
            self.bmi = self.weight / self.height ** 2.0
            self.o_bmi.set(self.bmi)
        except ValueError:
            messagebox.showinfo("Error", "You can only use numbers.")
        finally:
            self.i_weight.set("")
            self.i_height.set("")

    def __init__(self, master=None):
        ttk.Frame.__init__(self, master)
        self.grid()
        self.createWidgets()

class App2(ttk.Frame):
    def create_widgets(self):
        """Create the widgets for the GUI"""
        #1 textbox (stringvar)
        self.entry= StringVar()
        self.textBox1= ttk.Entry(self, textvariable=self.entry).grid(row=0, column=1)

        #5 labels (3 static, 1 stringvar)
        self.displayLabel1 = ttk.Label(self, text="feet").grid(row=0, column=2, sticky=W)
        self.displayLabel2 = ttk.Label(self, text="is equivalent to:").grid(row=1, column=0)
        self.result= StringVar()
        self.displayLabel3 = ttk.Label(self, textvariable=self.result).grid(row=1, column=1)
        self.displayLabel4 = ttk.Label(self, text="meters").grid(row=1, column=2, sticky=W)

        #2 buttons
        self.quitButton = ttk.Button(self, text="Quit", command=self.quit).grid(row=2, column=1, sticky=(S,E))
        self.calculateButton = ttk.Button(self, text="Calculate", command=self.convert_feet_to_meters).grid(row=2, column=2, sticky=(S,E))

    def convert_feet_to_meters(self):
        """Converts feet to meters, uses string vars and converts them to floats"""
        self.measurement = float(self.entry.get())
        self.meters = self.measurement * 0.3048
        self.result.set(self.meters)

    def __init__(self, master=None):
        ttk.Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

def button1_click():
    root = Tk()
    app = App1(master=root)
    app.mainloop()

def button2_click():
    root = Tk()
    app = App2(master=root)
    app.mainloop()
def main():
    #Setup Tk()
    window = Tk()

    #Setup the notebook (tabs)
    notebook = ttk.Notebook(window)
    frame1 = ttk.Frame(notebook)
    frame2 = ttk.Frame(notebook)
    notebook.add(frame1, text="BMI Calc")
    notebook.add(frame2, text="Feet to Meters")
    notebook.grid()

    #Create tab frames
    app1 = App1(master=frame1)
    app1.grid()
    app2 = App2(master=frame2)
    app2.grid()

    #Main loop
    window.mainloop()
main()

A: You have some fundamental mistakes in your program -- you cannot have three mainloops running at the same. You should always only have exactly one instance of Tk, and call mainloop exactly once.
Regardless of that, the solution is that you need to create a method or public variable in the app, and then your button callback needs to be able to call that method or access that variable.
For example, you would do it like this:
def callback():
    value1 = app1.getValue()
    value2 = app2.getValue()
    ...


text:
Q: Why is the speed and quality of streaming (over LAN) so different? Can someone explain why is the quality and speed of streaming over LAN (for example with VLC Streaming) less better than apps like DroidCam where it's the same principal?
I tried many times to stream my laptop camera over VLC (LAN) with different parameters (Protocols: HTTP/RTSP, Transcoding:HD/TS..) and there is always a delay and the quality of the video is bad.
On the other hand, android apps like DroidCam stream my phone camera over LAN with such a good video quality and speed.
So my question is why this difference?

A: Could be because of many things between the different apps:
Different resolution and/or frame rate. Better compression thus smaller throughput.
The buffer size may differ.


text:
Q: It is capturing SQL command text supported in .net 4.6 application in Application Insights? Imagine .NET 4.6 console app, that using ADO.NET to query sql database.
    static void Main(string[] args)
    {
        TelemetryConfiguration.Active.InstrumentationKey = "my key";

        var tc = new TelemetryClient(TelemetryConfiguration.Active);

        tc.TrackEvent("App start");

        string ConnString = "Data Source=localhost;Initial Catalog=MyDb;Persist Security Info=True;User ID=sa;Password=****;MultipleActiveResultSets=True";
        string SqlString = "Select * From Customers";
        using (SqlConnection conn = new SqlConnection(ConnString))
        {
            using (SqlCommand cmd = new SqlCommand(SqlString, conn))
            {
                cmd.CommandType = CommandType.Text;

                conn.Open();
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    var res = reader.Read();
                }
            }
        }

        tc.TrackEvent("App stop");
        tc.Flush();
        Thread.Sleep(5000);
    }

It is capturing SQL command text in this case supported? Or it is supported only on IIS and Azure App?
In this sample I would like to see text "Select * From Customers" on Application Insights in dependency event, but this text is not there. There is only dependency with few other properties like duration, client IP, etc., but not sql text.

A: The sql statements are collected by "status monitor", which is running as a .net profiler at runtime, on web apps.
https://learn.microsoft.com/en-us/azure/application-insights/app-insights-asp-net-dependencies
I'll ask around, but i'm pretty sure it isn't easy to hook that up on non-web apps without jumping through a lot of hoops.


text:
Q: Airflow macros not converting to date I have below hive operator where i have to add partitions based on date.
HiveOperator(task_id='add_partition_{}'.format(state),
             hql='alter table my_db.state_wise_records add partition (event_date="{{ ds }}", state="{state}") location "/user/cloudera/state_wise_records/event_date={{ ds }}/state={state}"'.format(state=state),
             dag=dag)

However, This is not converting macros to date rather than that I am getting like below
/user/cloudera/state_wise_records/event_date={ds}/state=UP

What's amiss here?

A: You cannot use string with parameters in combination with Jinja templates. You will have to split in various strings and concatenate them. For instance:
hql = 'alter table my_db.state_wise_records add partition (event_date="{{ ds }}",'
+ 'state="{state}")'.format(state=state)
+ 'location "/user/cloudera/state_wise_records/event_date={{ ds }}/'
+ 'state={state}"'.format(state=state)


text:
Q: Why did uninstalling Wubi not free disk space while virtual hard disk was 15GB? We recently uninstalled Wubi from a Windows Vista computer by selecting Ubuntu in Control Panel and clicking the uninstall button. The uninstaller ran suspiciously fast (it was done in a few seconds while Wubi's virtual hard disk was something like 15GB large), and after checking disk usage, no disk space was freed despite C:\ubuntu isn't there anymore.
Why did uninstalling it not free any disk space and how can I get my disk space back?

A: Normally, uninstalling Wubi from the Control Panel, Add/remove programs, the Ubuntu entry, will completely remove it. In some cases, uninstalling might fail, but it's unlikely for it to succeed and not free up space.
In rare cases, if your Wubi install is corrupted, Windows may automatically run chkdsk (which you should notice when Windows boots if you are watching it) and in that case it could recover the virtual disk to a hidden \found.??? folder on the drive that Wubi is installed on. If this happens you would probably have had issues booting the Wubi install (probably stuck at a grub prompt).
To delete this leftover virtual disk (don't do this if you have data you want to recover), run CMD.EXE as an administrator (right click on it and select "Run as administrator"). Change to the drive the \ubuntu directory was on, and search for the hidden \found.??? directories. And then delete the files to free up space.
C:\>dir /a:h
 Volume in drive C is OS
 Volume Serial Number is 20A3-F99V

 Directory of C:\

2013-01-16  08:42 PM    <DIR>          $Recycle.Bin
2012-05-18  10:08 PM           389,720 bootmgr
2012-06-02  07:30 AM                 1 BOOTNXT
2012-07-26  12:22 AM    <JUNCTION>     Documents and Settings [C:\Users]
2013-01-15  05:08 PM    <DIR>          ESD
2013-01-15  05:08 PM    <DIR>          found.000
2013-05-10  03:50 PM     5,065,179,136 hiberfil.sys
2013-05-10  03:51 PM     1,006,632,960 pagefile.sys
2013-04-12  11:47 AM    <DIR>          ProgramData
2013-05-10  03:51 PM       268,435,456 swapfile.sys
2013-05-14  10:57 AM    <DIR>          System Volume Information
               5 File(s)  6,340,637,273 bytes
               6 Dir(s)   8,312,860,672 bytes free

C:\>cd \found.000
C:\found.000>dir
 Volume in drive C is OS
 Volume Serial Number is 20A3-F99V

 Directory of C:\found.000

19/07/2011  02:02 PM    15,000,000,000 file0000.chk
               1 File(s) 15,000,000,000 bytes
               0 Dir(s)  222,258,069,504 bytes free

C:\found.000>del file0000.chk

If the whole \ubuntu\disks directory was corrupted, you're looking for a directory named dir0000.chk, and inside that you'll find the correctly named root.disk and swap.disk:
C:\>cd found.000

C:\found.000>dir
 Volume in drive C is OS
 Volume Serial Number is 20A3-F99V

 Directory of C:\found.000

19/10/2012  04:51 PM    <DIR>          .
19/10/2012  04:51 PM    <DIR>          ..
19/07/2011  02:02 PM    <DIR>          dir0000.chk
               0 File(s)              0 bytes
               3 Dir(s)  222,258,069,504 bytes free

C:\found.000>dir dir0000.chk
 Volume in drive C is OS
 Volume Serial Number is 20A3-F99V

 Directory of C:\found.000\dir0000.chk

19/10/2012  04:51 PM    <DIR>          .
19/10/2012  04:51 PM    <DIR>          ..
24/02/2012  12:22 AM    <DIR>          boot
06/11/2012  09:28 AM    13,000,000,000 root.disk
15/11/2011  09:28 PM       268,435,456 swap.disk
               2 File(s) 13,268,435,456 bytes
               3 Dir(s)  127,904,968,704 bytes free

C:\>DEL \found.000\dir0000.chk\root.disk

Etc. (delete others and remove the directories)
If you find nothing, then most likely you are mistaken about the space.


text:
Q: Prolog: List of succeeding sub-rules Let's say I have the following rule in Prolog (I am using SWI-Prolog):
rule :-
    subrule_1 ;
    subrule_2 ;
    subrule_3 ;

    ...

    subrule_n.

So "rule" succeeds whenever one of the sub-rules does. I know that as soon as one sub-rule succeeds the others will not be executed. What I want to do is add functionality so that ALL subrules are executed, and create a list of the subrules that succeeded. But "rule" should still fail when none succeed. So far this is all I can think of:
...
rule(Successes), % This is the external call
...

And the rule is:
rule(Succeed_List) :-
    L1 = [],
    ((subrule_1 -> append(L1,['subrule_1'],L2) ; L2 = L1) ,
    (subrule_2 -> append(L2,['subrule_2'],L3) ; L3 = L2) ,
    ...
    (subrule_n -> append(Ln,['subrule_n'],Succeed_List) ; Succeed_List = Ln)),
    \+ length(Succeed_List,0).

Surely there must be a better way to do this! I was thinking of using "bagof" but I am not sure how that would work. My question is, what is a better way of implementing the rule above?
For those wondering "what on earth could those subrules possibly be", I am omitting a lot of details here in terms of what I'm trying to do. If you want to know, each subrule has one argument, the same for each. It is a term with arity 8 but every argument is an atom already bound. The subrules examine the arguments of the term.

A: I think that bagof/3 can do a big part of your task:
rule(Succeed_List) :-
    bagof(P, (member(P, [subrule_1, subrule_2, .., subrule_n]), P), Succeed_List).

you could remove the big argument from P using functor:
rule(Succeed_List) :-
    bagof(F, (member(P, [subrule_1, subrule_2, .., subrule_n]), P, functor(P, F,_)), Succeed_List).


text:
Q: ActiveAdmin formtastic link_to on a collection leading to the show view Just wondering about how to have this link to this to the appropriate supplier_company_view with clickable names. The .to_sentence is optional.
column :supply_companies do |pt|
 pt.supply_companies.collect {|c| c.company_name.capitalize }.to_sentence
end

A: can do it this way but not sure if it is the best way.
column :supply_companies do |pt|
 pt.supply_companies.map { |cn| link_to cn.company_name,
 admin_supply_companies_path + "\/" + cn.id.to_s }.join(", ").html_safe
end


text:
Q: How get determined buttons from class this is not long story!! just it seems to be long ;)
in my app I have user access, it means access to a button relate to its user access scope.
in winform layer: I have a form, it shows all of the determined buttons' name in partitioned checkedListboxes. I dont want fill the form manually. I want create checkedListboxes by code. to get their items'text, I have below planing:
clssMenu_Item: I can save name and text property of one button in this class.
public class clssMenu_Item
{
    public string name;
    public string text;
}

clssMenu_List: it give me 2D generic List<clssMenu_Item>. all of the buttons in one form will be in a object of this class.
public class clssMenu_List
{
    public clssMenu_List ()
    {
           // I dont know how fill private variables
    }
    #region private variables
        private List<clssMenu_Item> _main ; // buttons in main form
        private List<clssMenu_Item> _accountancy; //buttons in accountancy form
        private List<clssMenu_Item> _management; //buttons in management form
    #endregion
    #region public properties

        public List<clssMenu_Item> main
        { get { return _main; } }

        public List<clssMenu_Item> accountancy
        { get { return _accountancy; } }

        public List<clssMenu_Item> management
        { get { return _management; } }

    #endregion
}

the buttons in each forms have a common character in their Name property. For example all of the determined buttons in Main form are started with ''Mbtn'', so there isn't any same buttons' Name between forms.
now I dont know how fill private variables in clssMenu_List. then I could use it in my facade layer.
thanks for your attention my friend!! please help me to solve it

A: I would create a separated helper class that extracts all buttons from a form.
public static class FormHelper
{
    public static Button[] GetButtonsFromForm(Form form)
    {
        // ...
    }
}

I would create properties instead of fields:
public class clssMenu_Item
{
    public string Name {get;set;}
    public string Text {get;set;}
}

A method to create menu_items:
public IEnumerable<clssMenu_Item> GetMenuItemsFromForm(Form form)
{
   // convert the buttons to menu_items
   return from button in FormHelper.GetButtonsFromForm(form);
          select new clssMenu_Item { Name = button.Name, Text = button.Text };
}

Next I would add all buttons to the right list.
public void Fill()
{
    clssMenu_List lst = new clssMenu_List();

    clssMenu_List.main.AddRange(GetMenuItemsFromForm(mainForm));
    clssMenu_List.accountancy.AddRange(GetMenuItemsFromForm(accountancyForm));
    clssMenu_List.management.AddRange(GetMenuItemsFromForm(managementForm));

}

Don't forget to create the list in you class:
    private List<clssMenu_Item> _main = new List<classMenu_Item>(); // buttons in main form
    private List<clssMenu_Item> _accountancy = new List<classMenu_Item>(); //buttons in accountancy form
    private List<clssMenu_Item> _management = new List<classMenu_Item>(); //buttons in management form

Personally:
I would store them in a dictionary because you can access them by name. And I would not create properties of List-types. I'd rather create Add/Remove methods.


text:
Q: Solving second order differential equation numerically with values given at intermediate points. I need to numerically solve the equation,
\begin{equation}
y''(x) + p(x)y(x) = 1
\end{equation}
in the range [a,b]
with conditions
\begin{eqnarray}
y'(\alpha) &=& 1\\
y(\beta) &=& 0  \hspace{1cm} a <\alpha < \beta <b
\end{eqnarray}
if the conditions were given for either of the endpoints, i.e.
\begin{eqnarray}
y'(a) &=& 1\\
y(a) &=& 0
\end{eqnarray}
I can find $y(a+\Delta x)$ using these conditions and rest of the solution can
be found from discretization,
\begin{eqnarray}
\frac{y(x+\Delta x) - 2y(x) + y(x-\Delta x)}{\Delta x^2} + p(x)y(x) = 1
\end{eqnarray}
But if initial value/derivatives are known at different points(that are not successive in discretization) then how can I proceed?

A: I think you can proceed in two different manners:

*

*Solve the problem in the grid corresponding to $x\in [\alpha,\beta]$ and then solve the two initial value problems given by:
$$y_L''+p(x) y_L=1,  \quad a < x < \alpha, \quad y_L(\alpha) = y(\alpha),  \quad y_L'(\alpha) = y_L(\alpha) \tag{1}$$
$$y_R''+p(x) y_R=1,   \quad \beta < x < b, \quad y_R(\beta) = y(\beta), \quad y_R'(\beta) = y_R(\beta) \tag{2}$$
on different suitable grids. Note that the problem for $y_L$ moves backwards and the change of variable $z \equiv \alpha -x$ can fix this issue. Besides, note that $(1)$ and $(2)$ are initial value problems for which you may or may not use another numerical method to solve them.

*The other option would be, provided you adapt your mesh so $\alpha$ and $\beta$ are nodes of the grid, to subsitute the discretized boundary conditions at $x=\alpha$ and $\beta$ while $y_0$ and $y_{N}$ (first and last values of $y_j \approx y(x_j)$) remains unknown (I think this approach is a bit more tedious).
Hope this helps.
Cheers!


text:
Q: Web Dynpro ALV conditionally editable cells The problem is I want that some cell of checkbox column in my WD ALV will be editable some cell will be non editable depending on some property.
I make next steps to achieve the required result:
1) Add attribute READONLY type WDY-BOOLEAN to the corresponding node ( attribute CHECK type WDY-BOOLEAN has already added ) .
2) Then in my code I Check some conditions in row of my table and assign attribute READONLY value abap_true or abap_false.
3) Then I bind my node with  table. Table is filled correctly, I checked in debugger.
4) Configure my alv:
  DATA: lo_table_settings TYPE REF TO if_salv_wd_table_settings,
  lo_column_settings TYPE REF TO if_salv_wd_column_settings,
  lo_column TYPE REF TO cl_salv_wd_column.
  lo_column_settings ?= lv_value.
  lo_table_settings ?= lv_value.

  lo_column = lv_value->if_salv_wd_column_settings~get_column( 'CHECK' ).
  DATA lr_checkbox TYPE REF TO cl_salv_wd_uie_checkbox.

  " create checkbox
  CREATE OBJECT lr_checkbox
  EXPORTING checked_fieldname = 'CHECK'.

  " make our table is editable
  lo_table_settings->set_read_only( abap_false ).

  lo_column = lo_column_settings->get_column( 'CHECK' ).

  " Creating UI Elmenent 'INPUT FIELD' to make the column editable
  DATA: lr_input_field TYPE REF TO cl_salv_wd_uie_input_field.
  CREATE OBJECT lr_input_field EXPORTING value_fieldname = 'CHECK'.

  lr_checkbox->set_read_only_fieldname( value = 'READONLY' ).
  lv_value->if_salv_wd_column_settings~delete_column( ID = 'READONLY' ).

But it doesn't work, all of cells of checkbox column is editable and I don't get non editable cells of checkbox column.

A: To make a field A editable or readonly, it's only a matter of "using a field B's value to the A's readonly property".
So, as I understand , you have a column which is checkbox, and you want some rows to be editable ,and others to be readonly.
To do so, you won't need to create input field, the only thing you need to do is get the checkbox column reference and set its readonly property bind to the field in your data structure.
if that still doesn't work, check your data, whether the readonly field's value of each record is '', if yes, then of course, every cell of the check will be editable.

A: Your first step is correct. You added attribute READONLY of type WDY-BOOLEAN to your node and assigned it abap_true value before calling the grid.
The next step is to create input field reference for each field/row which you wanna make editable and assign this reference to the field attribute READONLY and change this attribute only for the lines that fit the condition.
Here is the sample code:
Initial assignment
 loop at lt_table assigning field-symbol(<fs_table>).
  <fs_table>-read_only = abap_true.    " non editable
 endloop.

Setting column editibility
* input type reference
 data lr_input type ref to cl_salv_wd_uie_input_field.

* Retrieving all column id and reference
call method lv_value->if_salv_wd_column_settings~get_columns
   receiving
    value = data(lt_columns).

loop at lt_columns into ls_columns.
* Assigning column reference
data(lr_column) = ls_columns-r_column.

* Creating input field UI Element
create object lr_input
  exporting
   value_fieldname = ls_columns-id.

*Assigning input field to column to make it as editable
call method lr_column->set_cell_editor
  exporting
   value = lr_input.

* binding input field ref to READONLY field
lr_input->set_read_only_fieldname( value = "READONLY" ).
endloop.

Making single lines editable based on condition
loop at lt_table assigning field-symbol(<fs_table>).
  if smth = abap_true
    <fs_table>-read_only = abap_false.    " non editable
  endif.
endloop.

Check this guide for reference.


text:
Q: Define Pins For Use By a Library xc8 I've got some code i'd like to use in multiple projects so i'd like to put it into a library
The library will use no special features of the chip and whichever two pins it uses to do its job only have to be general I/O
As I plan to use this for multiple projects, these projects will have to specify which pins these two pins are on a project-by-project basis
My question is how I can set up my library and code in each project so that I can define which pins I want to use within each project - independent of the library.
Using XC8 compiler for PIC10s and 16s
Any guidance appreciated

A: I don't know if that changed recently, but a year ago or two I contacted Microchip technical support who confirmed that XC8 doesn't support libraries as such.
What you can do is have the C file in a "shared" folder and include it in the various projects.
The pins can be:

*

*defined by macros (#define) either in compiler options, or in a header of a predefined name e.g. "hardwareconfig.h" which your module would include and the projects supply;

*supplied at initialization by pointers to LAT/PORT registers and masks of the bits;

*your module could declare functions for the low level pin handling, call those, and the various projects would implement them as they see fit.

A: Define a strict that supports bits. Cast that strict to your variables and you have addressable bits.
Or use those ore defined in thee header file.
edit: to just expand a little bit of what I said earlier, here is an example of how this could be done on an 8-pin port.
//define a bit-addresable byte
typedef struct {
    uint8_t B0:1;                           //bit definitions
    uint8_t B1:1;                           //bit definitions
    uint8_t B2:1;                           //bit definitions
    uint8_t B3:1;                           //bit definitions
    uint8_t B4:1;                           //bit definitions
    uint8_t B5:1;                           //bit definitions
    uint8_t B6:1;                           //bit definitions
    uint8_t B7:1;                           //bit definitions
} B8_TypeDef;

//global variables
#define LED0            (((B8_TypeDef *)&PORTB)->B0)    //led0 on PORTB.0

//in your main loop
    while (1) {
        //flip LED0/PORTB.0
        LED0 = 1;                           //set LED0/PORTB.0
        LED0 = 0;                           //clear LED0 / PORTB.0

if you go through the canned header file, you will find an identical approach, except that each typedef has a different name.
here is how it goes in simulation:

The same concept can be done on variables, or 16/32-bit types, to the extend that the compiler support bit types.


text:
Q: Minor change in ansible playbook does not get updated in target host My playbook is (among other things) starting a docker container:
- name: Restart nginx container
  docker:
    name: nginx
    image: my-nginx
    state: started
    ports:
    - "{{ nginx_port }}:80"
    volumes:
    - "{{ host_socket }}:{{ container_socket }}"

This is correctly starting the container. But if I decide I need to run nginx in another port, and run again the playbook, the container is not restarted. It seems that ansible is happy with the container being up and running, but does not verify if the rest of parameters are right.
I see two options here:

*

*force a restart whenever I run the playbook, no conditions asked, so that I make sure that the latest configuration is active. I do not like this because most of the time the parameters do not change.

*force ansible to be more accurate and check all parameters, restarting the container if whatever value has changed. I am not sure there is such an option.

How can I tell ansible to be more accurate when checking the state of the container?

A: The docker module is deprecated, I assume it must be one of its issue.
Did you try the docker_container module? You will need ansible > 2.1.0 but I think it's worth a try.

A:
It seems that ansible is happy with the container being up and running, but does not verify if the rest of parameters are right.

Yes, because you specified state: started, and that's explicitly what that means:

"started" asserts that the matching containers both exist and are running, but takes no action if any configuration has changed.

You probably want reloaded instead:

"reloaded" (added in Ansible 1.9) asserts that all matching containers are running and restarts any that have any images or configuration out of date.


text:
Q: JDBC show rows count I want to print my rows count at the end, But it shows 1
    public void showRecords() {
    try {
        Statement st1 = con.createStatement();
        ResultSet result1 = st1.executeQuery("select * from mytable");
        while (result1.next()) {
            System.out.println(result1.getString(1) + " " + result1.getString(2));
        }

        ResultSet rs1 = st1.executeQuery("select count(*) from mytable");
        int rows = rs1.last() ? rs1.getRow() : 0;
        System.out.println("Number of rows is: "+ rows);  //print 1

    } catch (SQLException sqle) {
        System.out.println("Can not excute sql statement");
        sqle.printStackTrace();
    }
}

Output:
...
Number of rows is: 1

A:
Output: ... Number of rows is: 1

That's absolutely correct because the ouput of a count query like
select count(*) from mytable

would only contain a single row containing the total number of rows. For you to now retrieve that count you should make use of the Resultset's getter methods as usual.
int rows = rs1.getInt(1);

To retrieve the count the way you wanted to; use the same approach with your first query
ResultSet result1 = st1.executeQuery("select * from mytable");
int rows = result1.last() ? result1.getRow() : 0;
System.out.println("Number of rows is: "+ rows);  // should print the count

A: Selecting the count from a RecoredSet always returns a value of 1, i.e. the record containing the result of the query. You want
ResultSet rs1 = st1.executeQuery("select count(*) from mytable");
if (rs1.next()) {
   int rows = rs1.getInt("COUNT")
}

A: You must read the value from the rowcount query, as it is a normal query. Like
rows = rs1.getInt(1);

A: The count(*) does not have a column name (or only a "generated" one that you might not know). Therefor you need to get the value by column index.
Additionally you need to call next() on the ResultSet in order to be able to obtain the value:
ResultSet rs1 = st1.executeQuery("select count(*) from mytable");
int rows = 0;
if (rs1.next() {
  rows = rs1.getInt(1);
}
System.out.println("Number of rows is: "+ rows);  //print 1

A: I've written a blog post about retrieving query metadata without extra roundtrip, which is something people typically do to paginate their data. I really recommend you don't re-run your queries all the time just to count stuff.  A simple approach would be to use window functions, which are now supported in a lot of SQL dialects:
SELECT *, count(*) OVER () FROM mytable

Of course, since you're using low level JDBC API to iterate your ResultSet, why not just count things in the client at that point? E.g.
try (ResultSet rs = s.executeQuery("select * from mytable")) {
    int i = 0;

    while (rs.next()) {
        System.out.println(rs.getString(1) + " " + rs.getString(2));
        i++;
    }

    System.out.println("Number of rows is: " + i);
}


text:
Q: WebBrowserDocumentCompletedEventHandler Don't wait for Ajax Async to complete After reading Dianyang Wu article and this excellent post I managed to build a small .net app (almost a C&P from Wu source code) to automatize tests (let's call it protoTestApp). My final goal is to open a dozen small windows and in each simulate a different user interacting with a web app to stress it.
It works for some extend but after I logon on the web app (let's call it InternalTestSubject) it calls a external url (let's call it ExternalTestSubject) and injects it's content on a iFrame. This particular external url is another web app and it ill look up for the parent window to get some parameters. Opening ExternalTestSubject directly is not a option.
My problem is at my protoTestApp I want to also interact with that ExternalTestSubject (find a button by id, click it, etc) but at my CompletedEvent handler the iFrame is still empty.
The WebBrowser shows both web apps full loaded and working, so I suppose the handler is just not waiting for the iFrame content to load since it's done by a Ajax async call.
Any advice to acomplish it?

A: I think I explained this in the answer you linked (and in more details in another related answer). AJAX pages are non-determinustic, so there is no generic approach.
Use periodic asynchronous polling to watch the page's current HTML snapshot or DOM for changes, the linked post illustrates how to do that. You can poll the frame's content in the same way.

A: I can imagine the frame reports to be ready but it actually does not. For instance, the frame contains frames, you have no way to know whether all these frames are loaded by using DocumentCompleted event.
In short: Using a frame to load external stuff and do the testing is not a good approach. Even if you use a timer to check the loading status manually. But according to security considerations, you will have many problems to access the DOM.
I have two suggestions for you:

*

*Create a WebBrowser instance and open external test subject into it. You will have a very good chance to know, whether document (and its frames) have been loaded completely. You still have the full control to access any elements of the WebBrowser or cookies or click elements or change elements.

*Use 3rd tool such as Selenium as test driver.

Update 1:
As the questioner does not want any 3rd tool, I'd suggest let the internal test subject query the loading completeness of the target frame periodically. Possible code can be check document.readyState == 'complete'.
So far as I know, as the external test subject is embedded as frame, due to security consideration, you might not able to access the DOM of the frame. In other words, you cannot do mouse clicks, etc., unless you change the security settings for the Webbrowser control first.


text:
Q: Simple database editor I am looking for a java based web application that can be deployed to a tomcat and a simple frontend that supports CRUD operations.
I know I can write my own but what I am looking for is something to auto generate the hole application:

*

*Entities

*repositories

*Simple frontend to perform CRUD operations.

A:
I know I can write my own but what I am looking for is something to
auto generate the hole application

You are not going to find a tool that will auto generate your whole application without you having to write something.  There are tools that minimize the amount of code you have to write though.  For example, with Grails you could do this:
grails create-app myapp
cd myapp
grails create-domain-class demo.Person
grails generate-all demo.Person

Edit grails-app/domain/demo/Person.groovy to look like this (this is the only code you would have to write):
package demo

class Person {
    String firstName
    String lastName
}

Now you can run the app with ./gradlew bootRun and a fully functioning CRUD interface will be available at http://localhost:8080/person.
There is a whole lot more than just that which can be done with the app, but that is a very simple way to get a fully functioning CRUD web interface up and running.  That trivial app could literally be written in about 2 or 3 minutes.


text:
Q: Gitlab6 clone not working I have Gitlab6 setup at 192.168.1.74:8001. I want to access that gitlab from 192.168.1.73. I have a account in that and created a new project. Now I want to clone that project by command "git clone git@192.168.1.74:user1/sample-project.git".
It prompted me for password saying "git@192.168.1.74's password: " and I dont know the password as there is no git user on 192.168.1.74. I tried with my gitlab pass but failed. I have already added my shh public keys to my gitlab account.
How to fix this?
Thanks in advance.


text:
Q: Covariance matrix of errors for homoskedasticity/heteroskedasticity I've seen homoskedasticty and heteroskedasticity defined as the following

*

*The error term of our regression model is homoskedastic if the variance of the conditional distribution of $u_{i}$ given $X_{i}, \operatorname{Var}\left(u_{i} \mid X_{i}=x\right)$, is constant for all observations in our sample:
$$
\operatorname{Var}\left(u_{i} \mid X_{i}=x\right)=\sigma^{2} \forall i=1, \ldots, n .
$$

*If instead there is dependence of the conditional variance of $u_{i}$ on $X_{i}$, the error term is said to be heteroskedastic. We then write
$$
\operatorname{Var}\left(u_{i} \mid X_{i}=x\right)=\sigma_{i}^{2} \forall i=1, \ldots, n
$$

*Homoskedasticity is a special case of heteroskedasticity.

$$(\text {  } {u}_{i} \text { is the error term. },X_{i} \text { is the independent variable) }$$
https://www.econometrics-with-r.org/5-4-hah.html
So I am curious if we take it to multiple independent variables, how the  covariance matrix of the errors look.
This is my understanding:
So if we have an error vector $\boldsymbol{u}$,
homoskedastic and uncorrelated errors : covariance matrix is a diagonal matrix $\sigma^2 \boldsymbol{I}$, where the diagonal elements  are all the same value $\sigma^2$
homoskedastic and correlated errors : covariance matrix is  a nondiagonal matrix where the diagonal elements are all the same value $\sigma^2$.
heteroskedastic and uncorrelated errors: covariance matrix is is a diagonal matrix where the diagonal elements are not all  the same value
heteroskedastic and correlated errors: covariance matrix is is a nondiagonal matrix where the diagonal elements are not all the same value.
Is this a correct understanding?


text:
Q: Transport polling error with Socket.Io I'm getting a transport error when using socket.io v1.3.2. It's just meant to be a test for socket.io so I can familiarize myself with it.
I have a file app.js (taken directly from socket.io docs):
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(3000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
});

And a file index.html:
<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <link rel="stylesheet" href="">

Socket Test

In the console, I get the following error:
GET http://localhost/socket.io/?EIO=3&transport=polling&t=1422782880286-40
(index):1 XMLHttpRequest cannot load http://localhost/socket.io/?EIO=3&transport=polling&t=1422782880286-40. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404.
socket.io.js:3715 engine.io-client:socket socket error {"type":"TransportError","description":0} +37ms
socket.io.js:1402 socket.io-client:manager connect_error +38ms
socket.io.js:1402 socket.io-client:manager reconnect attempt error +1ms
socket.io.js:1402 socket.io-client:manager will wait 5000ms before reconnect attempt +0ms
socket.io.js:3715 engine.io-client:socket socket close with reason: "transport error" +2ms
socket.io.js:3715 engine.io-client:polling transport not open - deferring close +1ms
socket.io.js:1402 socket.io-client:manager attempting reconnect +5s
socket.io.js:1402 socket.io-client:manager readyState closed +0ms
socket.io.js:1402 socket.io-client:manager opening http://localhost +0ms
socket.io.js:3715 engine.io-client:socket creating transport "polling" +5s
socket.io.js:3715 engine.io-client:polling polling +0ms
socket.io.js:3715 engine.io-client:polling-xhr xhr poll +0ms
socket.io.js:3715 engine.io-client:polling-xhr xhr open GET: http://localhost/socket.io/?EIO=3&transport=polling&t=1422782885332-41 +1ms
socket.io.js:3715 engine.io-client:polling-xhr xhr data null +0ms
socket.io.js:3715 engine.io-client:socket setting transport polling +1ms
socket.io.js:1402 socket.io-client:manager connect attempt will timeout after 20000 +3ms

Does anyone know how to fix this error. I found this discussion, but have been unable to solve the problem.

A: The difference between your code and the sample on socket.io's site is that the socket.io example code is listening on port 80 and connecting the webSocket on port 80.  You are listening on port 3000, but trying to connect on port 80, thus the connection does not work.  io.connect('http://localhost'); does not specify a port number so it will use the default http port which is port 80.  But, your websocket server is not listening on port 80 so the connection fails.
The simplest way to fix this is to change the line of code in the client from this:
var socket = io.connect('http://localhost');

to this:
var socket = io.connect();

When you leave out the URL, it will, by default, use the domain and port from the current web page (which is what you want).

A: by default, the localhost port is 80. you connected the client's socket to localhost without declaring the port. so it gave you the port 80 by default and your node server is listening to port 3000. in order for your client to connect to your server, you must declare the port which server listens. example: var socket = io.connect('http://localhost:3000');


text:
Q: How to merge multiple csv files into one using hadoop getmerge in azure databricks I am have a folder with lot if csv files in DBFS file system in Azure Data bricks. I am trying to merge all csv files into one using hadoop -getmerge command. Below is the simple shell script I am using.
#!/bin/bash

echo "Merging all part files for CDF updated data into a single dat file"
Hadoop fs -getmerge [-nl] /dbfs/FileStore/final/cdf_inserted/ /dbfs/FileStore/finaldat/csg__cse_dtl_fact__inserted.dat
RC1=$?
if [ $RC1 -eq 0 ];then
  echo "Sucessfully merged all part files for CDF updated data into a single dat file"
elif [ $RC1 -ne 0 ];then
  echo "Failed to merge all part files for CDF updated data into a single dat file"
  exit 1
fi

When I run  %sh sh /dbfs/FileStore/final/exg.sh in databricks notebook I am getting this
error:
/dbfs/FileStore/final/exg.sh: 2: : not found
Merging all part files for CDF updated data into a single dat file
/dbfs/FileStore/final/exg.sh: 4: Hadoop: not found
/dbfs/FileStore/final/exg.sh: 8: Syntax error: "elif" unexpected (expecting "then")

I am in wrong directory of DBFS. Or I am missing something else?


text:
Q: How does State design pattern satisfy the open closed design principle I recently just started learning design patterns using java and I was a bit confused and wondering how does state design pattern satisfy the open closed design principle as I couldn't online resource that has a concrete explanation on this..

A: I really like this book Head First Design Patterns. It has a lot of examples with super simple explanations!
Imagine you have a game where hero can be any person in the world. Let's call him as Hero.
He can run, swim and fly. You have a button where you can change its state or shape.
The code of Hero would look like this:
public class Hero
{
    IState _state;

    public Hero()
    {
        _state = new SpiderManState();
    }

    public void Run()
    {
        _state.Run();
    }

    public void Swim()
    {
        _state.Swim();
    }

    public void Fly()
    {
        _state.Fly();
    }

    public void ChangeShape()
    {
        _state = _state.ChangeChape();
    }
}

Interfaces of IState would look like this:
public interface IState
{
    void Run();

    void Swim();

    void Fly();

    IState ChangeChape();
}

And concrete states look like this:
public class SpiderManState : IState
{
    public void Fly()
    {
        Console.WriteLine("Spiderman is flying");
    }

    public void Run()
    {
        Console.WriteLine("Spiderman is running");
    }

    public void Swim()
    {
        Console.WriteLine("Spiderman is swimming");
    }

    public IState ChangeChape()
    {
       return new IronManState();
    }
}

and IronManState would look like this:
public class IronManState : IState
{
    public void Fly()
    {
        Console.WriteLine("IronMan is flying");
    }

    public void Run()
    {
        Console.WriteLine("IronMan is running");
    }

    public void Swim()
    {
        Console.WriteLine("IronMan is swimming");
    }

    public IState ChangeChape()
    {
        return new SpiderManState();
    }
}

How does State design pattern satisfy the open closed design principle

Next time when you will want to add new State of Hero, you can add just new class like SomeSuperManState without editing Hero class.
So our Hero class is closed for modification, but it is opened for extension.

A: The state pattern is typically used as an extension of the strategy pattern that allows the strategy to be executed in steps or phases over multiple calls.
It implements the open/closed principle in the same way that the strategy pattern does.
Think of an executing workflow, which responds to events differently depending on the progress so far and which step is currently pending.  When it receives an event, it dispatches it to the current step (the state), and the step takes action that can include changing the current step to one of the following ones.
The alternative to the state pattern is just implementing the whole strategy in  a single object that stores internal state.  The state pattern is used to divide up the responsibilities and allow the states to be implemented independently.  It's also naturally emerges when the state must be persisted between calls.


text:
Q: json gzip compression with php I use this way to send serve a json file from my server.
$data = file_get_contents('cache/file.json');

ob_start('ob_gzhandler');

// Output as normal
echo ($data);

cache/file.json is not gzip compressed (plain json, without spaces the whole
file is one long row).
I'm thinking Instead of gzipping the file everytime it is requested.
Should I store it as a gzipped file
$gzjson = gzencode($data, 9);
file_put_contents('gzcache/file.json', $gzjson);

So I will minimize the server load?
The idea is to gzip it and everytime the file is requested
just serve the already gzipped file and not gzip it every time it's requested.
Does anyone think this is a good idea?

A: As your php sands some CPU load to generate zip so it mean - Yes it is good idea to have it cached and just read it instead if you have enough space on server.
Additionally you can implement old cached files remove logic. Check if file creation time( with http://php.net/manual/en/function.filemtime.php )
$creationTime = filemtime($zip);

if(time() - $creationTime >= 60 * 60 * 24 * 2) // 2 days
   @unlink( $zip );
}
// create new zip

and if it older then some range(2 days) delete it and regenerate it again, so it mean you will regenerate that file once per range

A: I would let httpd to serve the json as a static resource. The server should take care about content negotiation and return archived file, if client can unpack it.


text:
Q: Installing uWSGI service on RHEL8 I am trying to install the uWSGI service on RHEL8. After which I should be able to do systemctl start uwsgi.
As far as I can tell from online resources, this should work: yum install uwsgi (or dnf install uwsgi), but gives Error: Unable to find a match: uwsgi. Most resources are on earlier versions of RHEL, but I have not been able to find anything specific for RHEL8.
I have enabled the EPEL repository. yum repolist gives:
repo id                                  repo name                                                      status
*epel                                    Extra Packages for Enterprise Linux 8 - x86_64                   3678
rhel-8-for-x86_64-appstream-rpms         Red Hat Enterprise Linux 8 for x86_64 - AppStream (RPMs)         8289
rhel-8-for-x86_64-baseos-rpms            Red Hat Enterprise Linux 8 for x86_64 - BaseOS (RPMs)            3315
rhel-8-for-x86_64-supplementary-rpms     Red Hat Enterprise Linux 8 for x86_64 - Supplementary (RPMs)       28

I have tried the 'manual' approach, as per https://uwsgi-docs.readthedocs.io/en/latest/Systemd.html, but this hasn't been very successful so far either, and I would prefer to use a system package if at all possible.

A: A good resource to check for packages availability across repositories is pkgs.org. From there you can see uwsgi is just not there yet in RHEL 8 base repositories.
I think they (RedHat) keep it for some later time to release due to its complexity in package/migration.
You can attempt at installing uwsgi from a paid (cheap) third-party repository (disclaimer: I am the maintainer):
sudo dnf install https://extras.getpagespeed.com/release-el8-latest.rpm
sudo dnf install uwsgi

Notables:

*

*This is a rebuild of EPEL packages for EL7 (they are more tuned for RHEL so had to do only a few little tweaks to specs in order to successfully rebuild for EL8)

*I did not try those myself other than install and start uwsgi service (seems to work). Just did for the fun of it :)

*There is no Perl support (quite a bunch of Perl modules need to be packaged for this, way too exhausting and no fun anymore.

*If ever they release packaged uwsgi in the base repository, I don't think there should be any problem upgrading to it then. So feel free to use it as either long term or temporary solution. A full list of installable packages can be found here.


text:
Q: Passing Arabic data from node request to Java server I am trying to send Arabic data from post request of node to Java (Glassfish server, grizzly framework, formatted to be utf-8 for request content). But the request upon receiving in the Java server shows some garbage value "ÙÙاÙبة اÙعاÙÙ " instead of Arabic text.
The request from node is:
var request = require('request');
request.post("http://localhost:8080/taJavaServer/taResponse", {json: true, body: "مواكبة العالم "}, function(err, res, body) {console.log(body);console.log(err)});

So, I dont know how to send exact same Arabic text from node's request post to Java server.
More Info
On calling the java-api via ajax (jQuery), it works fine and Arabic text is getting detected.
$.ajax({
        url: "http://localhost:8080/taJavaServer/taResponse",
        type: 'POST',
        dataType: "JSON",
        data: JSON.stringify({data: "مواكبة العالم "}),
        success: function (respon) {..}...

A: You're not actually sending valid json, try something like this:
request.post("http://localhost:8080/taJavaServer/taResponse", {json: true, body: {data:"مواكبة العالم "}}, function(err, res, body) {console.log(body);console.log(err)});


text:
Q: Query Active Directory and Export using VBScript/WSH I want to query a AD server to get certain fields using VBScript or WSH script
These fields

*

*DN

*userid

*mail

*company

*displayName

And export/output the fields to a text file.
How can I accomplish that?
I came from linux background and need this as the computer that will run the script is running windows
Using linux,
`ldapsearch -x -h hostserver -b "cn=contacts,dc=support,dc=com" CN="name"`

A: The usual method is to use ADO and an LDAP query to retrieve information about AD objects:
Set rootDSE = GetObject("LDAP://RootDSE")

base   = "<LDAP://" & rootDSE.Get("defaultNamingContext") & ">"
filter = "(&(objectClass=user)(objectCategory=Person))"
attr   = "distinguishedName,userid,mail,company,displayName"
scope  = "subtree"

Set conn = CreateObject("ADODB.Connection")
conn.Provider = "ADsDSOObject"
conn.Open "Active Directory Provider"

Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = conn
cmd.CommandText = base & ";" & filter & ";" & attr & ";" & scope

Set rs = cmd.Execute
Do Until rs.EOF
  'do stuff with rs.Fields(fieldname).Value
  rs.MoveNext
Loop
rs.Close

conn.Close

As you can see there is a lot of boilerplate code involved, so I wrote this class (ADQuery) to simplify the handling. The README contains some examples.
If you already know the distinguished name of an object you can also directly retrieve it like this:
dn = "CN=Joe User,OU=Users,DC=example,DC=com"
Set user = GetObject("LDAP://" & dn)
WScript.Echo user.Get("displayName")
WScript.Echo user.Get("mail")
...

A: attr = "distinguishedName,userid,mail,company,displayName"

userid is not part of AD, it is sAMAccountName
Set cmd.CommandText = base & ";" & filter & ";" & attr & ";" & scope

cmd.CommandText is not an object, it is only:
    cmd.CommandText = base & ";" & filter & ";" & attr & ";" & scope

A: You need to use the DirectoryServices namespace. This will give you access to the AD and the required AP to query it.
Directory Searcher object can be used to quert the AD and it returns a SerchResult collection. You can then read the values out of that as strings, easily writable into a text file. Hope this was helpful!