how to calculate expected sample scale mean and sd based on the means and sd's of its dichotomous items?

Question: I am developing a new psychometric scale consisting of a several dichotomous items taken from a larger item bank. The p values (item means) are known. Now I need to calculate the expected mean and standard deviation of the scale after having picked the items. is there a formula, or well known procedure for it? I am looking for the best predicted mean and SD. I know there will allways be uncertainty about the true mean and SD, but for now that's not my main concern.
Many thanks in advance.
Edit. The scale is a lineair combination (just the sum) of the dichotomous items.
edit. This is an example of all the information I have of the picked items (=variables). Unfortenately I don't have the covariances.
<code>   M_item   SD_item
0.8622312   0.344657159720439
0.3368913   0.472647386520131
0.5976337   0.490375020391853
0.6673509   0.471162048842211
0.8394329   0.367131184180246
0.7136281   0.452065299365468
0.7948207   0.403832582701681
0.7589461   0.427722944550313
0.8300466   0.375591855380864
</code>
Comment: Is "digotomous" intended to be "dichotomous"?  Exactly what is the formula for your scale?  (Presumably it's a linear combination of responses, but it doesn't have to be linear.)
Answer: If you are developing a scale, you should collect a new sample using just the questions in your new smaller scale. There are a lot of problems and considerations when estimating mean and variance (especially variance) of a linear combination of means and variances.
However, if you need to get an estimate, the variance of the sum of any 2 random variables is
$$\text{Var}(X+Y) =\text{Var}(X)+\text{Var}(Y)+2\text{Cov}(X,Y)$$
You have more than 2 so the equation becomes
$$\text{Var}\Bigl(\,\sum_{i=1}^n X_i\,\Bigr)=  \sum_{i=1}^n\text{Var}( X_i)+
 2\sum_{i< j} \text{Cov}(X_i,X_j)$$
The mean of the sum of random variables is easier. Just sum the means.
$$\mu_T=\sum_{i=1}^n \mu_i$$
Comment: Yes, you cant get a covariance with just means. You can estimate a range though if you know n. I cant figure out the equation right now, but if you have n, you can figure out the maximum and minimum value that the covar can take, and after adding it to your other estimates you know you overall variance should be within that range. It'll probably be a rather large range however.

Edit: Accidentally deleted previous comment, for future readers, [here](http://stats.stackexchange.com/questions/67019/variance-and-covariance-of-binary-data) is the question with a shortcut for calculating covariance
Comment: Thanks for your answer! This works for dichotomous items as well ofcourse. But I don't think I have the covariances of the items... let me think on this. Do you happen to know an r function that does exactly the same as your formula?
Comment: If all you have is the mean, you cannot calculate the variance of items or covariance between items. You need the original data. Alternatively, you said you had p values. I don't know what the p value means in this context (what is being compared?). However, if you have F or T statistics, mean squared error, and degrees of freedom, you can back out what the variances are. Again, though this depends on what the tests were that generated the p value.
Comment: Regarding dichotomous items, the variance is p(1-p), so you can actually get that from means (since the mean is p).
Comment: by p value I mean variable mean. So I only have means of dichotomous variables. Variance of the variables shouldn't be so hard to caluculate because there are only two possible values of each variable. Covariates are not possible to calculate with as less information as I have, I guess.
Comment: That formula needs all the item scores. In my case I only have the item means.


Como passar informação da segunda ViewController para a primeira ViewController

Question: Estou com problemas para passar uma informação da segunda tela de um NavigationViewController para a primeira tela da NavigationViewController.
Em alguns sites gringos eu achei ensinando a fazer por Protocolo, mas não está funcionando.
Há um modo mais fácil e pratico de fazer?
Obs: A primeira tela é uma ViewController normal e a segunda é uma TableViewController que deve enviar as informações da célula selecionada para a primeira tela.
Answer: A direção que você deve tomar é justamente esta que você encontrou, através de protocolo. É bem simples e isso é independente se é TableViewController ou não.
Vamos supor que você tenha a PrimeiraViewController e SegundaViewController. Nesta segunda, no seu arquivo de cabeçalho .h, criamos o protocolo (antes da declaração @interface):
@protocol SegundaViewDelegate <NSObject>
@required
- (void)foo:(id)bar;
@end

E nesse mesmo arquivo, a propriedade:
@property (nonatomic, retain) id<SegundaViewDelegate> segundaViewDelegate;

No arquivo de implementação .m, seja onde for que você irá passar esse valor, você chama esse método:
[self.segundaViewDelegate foo:[NSDate date]]

Aqui eu passei um NSDate só de exemplo, naturalmente, mas você pode criar seu método como e onde você quiser, no seu caso será quando uma célula for pressionada.
Na PrimeiraViewController, adicionamos este delegate no .h:
@interface PrimeiraViewController : UIViewController <SegundaViewDelegate>

E quando a segunda tela é acionada, definimos este delegate:
SegundaViewController *viewController = [[SegundaViewController alloc] init];
[viewController setSegundaViewDelegate:self];

E implementamos o método que iremos receber as informações:
- (void)foo:(id)bar {
    NSLog("%@", bar);
}

Veja se consegue entender e implementar desta forma.
Comment: A alocação da 'SegundaViewController' devo fazer no prepareForSegue?
Comment: @DavidBatista Isso, já que você usa Storyboard, a alocação é na `prepareForSegue:` mesmo, só alterando para `SegundaViewController *viewController = [segue destinationViewController]`.
Comment: Acredito que este tenha sido meu erro quando testei na primeira vez. Mais tarde farei essa alteração e testar novamente.


Changing a template using user role and publishing variables

Question: I've been trying to get the following function to work in Drupal 7, where an unauthenticated user sees a different article template (in this case, node--article2.tpl) than a user that's logged in.  I get no php errors, but the template doesn't change if I'm logged out. What am I doing wrong here?
<code><?php
   function mytheme_preprocess_node(&$variables) {
   $node = $variables['node'];

   if($node->type === 'article'){
   global $user;
   if($user->uid == 0){
   $variables['template_file'] = 'node__article2';
  }
 }
}
</code>
Additionally, I'd like the function to look at an article's published state as well.  We're using the custom publishing options module that adds a publishing state of "archived."
So basically unauthenticated users will get a different template that has a publishing state of archived.
Comment: Is page caching enabled? If so, the page is cached in one of the two templates.
Comment: Turned if off and it's still not working.  I'm guessing that it's not finding the template file for whatever reason.
Answer: change code

$variables['template_file'] = 'node__article2';

to

$variables['theme_hook_suggestions'][] = 'node__article2';


comando para realizar uma chamada do telefone

Question: Então, estou tentando colocar uma imagem onde a pessoa clica e comece uma ligacação, e neste código devo inserir o telefone, para direcionar. Faz parte de um app mobile, estou fazendo numa pagina html e não manjo nada vcs podem me ajudar?
Comment: Com qual linguagem está sendo feito esse app?
Answer: Olá, faça assim.

Comment: A tag `img` não precisa ser fechada (e nem pode, em HTML normal, sem ser XHTML).


How to distinguish between order.paid event when authorization/capture and just capture?

Question: I asked this question back in 2020: How do I programmatically "place" an order? and provided my own answer there:
Provide an event subscriber:
  public static function getSubscribedEvents() {
    $events['commerce_order.order.paid'][] = ['placeOrder'];
    return $events;
  }

which then applies a transition to the Order:
 public function placeOrder($event) {
    $order = $event->getOrder();
    $order->getState()->applyTransitionById('place');
    return;
 }

This has worked well for the past 2 years but client now wants to split payment authorize and capture. This requires a later step after accepting payment to "capture" the payment. Although the payment capture seems to work and changes payment state to completed; the order balance is not reduced to $0. Removing my code to fix the Order being placed (on admin authorize and capture payments) allows capture to work correctly.
I can likely trigger my transition by something which distinguishes between the 2 types of payments; but suspect I am likely doing something wrong in how I am placing the Order.
EDIT
Changed title to better clarify the requirement.
Comment: And nothing in the order to give a clue as to authorization status. :(
Comment: Maybe you have a look in docroot/modules/contrib/commerce/modules/payment/src/EventSubscriber/OrderPaidSubscriber.php
Depends on your payment provider there are a few modules that integrate payment gateways such as klarna, gmo etc.
Answer: The order of operations here is this:

You create a payment on the backend.
Previously you were capturing immediately, resulting in a completed payment.
When a completed payment is saved, its postSave() function requests an update to the order via the PaymentOrderUpdater service, which recalculates the related order's total_paid field at the end of the page request via its destructor (the destruct() function).
The total_paid is calculated afresh. If it doesn't match the current total_paid value on the order, the order will be saved.
(Note: the first time a draft order is saved, its paid_event_dispatched boolean gets initialized to FALSE in its data array. This is important to the next step.)
When the order is saved by the PaymentOrderUpdater at the end of its updateOrder() function, the OrderStorage checks in the presave process to see if the total_paid is less than order equal to the order total. If so, it dispatches the OrderEvents::ORDER_PAID event you're depending on.
After all order paid subscribers execute, including to apply a state transition, the order is saved.

I don't see why changing from an authorization + capture workflow to an authorization only + capture later workflow would change this process. At the end of the day, steps 3 - 7 only activate when a completed payment is saved, and the process should be no different.
If the PaymentOrderUpdater service is somehow not getting a chance to function, I suppose that would create the instance you're seeing ... but if removing your subscriber solves things, then it sounds more like your subscriber is failing. However, if it is failing, I'd expect you'd see some sort of error. The most common failure I can imagine would be the transition failing to apply because the order is not in a draft state any longer. Since your logic wouldn't get activated until destruction, I suppose the HTTP response has already been streamed, but the save ultimately fails.
You can check your PHP error logs are add debugging to your subscriber, but my hunch is these orders you want to see the balance reduced to $0 on are already placed - i.e. no longer in the draft state.
Comment: Thanks Ryan, I think through all of that you are suggesting I am probably using the correct event to subscribe to but don't really mention how to "place" the order. Looking through the Payment event subscriber, I see they do the same thing I do - so most likely I am doing this correctly. The question then becomes (as I changed title); how to determine when order.paid is hit from auth/capture or just capture. I think you are suggesting they shouldn't be handled differently. Yet they are. I'll post my answer below.
Answer: Looking at default Event Subscriber from the Payment module, it seems as though I am subscribing to the correct event (commerce_order.order.paid) and I am correctly setting the Order to "placed" with:
$order->getState()->applyTransitionById('place');

The issue is then, that I need to execute this when I auth/capture but not when I capture only (as this partially breaks the capture process). This is my code to determine which of these has triggered the order.paid event and allows me to only "place" the order for the correct one.
  public function placeOrder($event) {
    $order = $event->getOrder();

    // Check Payment to see if we are just Capturing now.
    $payment = $this->getPayment($order_id);
    $authorized = $payment->authorized->value;

    // This only needs to be done when in Admin flow
    // - also, don't do this if just Capturing payment
    if (isStaff() && !$authorized) {
      $order->getState()->applyTransitionById('place');
    }
  }

  private function getPayment($order_id) {
    $payments = \Drupal::entityTypeManager()
      ->getStorage('commerce_payment')
      ->loadByProperties(['order_id' => $order_id]);
    $payment = current($payments);
    return $payment;
  }

This does seem a bit convoluted; so possibly there is a bug tied up in Commerce here somewhere. Commerce maintainers have suggested in the past that the admin payment flow is less supported than the customer flow - so possibly that explains the requirement for this.


Add new data in database using TypeOrm

Question: I am using in my NestJs application type-orm.
I have 2 entities:

User

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ nullable: true })
  gender: string;

  @OneToMany(() => Address, (address) => address.user)
  address: Address;
}

Address

@Entity()
export class Address {
  @PrimaryGeneratedColumn()
  id: number;

  @ManyToOne(() => User, (user) => user.address)
  user: User;
}

The idea is next: Each user can have multiple addresses, this is why i used OneToMany.
My provider looks like this:

async add(): Promise < User > {
  try {
    const newPost = this.usersRepository.create({
      gender: 'm',
    });
    return await this.usersRepository.save(newPost);
  } catch (err) {
    return err;
  }
}

It works and in db, in the table user i  can add gender: 'm'.
Issue: How to add in add() function and the addresses, because now i can add just the user.  Question: How to change the add() function to be able to add and addresses?
Answer: First of all, you have to fix the User entity by making addresses as an Array of addresses,
    @Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ nullable: true })
  gender: string;

  @OneToMany(() => Address, (address) => address.user)
  address: Address[];
}

For your question, you can achieve adding the address by saving them first then bind them with the user:
   async add(): Promise < User > {
  try {
    let adresses:Array<Address> = [] ; array of type Address entity
 for(let adress of sourceOfyouAdressses) //sourceOfyouAdressses = the array of addresses you want add
   {
    let  adrs =  await this.adress Repository.save({city: adress.city }); // here you save you adress informations
    adresses.push(adrs );
   }
const newPost = this.usersRepository.create({
      gender: 'm',
      address:adresses
    });
    return await this.usersRepository.save(newPost);
  } catch (err) {
    return err;
  }
}

Comment: could you help please https://stackoverflow.com/questions/65907844/update-a-column-in-database-in-nodejs
Comment: Sure, thanks to accepting this answer if it resolves your problem
Comment: could you take a look please https://stackoverflow.com/questions/66210852/get-hidden-field-from-database-using-nestjs

Add new data in database using TypeOrm


Angular 6: How to implement route guard with auth service

Question: How to use data from auth.service.ts in route guard. From auth.service.ts I use verify token api to check the validity (test in postman return {"valid" : true}). But I do not understand how to implement with route guard.
Code for auth.service.ts to verify token. If token valid return true
 verifyToken(id:string, token: string) {
    const params = new HttpParams().set('a', id).set('b', token);

    this.base_url = environment.MYAPI_REST_API_URL;

    this.customersObservable = this.httpClient.get(this.base_url +'/registration/application/verifyConfirmationToken', {params});

     this.data = JSON.stringify(this.customersObservable);

     return this.data;
}

Code for route Guard
 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    this.route.queryParams.subscribe(params => {
        this.id = params['a'];
        this.token = params['b'];
    });

    if (this.auth.verifyToken(this.id,this.token)) {
        // logged in so return true
        return true;
    }

    // not logged in so redirect to login page with the return url
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
    // window.location.href='http://www.cnn.com/';
    return false;
}

Comment: In the verify token method, you should validate the token, but that's what you are not doing in that method, you can use `angular-jwt` library to check whether token is valid or not https://github.com/auth0/angular2-jwt
Comment: Why are you making api call in the verify token method? Just to validate token?
Comment: .subscribe is async, you don't get the data immediately, so in verifyToken arg will unset
Comment: Not clear about the implementation you have done. Simply return a `boolean` from the `verifyToken` method and let that know in the canActivate method. canActive method just want to return true or false. Don't add so much responsibility in the canActivate method
Answer: Yes you can do this by creating Auth Guard service.

// Auth Gaurd Service
// In AuthGaurdService

@Injectable()
class CanTokenActive implements CanActivate {
  constructor(private currentUser: UserToken) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean>|Promise<boolean>|boolean {
    // Logic to check token is exist or not.
  }
}

// In routhing module

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'home',
        component: Home,
        canActivate: ['canTokenActive']
      }
    ])
  ]
 })
class AppModule {}
Answer: 1)
ng generate guard auth   [ Create guard, the file name would be like
auth.guard.ts ]

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from
'@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import {Router} from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private auth: AuthService,
    private myRoute: Router){
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> |
   boolean {
    if(this.auth.isLoggednIn()){
      return true;
    }else{
      this.myRoute.navigate(["login"]);
      return false;
    }
  }
}

2)  ng g c login  [Create login page ]
ng g c nav  [Create nav page ]
ng g c home  [Create home page ]
ng g c registration  [Create registration page ]

3) App.module.ts file add below contents

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule,Router,Routes } from '@angular/router';
import { ReactiveFormsModule,FormsModule } from '@angular/forms';
import { AuthService } from './auth.service';
import { AuthGuard } from './auth.guard';

import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { NavComponent } from './nav/nav.component';
import { HomeComponent } from './home/home.component';
import { RegistrationComponent } from
'./registration/registration.component';

// canActivate added for AuthGuard.
// Add in Providers: [AuthService,AuthGuard],

const myRoots: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' , canActivate:
  [AuthGuard]},
  { path: 'register', component: RegistrationComponent },
  { path: 'login', component: LoginComponent},
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard]}
];

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    NavComponent,
    HomeComponent,
    RegistrationComponent
  ],
  imports: [
    BrowserModule,ReactiveFormsModule,FormsModule,
    RouterModule.forRoot(
      myRoots,
      { enableTracing: true } // <-- debugging purposes only
    )
  ],
  providers: [AuthService,AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }

4) Add link in nav.component.html

  <button  routerLink="/home">Home</button>
  <button  *ngIf="!auth.isLoggednIn()"
  routerLink="/register">Register</button>
  <button  *ngIf="!auth.isLoggednIn()" routerLink="/login">Login</button>
  <button  *ngIf="auth.isLoggednIn()"
  (click)="auth.logout()">Logout</button>

4.1)  Add in nav.component.ts file

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
  constructor(public auth: AuthService) { }
  ngOnInit() {
  }
}

5)
ng g service auth  [Create service page Add below code in authservice.ts]

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable()
export class AuthService {
  constructor(private myRoute: Router) { }
  sendToken(token: string) {
    localStorage.setItem("LoggedInUser", token)
  }
  getToken() {
    return localStorage.getItem("LoggedInUser")
  }
  isLoggednIn() {
    return this.getToken() !== null;
  }
  logout() {
    localStorage.removeItem("LoggedInUser");
    this.myRoute.navigate(["Login"]);
  }
}

6) add content in login.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  form;
  constructor(private fb: FormBuilder,
    private myRoute: Router,
    private auth: AuthService) {
    this.form = fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', Validators.required]
    });
  }
  ngOnInit() {
  }
  login() {
    if (this.form.valid) {
      this.auth.sendToken(this.form.value.email)
      this.myRoute.navigate(["home"]);
    }
  }
}

6.1)  add in logincomponent.html page

<form [formGroup]="form" (ngSubmit)="login()">

<input  type="email" placeholder="Email" formControlName="email" />

<input  type="password" placeholder="Password" formControlName="password"
/>

<button type="submit" color="primary">Login</button>
</form>

7) Add below code in app.component.html

<app-nav></app-nav>
<router-outlet></router-outlet>


Bounding a cubic form with a quadratic form

Question: We have a positive definite quadratic form $Q(x,y)$, and we have a sequence $(x_n,y_n,z_n)$ satisfying $\lim_{n\to\infty}\frac1{z_n}Q(x_n,y_n) = 0$.
We want to show that $\lim\limits_{n\to\infty}\frac{x_n^3+\alpha y_n^3}{z_n^{3/2}}=0$, where $\alpha$ is a positive constant.
I've already shown it by setting $Q(x,y)=\epsilon$, using Lagrange multipliers to maximize $g_n(x,y)=\frac{x^3+\alpha y^3}{z_n^{3/2}}$, and obtaining a maximum value of $c\epsilon^{3/2}$ for some positive $c$. I suspect this is inelegant, and I wonder if there's some obvious better way that I'm missing.
I note that, in the calculation described above, I used the specific formula of $Q$, which I have available. I haven't provided it, because I'm looking for a solution that is independent of knowing that formula, because my intuition tells me it's something that should work for all positive definite quadratic forms. I hope there's a coordinate free argument, maybe working in the variables $\frac{x}{\sqrt{z}}$ and $\frac{y}{\sqrt{z}}$?
I'm grateful for any insights anyone can provide.
Answer: As $Q$ is positive-definite, there are $m$, $M>0$ with
$$m(x^2+y^2)\le Q(x,y)\le M(x^2+y^2)$$
for all $x$ and $y$. Thus
$$|x_n|^3\le(x_n^2)^{3/2}\le A Q(x_n,y_n)^{3/2}$$
for some constant independent of $n$. Likewise
$$|y_n|^3\le Q(x_n,y_n)^{3/2}.$$
So
$$\left|\frac{x_n^3+\alpha y_n^2}{z_n^{3/2}}\right|
\le A(1+\alpha)\left(
\frac{Q_n(x_n,y_n)}{z_n}\right)^{3/2}\to0.$$
Comment: I expected something looking like this would work. That initial fact, about bounds on positive definite quadratic forms: is that a standard result? I have a hard time finding a good text that covers these things.


Is a proxy web server the same as a firewall application gateway?

Question: I need a clarification regarding proxy server.
Is a web proxy server (in this case installed on win server) the type of a firewall? I thought these two are different. I am currently learning about firewalls and I see that the author mentions application firewall gateway but actually describes a proxy server.
I know they are different in essence since they operate on different layers but this made me a bit confused. Is a proxy server really a type of a firewall?
Thanks
Answer: Proxy is a relay that accepts a connection and makes its own connection on your behalf. Firewall is a rules based network security system.
Sophisticated firewalls likely include security aware proxies. Security oriented in that they understand application details like protocols, encryption such as TLS, and hopefully user identity.  And via proxy, as where else are you going to put it, other than a proxy middlebox?
But no, a proxy doesn't mean a firewall. These are broad categories of network services. Beware when making broad statements:

Not all proxies are security oriented, some do other services like load balancing.
Not every proxy is web, there are proxies for non-http protocols.
Not every firewall is a layer 3 packet filter. Layer 4-ish knowledge is useful for connection tracking. Application level knowledge allows for smarter decisions than when limited to a TCP/IP 5-tuple.
Not every firewall is application aware, either. Sometimes, a layer 4 packet filter is sufficient.


Strategy for fitting highly non-linear function

Question: For analyzing data from a biophysics experiment, I'm currently trying to do curve fitting with a highly non-linear model. The model function looks basically like:
$y = ax + bx^{-1/2}$
Here, especially the value of $b$ is of great interest.
A plot for this function:

(Note that the model function is based on a thorough mathematical description of the system, and seems to work very well --- it's just that automated fits are tricky).
Of course, the model function is problematic: fitting strategies I've tried thus far, fail because of the sharp asymptote at $x=0$, especially with noisy data.
My understanding of the issue here is that simple least-squares fitting (I've played with both linear and non-linear regression in MATLAB; mostly Levenberg-Marquardt) is very sensitive to the vertical asymptote, because small errors in x are hugely amplified.
Could anyone point me to a fitting strategy that could work around this?
I have some basic knowledge of statistics, but that's still pretty limited. I'd be eager to learn, if only I'd know where to start looking :)
Thanks a lot for your advice!
Edit Begging your pardon for forgetting to mention the errors. The only significant noise is in $x$, and it's additive.
Edit 2 Some additional information about the background of this question. The graph above models the stretching behavior of a polymer. As @whuber pointed out in the comments, you need $b \approx -200 a$ to get a graph like above.
As to how people have been fitting this curve up to this point: it seems that people generally cut off the vertical asymptote until they find a good fit. The cutoff choice is still arbitrary, though, making the fitting procedure unreliable and unreproducible.
Edit 3&4 Fixed graph.
Comment: Do the errors come in $x$ or in $y$ or both?  In what form do you expect noise to enter (multiplicative, additive, etc.)?
Comment: @onnodb: My concern is, might this not fundamentally question how robust your model itself is? No matter what fitting strategy you use won't $b$ remain highly sensitive? Can you ever have a high confidence in such an estimate for $b$?
Comment: Unfortunately, that still won't work. There simply is no possible combination of $a$ and $b$ that will even qualitatively reproduce the graph you have drawn.  (Obviously $b$ is negative.  $a$ must be less than the least slope in the graph, yet positive, which puts it into a narrow interval. But when $a$ is in that interval, it simply is not large enough to overcome the huge negative spike at the origin introduced by the $b x^{1/2}$ term.)  What have you drawn?  Data?  Some other function?
Comment: Thanks, but it's still wrong. Extending the tangent to this graph backwards from *any* point $(x,ax+bx^{1/2})$ where $x\gt 0$, you will intercept the y-axis at $(0,3b/(2x^{1/2}))$. Because the downward spike at $0$ shows $b$ is negative, this y-intercept has to be negative, too. But in your figure it is abundantly clear that most such intercepts are positive, extending as high as $15.5$. Thus **it is mathematically impossible that an equation like $y=ax + bx^{1/2}$ can describe your curve**, *not even approximately.* At a minimum you need to fit something like $y=ax+bx^{1/2}+c$.
Comment: Before I did any work on this, I wanted to make sure of the statement of the question: that's why it's important to get the function correct. I haven't time to give a full answer now, but would like to remark that "other people" may be wrong--but it depends on yet more details, alas. If your $x$ error is truly *additive* it seems to me it must still be strongly heteroscedastic, for otherwise its variance at small values of $x$ would be truly tiny. What can you tell us--quantitatively--about that error?
Comment: @probabilityislogic Thanks for pointing that out! Question edited.
Comment: When you say fitting strategies fail, what exactly happens?
Comment: @curious_cat They produce fits that are clearly off (visually). If I simulate data, and fit them again, I get wildly different parameter values, combined with fits that *look* bad. Cutting off the vertical asymptote helps, but then the fit parameters tend to depend on the cutoff position. Does that answer your question? Thanks for chiming in!
Comment: @onnodb: Also, how many data points do you have? And how many fall in that initial spike region?
Comment: @curious_cat The robustness question is a very good one, and one I've been worrying about a lot. Still, I do feel that producing a good fit *should* be possible, since doing it by hand seems easy enough. Would there be a way to have a least-squares error based on 'proximity' in the x-y plane, instead of x or y error? (Or is that a silly question?)
Regarding the number of data points: this can be arbitrarily high (thousands of points would be no problem). Since in the experiment we actually control $y$, especially the vertical asymptote is easy to measure very fine-grained.
Comment: @onnodb: About your proximity question:  "PCA effectively minimizes error orthogonal to the model" Look here: http://i.stack.imgur.com/bOl5N.png and http://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues Though, I'm not sure if or not this is relevant.
Comment: Hm, yeah, but PCA would only be useful for fitting a linear model --- unless you start looking into nonlinear PCA algorithms, but I don't think they'd be useful. Thanks for the suggestion, though!
Comment: I cannot make a graph of $y = a x + b / \sqrt{x}$ look like the one shown here until I introduce a sizable additive constant. What exactly is this figure depicting?
Comment: @whuber Good point; see Edit 2.
Comment: @whuber Apologies, the bit to the right was indeed incorrect --- a leftover from a different model function which is besides the point. The current graph should be fine.
Comment: @whuber Of course, you are absolutely right. Pardon my sloppiness --- experimental physicist at work ;) Graph is fixed now. Basic problem is still the same though: how to fit a function that displays asymptotic behavior in both the $x$ and $y$ direction? Discussion with other people suggest that very high-precision data would be needed for the vertical asymptote regime, and then it might work without problems.
Comment: Yes, thanks for correcting the graph, @whuber. Of course, I'm happy to provide more details! $x$ is the force on a polymer, which we can measure with a precision of around 0.5--1 (bottleneck being instrument noise). Variance in $x$ stays the same over the whole range of $y$, basically. Does that help?
Answer: The methods we would use to fit this manually (that is, of Exploratory Data Analysis) can work remarkably well with such data.
I wish to reparameterize the model slightly in order to make its parameters positive:
$$y = a x - b / \sqrt{x}.$$
For a given $y$, let's assume there is a unique real $x$ satisfying this equation; call this $f(y; a,b)$ or, for brevity, $f(y)$ when $(a,b)$ are understood.
We observe a collection of ordered pairs $(x_i, y_i)$ where the $x_i$ deviate from $f(y_i; a,b)$ by independent random variates with zero means.  In this discussion I will assume they all have a common variance, but an extension of these results (using weighted least squares) is possible, obvious, and easy to implement.  Here is a simulated example of such a collection of $100$ values, with $a=0.0001$, $b=0.1$, and a common variance of $\sigma^2=4$.

This is a (deliberately) tough example, as can be appreciated by the nonphysical (negative) $x$ values and their extraordinary spread (which is typically $\pm 2$ horizontal units, but can range up to $5$ or $6$ on the $x$ axis).  If we can obtain a reasonable fit to these data that comes anywhere close to estimating the $a$, $b$, and $\sigma^2$ used, we will have done well indeed.
An exploratory fitting is iterative.  Each stage consists of two steps: estimate $a$ (based on the data and previous estimates $\hat{a}$ and $\hat{b}$ of $a$ and $b$, from which previous predicted values $\hat{x}_i$ can be obtained for the $x_i$) and then estimate $b$.  Because the errors are in x, the fits estimate the $x_i$ from the $(y_i)$, rather than the other way around.  To first order in the errors in $x$, when $x$ is sufficiently large,
$$x_i \approx \frac{1}{a}\left(y_i + \frac{\hat{b}}{\sqrt{\hat{x}_i}}\right).$$
Therefore, we may update $\hat{a}$ by fitting this model with least squares (notice it has only one parameter--a slope, $a$--and no intercept) and taking the reciprocal of the coefficient as the updated estimate of $a$.
Next, when $x$ is sufficiently small, the inverse quadratic term dominates and we find (again to first order in the errors) that
$$x_i \approx b^2\frac{1 - 2 \hat{a} \hat{b} \hat{x}^{3/2}}{y_i^2}.$$
Once again using least squares (with just a slope term $b$) we obtain an updated estimate $\hat{b}$ via the square root of the fitted slope.
To see why this works, a crude exploratory approximation to this fit can be obtained by plotting $x_i$ against $1/y_i^2$ for the smaller $x_i$.  Better yet, because the $x_i$ are measured with error and the $y_i$ change monotonically with the $x_i$, we should focus on the data with the larger values of $1/y_i^2$. Here is an example from our simulated dataset showing the largest half of the $y_i$ in red, the smallest half in blue, and a line through the origin fit to the red points.

The points approximately line up, although there is a bit of curvature at the small values of $x$ and $y$.  (Notice the choice of axes: because $x$ is the measurement, it is conventional to plot it on the vertical axis.)  By focusing the fit on the red points, where curvature should be minimal, we ought to obtain a reasonable estimate of $b$.  The value of $0.096$ shown in the title is the square root of the slope of this line: it's only $4$% less than the true value!
At this point the predicted values can be updated via
$$\hat{x}_i = f(y_i; \hat{a}, \hat{b}).$$
Iterate until either the estimates stabilize (which is not guaranteed) or they cycle through small ranges of values (which still cannot be guaranteed).
It turns out that $a$ is difficult to estimate unless we have a good set of very large values of $x$, but that $b$--which determines the vertical asymptote in the original plot (in the question) and is the focus of the question--can be pinned down quite accurately, provided there are some data within the vertical asymptote.  In our running example, the iterations do converge to $\hat{a} = 0.000196$ (which is almost twice the correct value of $0.0001$) and $\hat{b} = 0.1073$ (which is close to the correct value of $0.1$).  This plot shows the data once more, upon which are superimposed (a) the true curve in gray (dashed) and (b) the estimated curve in red (solid):

This fit is so good that it is difficult to distinguish the true curve from the fitted curve: they overlap almost everywhere.  Incidentally, the estimated error variance of $3.73$ is very close to the true value of $4$.
There are some issues with this approach:

The estimates are biased.  The bias becomes apparent when the dataset is small and relatively few values are close to the x-axis.  The fit is systematically a little low.
The estimation procedure requires a method to tell "large" from "small" values of the $y_i$.  I could propose exploratory ways to identify optimal definitions, but as a practical matter you can leave these as "tuning" constants and alter them to check the sensitivity of the results.  I have set them arbitrarily by dividing the data into three equal groups according to the value of $y_i$ and using the two outer groups.
The procedure will not work for all possible combinations of $a$ and $b$ or all possible ranges of data.  However, it ought to work well whenever enough of the curve is represented in the dataset to reflect both asymptotes: the vertical one at one end and the slanted one at the other end.

Code
The following is written in Mathematica.
estimate[{a_, b_, xHat_}, {x_, y_}] :=
  Module[{n = Length[x], k0, k1, yLarge, xLarge, xHatLarge, ySmall,
    xSmall, xHatSmall, a1, b1, xHat1, u, fr},
   fr[y_, {a_, b_}] := Root[-b^2 + y^2 #1 - 2 a y #1^2 + a^2 #1^3 &, 1];
   k0 = Floor[1 n/3]; k1 = Ceiling[2 n/3];(* The tuning constants *)
   yLarge = y[[k1 + 1 ;;]]; xLarge = x[[k1 + 1 ;;]]; xHatLarge = xHat[[k1 + 1 ;;]];
   ySmall = y[[;; k0]]; xSmall = x[[;; k0]]; xHatSmall = xHat[[;; k0]];
   a1 = 1/
     Last[LinearModelFit[{yLarge + b/Sqrt[xHatLarge],
          xLarge}\[Transpose], u, u]["BestFitParameters"]];
   b1 = Sqrt[
     Last[LinearModelFit[{(1 - 2 a1 b  xHatSmall^(3/2)) / ySmall^2,
          xSmall}\[Transpose], u, u]["BestFitParameters"]]];
   xHat1 = fr[#, {a1, b1}] & /@ y;
   {a1, b1, xHat1}
   ];

Apply this to data (given by parallel vectors x and y formed into a two-column matrix data = {x,y}) until convergence, starting with estimates of $a=b=0$:
{a, b, xHat} = NestWhile[estimate[##, data] &, {0, 0, data[[1]]},
                Norm[Most[#1] - Most[#2]] >= 0.001 &,  2, 100]

Comment: This is an amazing answer; I'm much obliged! I've been playing with this, and the results look very promising. I'll need a bit more time to fully understand the reasoning, though :)
Also: could I contact you through your website for one additional (private) question, regarding acknowledgements?
Answer: See the important questions @probabilityislogic posted
If you only have errors in y, and they're additive and you have constant variance (i.e. your assumptions fit what it sounds like you did), then if you let $y^* = y\sqrt{x}$, you could perhaps try a weighted linear fit of $y^*$ on $x^* = x^{3/2}$, where the weights will then be proportional to $1/x$ ... (and yes, this might simply be shifting the problem around, so it may still be problematic - but you should at least find it easier to regularize with this transformation of the problem).
Note that with this manipulation, your $b$ becomes the intercept of the new equation
If your variances are already not constant or your errors aren't additive or you have errors in the $x$, this will change things.
--
Edit to consider the additional information:
We got to a model of the form: $y^* = b + a x^*$
We now have that the errors are in x and additive. We still don't know if the variance is constant on that scale.
Rewrite as $x^* = y^*/a - b/a = m y^* + c$
Let $x_o^* = x^* + \eta$, where this error term may be heteroskedastic (if the original $x$ has constant spread, it will be heteroskedastic, but of known form)
(where the $o$ in $x_o^*$ stands for 'observed')
Then $x^*_o = c +  m y^* + \epsilon$  where $\epsilon = -\zeta$ looks nice but now has correlated errors in the $x$ and $y$ variables; so it's a linear errors-in-variables model, with heteroskedasticity and known form of dependence in the errors.
I am not sure that improves things! I believe there are methods for that kind of thing, but it's not really my area at all.
I mentioned in the comments that you might like to look at inverse regression, but the particular form of your function may preclude getting far with that.
You might even be stuck with trying fairly robust-to-errors-in-x methods in that linear form.
--
Now a huge question: if the errors are in x, how the heck were you fitting the nonlinear model? Were you just blindly minimizing the sum of squared errors in $y$? That might well be your problem.
I suppose one could try to rewrite the original thing as a model with errors in the $x$ and try to optimize the fit but I am not sure I see how to set that up right.
Comment: ...or you could directly fit the model $x = \frac{1}{3} \left(\frac{2 y}{a}+\frac{2^{1/3} y^2}{\left(27 a^4 b^2-2 a^3 y^3+3 \sqrt{3} \sqrt{27 a^8 b^4-4 a^7 b^2 y^3}\right)^{1/3}}+\frac{\left(27 a^4 b^2-2 a^3 y^3+3 \sqrt{3} \sqrt{27 a^8 b^4-4 a^7 b^2 y^3}\right)^{1/3}}{2^{1/3} a^2}\right)$ :-).
Comment: "*even though the errors are in x*" -- yikes, that's kind of important. You may want to check up on inverse regression.
Comment: Thanks! It's an interesting transformation, hadn't thought of that --- even though the errors are in $x$, I'll play around with it anyway!
Comment: @whuber Hmm. Solving for the cubic, clever. If we write the original in terms of $x_o$ where $x_o$ is $x + \zeta$, this would leave us with $x = (\rm{that\,\, monster}) + \epsilon\,$, (again with $\epsilon = -\zeta$) which at least notionally can be done with nonlinear least squares. So that looks like it takes care of the error propagation properly. It *might* actually work if the OP was to use the linear form I was playing with (using some  robust-to-errors-in-the-IV-and-hetero estimation) to get good starting values for the parameters and then try to use this nonlinear LS form to polish it.
Comment: I believe linearizing the function $x(y)$ and (ironically) applying nonlinear (weighted) least squares would work, especially if the data were restricted to relatively small values of $y$ where the curve is primarily determined by $b$.
Comment: Thanks for the extensive reply, Glen. I'll have to sit down and study this, which might take a few days (I'm leaving for a short conference this morning). I'll get back to you, though! Thanks again!
Answer: After some more weeks of experimenting, a different technique seems to work the best in this particular case: Total Least Squares fitting. It's a variant of the usual (nonlinear) Least Squares fitting, but instead of measuring fit errors along just one of the axes (which causes problems in highly nonlinear cases such as this one), it takes both axes into account.
There's a plethora of articles, tutorials and books avaiable on the subject, although the nonlinear case is more elusive. There's even some MATLAB code available.
Comment: Thanks for sharing this.  I accept that it it might produce good-looking results in your case, but I have two concerns.  The first you mention: how exactly does one apply total least squares/errors-in-variables regression/orthogonal regression/Deming regression to nonlinear fits?  The second is that this approach does not seem appropriate for your data, in which $y$ is measured essentially without error.  When that's the case, you should *not* be allowing for residuals in the $y$ variable and doing so *ought* to produce unreliable, biased results.
Comment: @whuber Thanks for expressing your concerns! Right now, I'm still working on running simulations to probe the reliability of TLS fitting for this problem. What I've seen thus far, though, is that TLS' consideration of *both* variables helps greatly in overcoming the high non-linearity of the model. Fits of simulated data are reliable and converge very well. More work needs to be done though, and I'll definitely have to stack your method up to this one, once we have more actual data available --- and look in detail into your concerns.
Comment: OK--don't forget I have comparable concerns about the method I proposed!


Conditional Stylesheets Set-up: Using the Module

Question: Problem
I'm trying to set-up conditional stylesheets. I've followed the instructions but it's still not registering. What have I done wrong?
Set-Up
I installed and enabled the conditional stylesheets module. I'm running a Tao sub-theme.
I then added the following lines to my theme.info file:
//these are my original stylesheets
stylesheets[all][] = reset.css
stylesheets[all][] = typography.css

//these are my conditional stylesheets
conditional-stylesheet [IE][all][] = styleie7.css
conditional-stylesheets [if !IE][all][] = style.css

I then cleared my cache and no style sheets were loaded.
At the moment I'm just trying to have one stylesheet for IE and one for everything else.
I took the syntax from the [link] in the conditional css directory.1
NOTE:
It's not clear whether you should put
conditional-stylesheet OR stylesheet-conditional

The documentation says one, a lot of posts suggest the other. However I can't get either of them to work.
Answer: Assuming you are using the conditional style module the format would be
; Set the conditional stylesheets that are processed by IE.
stylesheets-conditional[lt IE 7][all][] = ie6-and-below.css
stylesheets-conditional[IE 9][all][] = ie9.css
stylesheets-conditional[IE][print][] = ie-print.css
stylesheets-conditional[(gte IE 9)|(gt IEMobile 7)|(!IE)][all][] = modern-browsers.css

And there should be no space between the conditional-stylesheet and [IE].
If that doesn't work then you should make sure that the stylesheet it is referencing can be loaded. The stylesheet lines don't show up if the stylesheet doesn't exist or cannot be opened.
Comment: Cheers, turns out how I had a couple problems. First was the space, the second was I was using putting in an `[if]`, which the module adds automatically so I had two `[if]'s`. Weirdly it also didn't work at all on my Windows 7 machine. I had to switch to XP.
Answer: My final code in my .info file is:
stylesheets-conditional[!IE 6][all][] = typography.css
stylesheets-conditional[IE 6][all][] = typographyie6.css

stylesheets-conditional[IE 6][all][] = styleie6.css
stylesheets-conditional[IE 7][all][] = styleie7.css

I had three problems. First I had an extra space. Second I was putting [if] into the conditional statements i.e.
stylesheets-conditional[if IE 6][all][] = styleie6.css

The module already adds an [if] so it was printing out:

Lastly I couldn't get it work at all on my Windows 7 machine, but switching to XP worked fine.
IE6 & 7 don't work very well on Windows 7 (hacks needed...) so might be worth setting up an XP test machine as you wouldn't need them to work on 7 anyway.


StaleElementReferenceException even when having explicit wait

Question: I've been trying to crawl data from the website AlgoExplorer. It has a table with pagnigation to store data. Even though I use an Explicit Wait for clicking a 'next' button, it still get StaleException.
Here is a piece of my code, and an image of error:
<code>for i in tqdm(range(5)):
  page = driver.find_element_by_tag_name('tbody').find_elements_by_tag_name('a')
  for e in page:
    pages.append(e.text)
  WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.pagination.next'))).click()
</code>
Of course, every variable has been declared and library has been imported.
Can you please explain me why I still have that exception?
enter image description here
Comment: Provide the HTML... Maybe try to wait for element presence, and after that implement clickable.
Comment: @GajJulije thanks for replying me. I also tried it. I even tried to wait for element (that I need) visibility, crawl it, and then wait for button clickable to click it. It still doesn't work. However, Im not sure what parts of HTML I can caption to show here?
Answer: StaleElementReferenceException is thrown when an element is no longer attached to the page. My guess is that sequence looks like:

element has been found
html dom was rebuild - element can be found with used locator BUT it's not the element found in step 1)
js script tries to interact with element found in step 1) BUT it's not THE SAME element (it has the same attributes etc. but it is a different element in case of Selenium

You can try to verify my hypothesis by checking what DOM elements has been added/removed with https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver


How do I create a Zen's sub-theme using Drush?

Question: I am trying to install Zen theme and create a new sub-theme from STARTERKIT. I am using the following Drush commands.

drush dl zen
drush cc all
drush zen "Name" machine_name --description="Description." --without-rtl

The first two commands work; the third one throws an error:

The drush command 'Name machine_name' could not be found

Does anyone know how to do this?
EDIT
My mistake must be that I'm running Drush from my local machine. I downloaded Drush for Windows from the Drush site. I should be running it on my server where my Drupal site is right?
Comment: "drush zen command 'Name machine_name'" doesn't install Zen theme, it creates a new subtheme. Is that what you are trying to do?
Comment: Yes, sorry, I'm trying to create a new sub-theme.
Comment: I have installed Drush for Windows. My command prompt is C:\ProgramData\Drush >. But I want Zen and my sub-theme to be created on my server in my site's folder structure, not in C:\ProgramData\Drush. I've must have missed a vital step?
Answer: Reading How to build your own sub-theme (7.x-5.x) using Drush, I get that the commands should be the following ones.
drush dl zen
drush en zen
drush cc all
drush zen "Name" machine_name --description="Description." --without-rtl

In order, the commands:

Download the Zen theme
Enable it
Clear the cache
Create the sub-theme
The reason of the second command is explained in the linked page.

Ensure drush knows about the zen command
After you have downloaded Zen and placed it in your sites/all/themes directory, you need to enable the Zen theme and clear Drupal's (and Drush's) cache so that it will notice the Zen drush command. Type drush en zen followed by drush cc all.

As for running Drush on the remote server or in the local server, see this answer from one of the Drush maintainers for How to use Drush in remote server?

It is possible to use Drush with a Drupal site that is running on a remote server that does not have Drush installed.  This is possible because the Drush commands drush rsync and drush sql-sync work by composing ssh commands; if you set up your site alias configuration carefully, then you can copy your site to a local machine to operate on it.
In order for sql-sync to work without Drush on the remote system, you must define the 'databases' and '%dump-dir' variables in your site alias.  Otherwise, Drush will try to use Drush on the remote system to look up these values.  See example.aliases.drushrc.php for more information.
Note that it is really useful to be able to at least run drush updatedb on the remote server, so that you can update your database after you rsync new code over. Of course you can do this through the GUI too, but Drush is faster.  The Resources page on drush.org lists some hosting providers that are Drush-friendly.

Keep in mind that you could create the theme on your local site, and then copy the files over the remote site, or in a git repository that you then use when deploying your server.
Comment: @user1919784 Yes Drush needs to be invoked on the Drupal environment itself; but you can do that remotely by setting up aliases. There's a good write-up [here](http://eporama.com/ramblings/drush-aliases)
Comment: Thanks. I think my error is more basic. I don't think I should be running Drush on my local machine. Not sure how I should have set Drush up. But is seems logical that it should be running on my server where my sites/all/themes folder is located?
Comment: Just FYI for those who are recently doing this and finding trouble, make sure you are installing the --HEAD version of drush because version 6.3 was not working for me for some reason.

Also if you are using MAMP, you need to create a symlink. [Here](https://www.drupal.org/node/954766) is a great guide.
Answer: This was the solution I chose (although I ticked the answer that directly answered my question):
As Clive commented Drush needs to invoked in the Drupal environment itself. Seems obvious now, but it didn't occur to me initially. Instead of carrying on developing in my server space I decided to start developing my sites on my local machine. I downloaded and installed the Acquia Dev Desktop on my Windows PC. To get the Drush command line you can use the Drush Windows Installer. Now you're ready to go.
Start the Drush command line. Choose the directory where you want to install Zen, for example:
C:\ProgramData\Drush> cd c:\users\sites\mysite\sites\all\themes

I had to create the 'themes' folder (the Acquia install didn't create it for me). These are the commands I used to install Zen, create a sub-theme and enable the sub-theme (see kiamlaluno's answer for more info):
C:\Users\Sites\mysite\sites\all\themes> drush dl zen
C:\Users\Sites\mysite\sites\all\themes> drush cc all
C:\Users\Sites\mysite\sites\all\themes> drush zen "mysubtheme" --without-rtl
C:\Users\Sites\mysite\sites\all\themes> drush en mysubtheme

There is no command for setting the theme as default as far as I know, but everything else seems to be done. Much quicker than doing it manually!


Como acessar e parar uma Thread? ASP.NET C#

Question: Desenvolvo em ASP.NET MVC5 e dentro de uma Action de POST eu inicio uma Thread:
[HttpPost]
[AutorizacaoFilterAttribute]
public ActionResult ProcessarEmails(ProcessEmailModel model)
{
    ViewBag.Processing = false;

    if (ModelState.IsValid)
    {
        if (EmailAnalisys.State == AnalyseStatus.Stopped || EmailAnalisys.State == AnalyseStatus.Finished)
        {
           Thread thread = new Thread(() => EmailAnalisys.FilterErrorEmails(model.Label, model.Email));
           thread.Start();
            ViewBag.Processing = true ;
         }
     }
     return View(model);

}
Como eu abortar a Thread uma vez que eu não tenho mais acesso a ela pois já retornei a View ?
Edit: A necessidade de retornar uma View() é porque imagina que a caixa de email tem 1000 mensagens, e eu estou processando 1 a 1, eu preciso mostrar para o usuário qual mensagem está sendo processada, tipo "1/1000" > "2/1000", essa é a justificativa de eu precisar retornar a View().
Comment: No seu exemplo se a sua Thread gerar uma exceção, você nunca vai saber. O mais correto é você esperar a thread finalizar ao invés de abortar ela.
Comment: Fica aqui uma referencia para [como fazer o cancelamente duma Task](https://pt.stackoverflow.com/questions/162450/diferen%C3%A7a-entre-backgroundworker-e-task-run)
Answer: Pensando numa resposta pra pergunta, e pegando o gancho da discussão com @perozzo, que já postou uma solução usando Thread.Abort, fiquei pensando em outras formas de abortar a thread, coisas como semáforos por exemplo, e me deparei com o interessante artigo do MVP Joydip Kanjilal: My two cents on the Thread.Abort and Thread.Interrupt methods
Nesse artigo, ele aborda alguns aspectos do uso de Thread.Abort() e Thread.Interrupt(), e lembra que na thread podemos tratar isso (detectar que foi abortada), usando ThreadAbortException.
No artigo ele lembra também que nenhum dos dois métodos é thread-safe (se não conhece o conceito, pode ler mais aqui: Thread safety), ou seja, temos que tratar a concorrência a recursos compartilhados.
A parte que realmente chamou a atenção foi que ele, "em sua opinião", não recomenda abortar a thread usando Thread.Abort() por exemplo (em tradução livre):

Minha resposta sincera é que você nunca deve usar nenhum desses
  métodos para encerrar uma thread. É aconselhável não usar os métodos Thread.Abort
  ou Thread.Interrupt para terminar uma thread - você deve ao invés disso,
  aproveitar os objetos de sincronização (como, WaitHandles ou
  Semáforos) e encerrar de forma "graciosa" as threads que você
  está usando.

Uma outra ideia que ele menciona é usar uma variável boolean volatile compartilhada com a thread, que é verificada para continuar a execução da thread e pode ser alterada por outra thread, fazendo assim com que seja encerrada de forma "graciosa" como ele menciona.
Um exemplo que código do C# Programming Guide:
// variável de controle
internal volatile bool _shouldStop;

// método para "parar a thread", que vai setar a variável
public void RequestStop()
{
   _shouldStop = true;
}

// método da thread
public void DoWork()
{
   while (!_shouldStop)
   {
       Console.WriteLine("worker thread: working...");
   }
   Console.WriteLine("worker thread: terminating gracefully.");
}

Uma outra forma de fazer algo parecido é usando um objeto CancellationTokenSource  . Esse pedaço de código (baseado No MSDN) mostra um exemplo:
var cts = new CancellationTokenSource();

void ExecutarThread()
{
    // inicia o token
    cts = new CancellationTokenSource();
    // Passa o token para a thread
    Task.Run(() => DoWork(cts.Token), cts.Token);
}

void CancelarThread()
{
    cts.Cancel();
    cts.Dispose();
}

void DoWork(CancellationToken token)
{
  while (alguma_condicao_de_loop)
  {
     // verifica se foi cancelado
     if (token.IsCancellationRequested) {
        Console.WriteLine("I was canceled while running.");
        // sai e trata
        break;
        // ou dispara uma exception tratada pelo token
        token.ThrowIfCancellationRequested();
     }
  }
}

Os códigos são exemplos adaptados para demonstrar a funcionalidade, provavelmente necessitam de algum ajuste pra funcionar em cada cenário, mas são outras formas de tentar abortar uma thread.
Answer: O que você esta tentando fazer é um bad design. Perceba que, o seu request é retornado sem a finalização da thread, mas e se a thread gerar uma exceção e não finalizar corretamente sua operação? Como você vai saber sobre isso se não tem um sistema de log, e pior que isso, provavelmente já apresentou uma mensagem de sucesso ao usuário.
Abortar uma thread pode causar muitos problemas, se você abortar a thread no meio da sua execução você pode ter inconsistência de dados. E já que você já retornou a thread principal, você não tem como saber se essa thread já finalizou seu trabalho.
Sobre todas as respostas sobre Thread.Abort(), vale ressaltar que isso não garante a finalização de uma thread. Quando você chama o Thread.Abort(), você faz com que a Thread receba um ThreadAbortException, mas a mesma pode chamar o Thread.ResetAbort() e cancelar o pedido.
O mais correto é você esperar o retorno da Thread:
Thread thread = new Thread(() => EmailAnalisys.FilterErrorEmails(model.Label, model.Email));
thread.Start();
//Se tiver algo para fazer a mais, pode ser feito aqui.
thread.Join();

Assim a sua thread principal vai esperar a thread ser finalizada, e caso aconteça algo de errado com a thread eu posso tratar de maneira eficaz (Não exemplifico no código como fazer isso).
Claro que, fazendo isso o meu código perdeu os benefícios do uso da thread. Por isso comentei do bad design. Para saber uma maneira boa de trabalhar com thread no seu caso teria que saber o que FilterErrorEmails implementa.
Comment: Eu discordo em partes com o que você disse, pois se eu esperar a `Thread` executar que vantagem eu tenho utilizando essa nova Thread? sendo que ela precisa ser assíncrona como já está sendo na action?
Comment: Se eu precisar esperar a `Thread` eu apenas chamo o método, é mais simples e limpo e da na mesma, mas não eu preciso chamar a `Thread` e retornar a `View`
Comment: Você não leu meu comentário por completo. Como eu mesmo comentei não tem vantagem em fazer da maneira correta, por isso o seu código esta com bad design.
Comment: Se você não quer travar seu front-end esperando um processo muito grande, o mais certo é fazer um Worker e deixar ele esperando enquanto o processo não finaliza. Simplesmente ignorar a thread e retornar o valor abre sua aplicação a falhas.
Comment: imagina que você recebeu um POST , você processa os valores e precisa retornar a `View()`(pois o usuário precisa de uma interface para saber o que está acontecendo), imagina que o POST é um trigger para executar algo que **NÃO** pode ficar rodando 24 horas em background. Como você faria isso com um "good design" ?  porque ao meu ver(posso estar enganado) não tem um "bad design" no meu código. É apenas programação assíncrona.
Comment: você mesmo disse que precisa de uma interface do que esta acontecendo. Como vai retornar um resultado de algo que ainda nem foi finalizado?
Comment: Puts, desculpa eu não expliquei direito na pergunta, vou editar...
Comment: Pronto Gabriel, por isso eu preciso retornar a View()
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/74458/discussion-between-gabriel-coletta-and-leonardo-bonetti).
Answer: Você pode usar Thread.Abort. Segundo seu código, thread.Abort();.
Porém segundo um post do Eric Lippert, não é certo que isso irá realmente parar a Thread, sem falar que é arriscado utilizar.
Segue:

Deixe me adicionar que não há garantias que chamar Thread.Abort irá realmente abortar a thread em questão. É possível (porém nem um pouco fácil) de dificultar uma thread de ser abortada. Se por exemplo, você estiver abortando uma thread por que acredita que ela está rodando um código hostil e então o código hostil pode estar resistindo a sua própria destruição.
  Se você possui uma operação longa envolvendo código que você não é responsável que precise ser parada corretamente, a correta forma de fazer isso é colocar o respectivo código no seu próprio processo, não na sua própria thread. (E de preferência em um processo altamente seguro-restrito). Então você pode corretamente matar o processo.
  Resumindo, Thread.Abort é a melhor indicativa de design ruim, possivelmente não confiável, e extremamente perigoso. Deve ser evitado a qualquer custo; o único momento que você deveria considerar em abortar uma thread é em caso de algum código de "desligamento de emergência" onde você está tentando desligar um appdomain da forma mais limpa possível.
Comment: é possível fazer o `Thread.Abort` a partir de outra thread, como no exemplo onde a controller já devolveu o resultado?
Comment: perozzo ok eu posso utilizar o Abort, mas como eu vou ter acesso aquela Thread para dar o abort?
Comment: @RicardoPontual é possível sim, mas não é muito fácil de fazer não.
Comment: @LeonardoBonetti porque você está querendo abortar a thread?
Comment: @perozzo porque a thread que eu dou start processa uma caixa de emails com + 1000 emails, e surgiu a necessidade de dar um stop nela, para por exemplo eu recomeçar. É mais para ter um controle dessa thread, porque se a caixa de email tem 20mil emails, eu teria que esperar todo esse tempo caso, e se eu precisar parar o processo?
Comment: E se você colocasse esse processo de emails dentro de uma Async Task com um timeout? Esta seria a forma correta de fazer o que está querendo.
Comment: A minha dúvida é a mesma do @LeonardoBonetti, se dá pra fazer isso no caso da pergunta dele, porque, até onde conheço, se você encerrar a execução de quem criou a `thread` (no caso, a Controller que já retornou), você "perde" a `thread`, ela fica executando mas você não consegue ter acesso a ela, para fazer o *Abort* por exemplo
Comment: Se você abortar a thread sem ela finalizar, vai dar problema. O mais correto é você esperar o resultado dela antes de retornar.
Comment: @leonardo-bonetti você teria acesso a thread se salvar numa variavel estática no controller (não recomendado!), mas acredito que o melhor é implementar uma das soluções proposta pela Ricardo Pontual de finalizar de forma mais "graciosa" que seria fazer "checagens" dentro do seu metodo de envio de email, voce pode utilizar session ou o banco para fazer este controle de semafaro


select routes based on roles

Question: So I'm trying to create role-based routes, however I can't figure it out how to display specific pages that relies on which role user has.
Example:
<Route exact path="/users">
          {(localStorage.getItem("role") === "ROLE_ADMIN" && (
            <Appbar/>) && (
            <Users/>))}
        </Route>

So let's say when user with ROLE_ADMIN directs to /users path, it should display  and  components. But I want to direct him to the other component if he doesn't have that role. Can anyone help me? Thanks!
Answer: It's common to create a custom route component to handle checking the role. Pass the role as a prop to the custom route and check against what is stored in localStorage and conditionally return a Route or Redirect component.
Example:
const RoleRoute = ({ role, ...props }) => {
  return JSON.parse(localStorage.getItem("role")) === role
    ? <Route {...props} />
    : <Redirect to="/" />;
};

Usage:
<RoleRoute exact path="/users" role="ROLE_ADMIN">
  <Appbar/>
  <Users/>
</Route>

This is assuming you are using react-router-dom@5 since that appears to be the route syntax/props of your code example. If you are using react-router-dom@6 the logic changes a bit.
const RoleWrapper = ({ role }) => {
  return JSON.parse(localStorage.getItem("role")) === role
    ? <Outlet />
    : <Navigate to="/" replace />;
};

Usage:
<Route element={<RoleWrapper role="ROLE_ADMIN" />}>
  <Route
    path="/users"
    element={(
      <>
        <Appbar/>
        <Users/>
      </>
    )}
  />
</Route>

Answer: You can simply use ternary condition as follow:
    {
     localStorage.getItem("role") === "ROLE_ADMIN" ? <Appbar /> && <Users /> :
      <Redirect to="/" />;
     }

Comment: FYI ` && ` will render ***only*** ``.
Comment: No problem, you can put these two components in another single component and then use that new component here.

select routes based on roles


Vector notation for an integral with basis vectors

Question: Suppose we have a function $g: \mathbb{R}^m \to \mathbb{R}^m$ which is defined as follows:
$$
[g(x)]_i= \exp \left( \int_0^{x_i} (e_i)^{t} f(t) dt_i \right) \qquad (i=1,\dots,m)
$$
where $t_j=x_j$ for $j \neq i$ and $f: \mathbb{R}^m \to \mathbb{R}^m$ is another function. Here, $[ \cdot ]_i$ denotes the $i$-th element of the vector and $\{e_i :\, i=1,\dots,m \}$ is the standard basis of $\mathbb{R}^m$.
Question: Can this be written in vector notation such that the basis vectors are avoided?
For example, can this be written in terms of a line integral?
Answer: Note that inside the exponential you're integrating the $i$th component of $f(x_1,x_2,\dots,x_{i-1},t_i,x_{i+1},\dots,x_m)$ with respect to $t_i$. If you had a sum of such integrals, rather than a vector with those components, it would be tempting to say you were doing a single line integral from $0$ to $x$. But, in fact, for this you would need to do a sequence of line segments all getting you from the origin to $x$ (e.g., $(t_1,0,0) \rightsquigarrow (x_1,t_2,0) \rightsquigarrow (x_1,x_2,t_3)$). But, as things stand, everything is totally dependent on the standard coordinate system. I've never seen anything like this before.
Comment: Thanks.  I liked the discussion that you provide. It did help me to think about the problem in a different way.
Comment: You're welcome. If you ask follow-up questions, I'll do my best.


DMZ Setup Reality Check?

Question: I'm currently doing some upgrades to servers and networking in our network and I'm looking for a reality check on our DMZ configuration.  I put it together quite a long time ago and I'm wondering if it's still relevant or if there's a better (more secure) way?
I'm thinking specifically of our webserver traffic.  We have numerous web applications that people need to access from outside our network.  Nearly all of them require some sort of access to our internal Active Directory and sometimes other internal services.
I always hated the thought of putting the webservers in the DMZ and punching holes back into the internal network for Active Directory and/or LDAP so rather than do that I setup a reverse proxy in the DMZ and proxied the web requests from the DMZ through on port 443/80 into the servers on the internal network (kinda like this example).  It's worked okay over the years, some applications work well with it, and others are a bit of a trial.
Anyway, before I go and upgrade a number of the servers in question (some are 2k8 R2, which is EOL soon) I thought I'd review it all.  I know there are other ways you can achieve this (like putting the webservers in the DMZ with an RODC for example).  I'm after some thoughts on whether I need to change my setup (and what an alternative might look like), or if it's still valid.
Thanks.
Answer: Proxy from a perimeter network to inside is still a good idea.
However, what the trusted perimeter concept lacks is that there are plenty of threats inside. Workstations get compromised, users go rogue and do bad things. Micro segmentation may help. Most users don't need to see LDAP or internal app traffic, so firewall it internally to only where needed. This requires some  maturity around security processes and tooling, different from an edge firewall and its rules.
For auth specifically, protocols exist for federated single sign on (SAML, OAuth) or auth over untrusted networks (Kerberos). Rather than bring your full directory to your perimeter, consider something like AD Federation Services that speaks the auth of web apps.
Comment: Thanks for your reply, we don't have the option of changing any apps to support different auth. schemes, but I like the idea of (more) internal firewalling.

DMZ Setup Reality Check?


Cohomology to compute number of holes?

Question: Can one use cohomology to compute the number of holes in a space $E$, where $E=R\times R$, $R$ is a Riemann surface of genus $g$, - i.e., is $\dim(H^n(E))$, and by Künneth's formula, $H^{n}(E) \cong \bigoplus_{k+l=n} H^k(R) \otimes H^l(R)$ in some way related to the number of $n$-dimensional holes in the space $E$? If yes, then how?
Comment: http://en.wikipedia.org/wiki/Hirzebruch–Riemann–Roch_theorem
Comment: I've always thought this was more a heuristic than a precise statement-since what's an $n$-dimensional hole if not, I guess, the dual of an $n$-codimensional cohomology class? Anyway, if for instance $g=1$ then $E$ is a 4-torus, whose "holes" you might interpret by considering it as a quotient of a 4-dimensional hypercube.
Comment: Can we not then use Poincare duality?
Comment: If $E$ would be a compact Riemann surface we have Riemann-Roch Theorem $$\dim H^0(E,\mathcal{O}_D)-\dim H^1(X,\mathcal{O}_D)=1-g+\deg D$$ Where $D$ is divisor on $E$. But this is only in $2$ dimensions, still it is a start.
Comment: @Kaladin True. What about other dimensions - more specifically, if $E=R\times R$, $R$ is a Riemann surface of genus $g$?
Comment: What's an $n$-dimensional hole?
Comment: @DanielRust From Wikipedia: "The dimension of the $n$-th homology of $E$ turns out to be the number of "holes" in $E$ at dimension $n$."
Comment: @DanielRust That's true! I never thought about that!
Answer: The manifold $R$ is compact and orientable and so we can say the same for $E$, in which case we may use Poincaré duality to swap $r$th cohomology for $(4-r)$th homology.
So the number of $r$-dimensional holes in $E$ is $$\mbox{rank }\left(\bigoplus_{k+l=4-r} H^{k}(R)\otimes H^{l}(R)\right)=\sum_{k+l=4-r}\mbox{rank }H^k(R)\cdot\mbox{rank }H^l(R).$$
(Hopefully I didn't mess up in the above - horrible indices)
Comment: What if $4=r$? Then, $\mbox{rank }\left(\bigoplus_{k=-l} H^{k}(R)\otimes H^{l}(R)\right)=\sum_{k=-l}\mbox{rank }H^k(R)\cdot\mbox{rank }H^l(R),$ so what is $H^{-l}(R)$?
Comment: @SanathDevalapurkar Then both $k$ and $l$ are equal to $0$ and so $\sum_{k=-l}\mbox{rank }H^k(R)\cdot\mbox{rank }H^l(R)=(\mbox{rank }H^0(R))^2$.

Cohomology to compute number of holes?


Excel: Repeat VBA script after word is finished

Question: I'm still learning how to make scripts in VBA.
For now I want to create script converting text from cell to Unicode Little Endian Hex. I have script that works now only for first character. How should i apply loop to switch to next letter, add it to print and finish script when text is over?
Function Text2LE(Character As String)
Dim x As Long
x = AscW(Character)
If x < 16 Then
  Text2LE = "000" & Hex(AscW(Character))
  Text2LE = Right(Text2LE, 2) & Left(Text2LE, 2)
ElseIf x < 256 Then
  Text2LE = "00" & Hex(AscW(Character))
  Text2LE = Right(Text2LE, 2) & Left(Text2LE, 2)
Else
  Text2LE = "0" & Hex(AscW(Character))
  Text2LE = Right(Text2LE, 2) & Left(Text2LE, 2)
End If
End Function

Comment: Looks like that function handles 1 character. You need to look at the code that's *invoking* that function.
Comment: Look in to `MID()` and increment a character by one each loop.
Comment: Possible duplicate of [Excel 2010 VBA step through a string and place one char into each cell in sequence](https://stackoverflow.com/questions/13778819/excel-2010-vba-step-through-a-string-and-place-one-char-into-each-cell-in-sequen)
Comment: OK, thx for help with MID.
I made something like this and is working.
`Function Text2LE(Character As String)
Dim x As Long
Dim a As String
Dim i As Long
c = Len(Character)
For i = 1 To c
a = Mid(Character, i, 1)
x = AscW(a)
If x < 16 Then
  LE = "000" & Hex(AscW(a))
ElseIf x < 256 Then
  LE = "00" & Hex(AscW(a))
Else
  LE = "0" & Hex(AscW(a))
End If
  Text2 = Right(LE, 2) & Left(LE, 2)
  Text2LE = Text2LE + Text2
Next i
End Function
`
Answer: you need something like to loop through the Character in the string and convert it using your function! Then Group the HEX together and display or consume! (Not to sure on the display of hex in debug window)
sub Convert()
 Dim i as long
 Dim string_to_convert as string
 Dim Hex as String

 For i = 1 to len(string_to_convert)
   Hex = Hex + Text2LE(Mid(string_to_convert, i, 1))
 Next i

 debug.Print Hex

end sub


Adjusting Height of Panel Columns using CSS

Question: I am using panel-2col-brick to make a 2 x 2 information block. The HTML structure of the page is as follows

Now i need to change height of the second occurrence of panel-col-first and panel col-second. I have tried
.panel-2col-bricks .center-wrapper .panel-col-first:first-of-type,
.panel-2col-bricks .center-wrapper .panel-col-last:first-of-type{
       height:80px;
       overflow:hidden;
}

However this changes  the height of both top-first and bottom-first columns. Is there any way i can adjust height of both rows separately ?
Answer: to achieve this you need make use of CSS pseudo selectors and apply them in the correct element, a good approach can be this:
.panel-2col-bricks > .panel-panel:nth-child(2) .center-wrapper .panel-col-first,
.panel-2col-bricks > .panel-panel:nth-child(2) .center-wrapper .panel-col-last

You can see this in action in the link below:
https://codepen.io/anon/pen/xBZGGb
Comment: If this answer is correct for your problem please mark this as accepted answer. Thanks
Comment: Thanks Jjsg08. I tried it, but unfortunately it did not work. This CSS portion has stopped applying altogether with the mentioned changes.
Comment: Also panel-panel and center-wrapper are at the same level. They do not share parent child relationship. so i tried

.panel-display .center-wrapper:nth-child(2) .panel-panel{
 height:80px;
 overflow:hidden;
}

However this only changes the first row. Whereas it is supposed to apply to second row of columns
Answer: With the help of Jjsg08's idea of CSS pseudo selectors i was able to figure it out. The idea is to jump in multiples of 2. So .center-wrapper:nth-child(2) will apply to first row whereas .center-wrapper:nth-child(4) will apply to second. Strange as it may seem, as i have only two center-wrapper elements in the code, it works.


C# TCP Client sends a message, but Server is not receiving the message

Question: This is the error :
**

Exception thrown: 'System.InvalidOperationException' in
  System.Windows.Forms.dll Additional information: Cross-thread
  operation not valid: Control 'displayText' accessed from a thread
  other than the thread it was created on.

**
I was created multi threaded client and server application using on C#. I was researched about this error but I could not find any relevant answer. I know this is comes when two or more threads started on the program...But my server side has one thread...I don't know why this is comes..........
Here is my Server side:
<code>        private void Handler()
        {
            try {

                byte[] b = new byte[100];
                int k = s.Read(b, 0, b.Length);

                //int k = s.Receive(b);

                string szReceived = Encoding.ASCII.GetString(b,0,k);
                //If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks,

                while (ServerRunning)
                {
                    string ConcatString = "";
                    for (int i = 0; i < k; i++)
                    {

                        char n = Convert.ToChar(b[i]);
                        string chars = Convert.ToString(n);
                        ConcatString = ConcatString + chars;

                    }

                    if (b[0] == '$')
                    {
                        displayText.AppendText("\nPrivate Message");
                        //MessageBox.Show("\nPrivate Message" + Environment.NewLine);
                    }
                    else
                    {
                        displayText.AppendText("\n" + ConcatString);
                        //MessageBox.Show(ConcatString + Environment.NewLine);
                    }

                    //Encoding is the process of transforming a set of Unicode characters into a sequence of bytes and using new instance
                    ASCIIEncoding asen = new ASCIIEncoding();

                    //s.Send(asen.GetBytes("The string was recieved by the server." + Environment.NewLine));

                    displayText.AppendText("\n" + ConcatString);
                    /* clean up */
                    //*
                   // k = s.Receive(b);
                    s.Close();
                    client.Close();
                    //MessageBox.Show("Recieved..." + Environment.NewLine);

                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error ...." + ex);
            }
        }
</code>
I am new to Socket Programming, but I was researched each and every code segment and experimented the code in several times.. Still can't figure out what exactly I missed in this program...
So please help me to solve this...I will be appreciated very much...
Thanks..
Comment: the error you're getting is because you tried to update the UI from another thread which you cannot do, Im not convinced it didnt receive the message, the title and body of this post dont match
Comment: Your server is receiving the message, but you are trying to access the `displayText` control from another thread - you cannot do this.
Comment: Look at the question that @rene mentions and how about trying to understand the actual error you've got - notice how it mentions nothing about sockets...
Comment: Learn to debug first - then step through the code.
Comment: again, the error you are describing has **nothing to do with the socket code**, and everything to do with how you are touching the UI; forget about sockets for now, that doesn't seem to be the problem
Comment: Yeh, Sockets, it is not the problem, the case is only appears when I send a message to the server
Answer: <code>Invoke((MethodInvoker) delegate { displayText.AppendText("\n" + ConcatString); });
</code>
should fix it; that dispatches the "append to the UI" code to the UI thread and waits for it to complete.
Comment: @PiyasenaSenani again, this has **nothing to do with sockets**, and everything to do with the fact that you're touching the UI from a non-UI thread
Comment: @PiyasenaSenani `Invoke` is the `Form.Invoke` method, [here](https://msdn.microsoft.com/en-us/library/system.windows.forms.form.invoke(v=vs.110).aspx); `MethodInvoker` is just a well-known delegate type that is special-cased by `Invoke` for performance (rather than using `Delegate.DynamicInvoke`). Basically, it just creates a runnable code fragment and says "hey, UI: run this for me while I wait"
Comment: @PiyasenaSenani of course it is threading - that's exactly what the exception told you; see your code here: `Thread tcpHandlerThread = new Thread(Handler); tcpHandlerThread.Start();` - that runs the `Handler` method ***on a different thread***. That thread is not allowed to directly touch the UI.


Print each servername line by line from specified column in CSV file using Powershell

Question: I am creating a powershell script which compares the memory usage percent to a predefined number.
Based on the outcome of this, a line will be printed detailing whether the memory usage is below or above the predefined number.
I am having problems trying to get each servername printed row by row from a specific column into a DAT file.
My Powershell script:
$day = Get-Date -format dd
$Dir = "C:\test\output"
$file = "$Dir\result_esxhost_memory_check2.dat"
$location = "C:\test\output"
$FileExist =  Test-Path -Path $location
$date = Get-Date -format "dd.MM.yy HH:mm"

#--------------------------------------------------------------------------------
#Declaring variables which stores a value from a selected column in the CSV file
#
#
#--------------------------------------------------------------------------------
$memoryusage = Import-Csv -Path C:\test\log\checks2.csv | select -ExpandProperty MemoryUsage
$name = Import-Csv -Path "C:\test\log\checks2.csv" | select -ExpandProperty Name -First 1

#--------------------------------------------------------------------------------

Clear-Content "$file"

    foreach ($row in $memoryusage) {

    If ( "$row" -lt [int32]"45") {
        $Line = "$name" + "|" + $date + "|MemoryUsage|NONE|OK|Memory usage of ESX Host $name is below the threshold" + " " + "($row)" }
    else {
        $Line = "$name" + "|" + $date + "|MemoryUsage|NONE|WARNING|Memory usage of ESX Host $name is above the threshold" + " " + "($row)"}

         Add-Content "$file" `n$Line
                $in = [System.IO.File]::OpenText($file)
$text = ($in.readtoend()).trim("`n")
$in.close()

$stream = [System.IO.StreamWriter]$file
$stream.write($text)
$stream.close()

    }

When the script is run, the results in the DAT file shows as follows:
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (33.14%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (25.23%)
Server1|21.03.23 12:46|MemoryUsage|NONE|WARNING|Memory usage of ESX Host Server1 is above the threshold (54.23%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (37.57%)
Server1|21.03.23 12:46|MemoryUsage|NONE|WARNING|Memory usage of ESX Host Server1 is above the threshold (46.76%)
Server1|21.03.23 12:46|MemoryUsage|NONE|WARNING|Memory usage of ESX Host Server1 is above the threshold (48.94%)
Server1|21.03.23 12:46|MemoryUsage|NONE|WARNING|Memory usage of ESX Host Server1 is above the threshold (61.30%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (43.27%)
Server1|21.03.23 12:46|MemoryUsage|NONE|WARNING|Memory usage of ESX Host Server1 is above the threshold (52.16%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (1.74%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (1.78%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (26.95%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (39.59%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (1.89%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (39.40%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (33.16%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (1.90%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (23.37%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (23.73%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (25.26%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (12.39%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (44.62%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (23.60%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (12.82%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (12.84%)
Server1|21.03.23 12:46|MemoryUsage|NONE|WARNING|Memory usage of ESX Host Server1 is above the threshold (75.82%)
Server1|21.03.23 12:46|MemoryUsage|NONE|WARNING|Memory usage of ESX Host Server1 is above the threshold (73.86%)
Server1|21.03.23 12:46|MemoryUsage|NONE|WARNING|Memory usage of ESX Host Server1 is above the threshold (57.83%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (1.77%)
Server1|21.03.23 12:46|MemoryUsage|NONE|WARNING|Memory usage of ESX Host Server1 is above the threshold (6.30%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (11.74%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (21.01%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (18.65%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (28.65%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (22.22%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (1.88%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (23.21%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (12.36%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (23.45%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (23.83%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (23.63%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (14.96%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (16.05%)
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (15.25%)

PLEASE NOTE: I only added the -First 1 to end of the $name variable to keep the data tidy, as it will simply add EVERY server name from each row of the "Name" column in the CSV file on EACH line in the DAT file.
The CSV file looks like this:
"Name","ConnectionState","PowerState","CpuUsage","MemoryUsage","Version"
"Server1","Connected","PoweredOn","2.64%","33.14%","7.0.3"
"Server2","Connected","PoweredOn","1.85%","25.23%","7.0.3"
"Server3","Connected","PoweredOn","10.99%","54.23%","7.0.3"
"Server2esx401","Connected","PoweredOn","8.95%","37.57%","7.0.3"
"Server2esx402","Connected","PoweredOn","3.96%","46.76%","7.0.3"
"Server1esx403","Connected","PoweredOn","18.66%","48.94%","7.0.3"
"Server1esx402","Connected","PoweredOn","27.51%","61.30%","7.0.3"
"Server1esx401","Connected","PoweredOn","21.83%","43.27%","7.0.3"
"Server1esx502","Connected","PoweredOn","6.74%","52.16%","7.0.3"
"Server1esx503","Connected","PoweredOn","0.15%","1.74%","7.0.3"
"Server1esx505","Connected","PoweredOn","0.31%","1.78%","7.0.3"
"Server1esx501","Connected","PoweredOn","2.01%","26.95%","7.0.3"
"Server1esx504","Connected","PoweredOn","4.28%","39.59%","7.0.3"
"Server1esx802","Connected","PoweredOn","0.21%","1.89%","7.0.3"
"Server1esx803","Connected","PoweredOn","2.67%","39.40%","7.0.3"
"Server1esx801","Connected","PoweredOn","1.35%","33.16%","7.0.3"
"Server1esx804","Connected","PoweredOn","0.17%","1.90%","7.0.3"
"Server1esx406","Connected","PoweredOn","1.67%","23.37%","7.0.3"
"Server1esx405","Connected","PoweredOn","1.80%","23.73%","7.0.3"
"Server1esx404","Connected","PoweredOn","1.17%","25.26%","7.0.3"
"Server1esx302","Connected","PoweredOn","0.74%","12.39%","7.0.3"
"Server1esx305","Connected","PoweredOn","1.14%","44.62%","7.0.3"
"Server1esx301","Connected","PoweredOn","1.11%","23.60%","7.0.3"
"Server1esx303","Connected","PoweredOn","0.53%","12.82%","7.0.3"
"Server1esx304","Connected","PoweredOn","0.46%","12.84%","7.0.3"
"Server1esx902","Connected","PoweredOn","12.35%","75.82%","7.0.3"
"Server1esx901","Connected","PoweredOn","28.83%","73.86%","7.0.3"
"Server2esx501","Connected","PoweredOn","5.19%","57.83%","7.0.3"
"Server2esx503","Connected","PoweredOn","0.17%","1.77%","7.0.3"
"Server2esx502","Connected","PoweredOn","1.65%","6.30%","7.0.3"
"Server2esx505","Connected","PoweredOn","2.31%","11.74%","7.0.3"
"Server2esx504","Connected","PoweredOn","2.11%","21.01%","7.0.3"
"Server2esx804","Connected","PoweredOn","1.40%","18.65%","7.0.3"
"Server2esx802","Connected","PoweredOn","2.30%","28.65%","7.0.3"
"Server2esx801","Connected","PoweredOn","1.46%","22.22%","7.0.3"
"Server2esx803","Connected","PoweredOn","0.39%","1.88%","7.0.3"
"Server2esx301","Connected","PoweredOn","1.68%","23.21%","7.0.3"
"Server2esx304","Connected","PoweredOn","0.32%","12.36%","7.0.3"
"Server2esx302","Connected","PoweredOn","1.55%","23.45%","7.0.3"
"Server2esx303","Connected","PoweredOn","0.37%","23.83%","7.0.3"
"Server2esx305","Connected","PoweredOn","0.94%","23.63%","7.0.3"
"Server2esx406","Connected","PoweredOn","1.10%","14.96%","7.0.3"
"Server2esx405","Connected","PoweredOn","1.02%","16.05%","7.0.3"
"Server2esx404","Connected","PoweredOn","0.97%","15.25%","7.0.3"

So to conclude, I would like the DAT file to show each servername from the "Name" column of the CSV file line by line.
An example of the output I am looking for:
Server1|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server1 is below the threshold (33.14%)
Server2|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server2 is below the threshold (25.23%)
Server3|21.03.23 12:46|MemoryUsage|NONE|WARNING|Memory usage of ESX Host Server3 is above the threshold (54.23%)
Server2esx401|21.03.23 12:46|MemoryUsage|NONE|OK|Memory usage of ESX Host Server2esx401 is below the threshold (37.57%)
Server2esx403|21.03.23 12:46|MemoryUsage|NONE|WARNING|Memory usage of ESX Host Server2esx403 is above the threshold (46.76%)
Server1esx403|21.03.23 12:46|MemoryUsage|NONE|WARNING|Memory usage of ESX Host Server1esx403 is above the threshold (48.94%)
Server1esx402|21.03.23 12:46|MemoryUsage|NONE|WARNING|Memory usage of ESX Host Server1esx402 is above the threshold (61.30%)

Hopefully, that explains what I am looking for.
Thank you, and much appreciated for any help!
Mike
Comment: After Import-CSV you want to sort object by server name.  See : https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/sort-object?force_isolation=true&view=powershell-7.3
Answer: The reason that you are getting all of the server names on each line is that your $name variable is a collection. It is the entire contents of the "name" column from your CSV. So when you put that variable into a string, it puts the entire set of server names in.
First, you can simplify how you import the CSV. Given what you are trying to do, you do not need two imports, and you do not need to use the -ExpandProperty flag.
Simply using $csvData = Import-Csv -Path "YourPath" is enough for you to get the entire CSV into an object, where the CSV column names are now object property names. If you just want the name and memoryUsage from the CSV then you can do this:
$csvData = Import-CSV -Path "YourPath" | Select-Object -Property Name, MemoryUsage

By not using -ExpandProperty the resulting $csvData object will contain named properties, making them easier to reference in a loop.
Finally we can build the desired string:
ForEach($row in $csvData){
   #skipping the conditional logic for clarity
   $line = $row.name + '|' + $date + '|' + $row.MemoryUsage + etc...
}

As a side note, I prefer to use a more explicit form of string concatenation. This certainly isn't a standard, but I like the way it looks:
$line = [string]::concat($row.Name, '|', $date, '|MemoryUsage|NONE|OK|Memory usage of ESX Host ', $row.Name, ' is below the threshold ', $row.MemoryUsage)


php5-fpm + nginx + drupal7 : keeps sending me index.php for download

Question: Pulling my hairs out here can't figure out why :
My virtual host in /etc/nginx/sites-available/
server {
        listen   80 default;

        location /
        {
                root   /var/www;
                index  index.php;
        }

        location ~* \.php$
        {
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME /var/www$fastcgi_script_name;
                fastcgi_param PATH_INFO $fastcgi_script_name;
                include fastcgi_params;
        }
    }

nginx.conf
user www;
worker_processes 4;
pid /var/run/nginx.pid;

events {
    worker_connections 768;
    multi_accept on;
}

http {

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    server_tokens off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    gzip on;
    gzip_disable "msie6";

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

installed packages

php5-cgi
php5-fpm
php5-mysql
nginx

on fresh clean install ubuntu 11.04.
curl'ing the ip gives me the php file 'not interpreted'
Answer: Suggest you maximize verbosity of all logs, and paste all log entries associated with your 'non-interpreted' request.
Also, I was setting up a server just yesterday, diff components but same non-interpret result - turned out I just hadn't restarted all appropriate services to pick up the php engine for parsing.
Comment: To elaborate, OP has `default_type application/octet-stream;` So if the backend doesn't provide a mime type such as when errors happen then it will default to application/octet-stream, which is of course a download.
Comment: Right ... i'm really 'dumb' sometimes ... didn't notice the big fat '500' error from PHP. Thanks !


Entity Background 'parallax image' positioning 'top' value issue when DOM is manipulated by other modules

Question: I am having an issue where the calculated value for the 'top' property that applied to the parallax-slider image is excessively large and pushing the image outside of the viewport.

In my case as you can see the 'top' property is 34946px which is 5X the height of my page content (6502px). After some testing I (believe) I have narrowed it down to a result of other modules manipulating the DOM and giving a miscalculation.
I am using the Responsive Menu module as well as the Adminimal Theme and Menu modules which both manipulate the DOM and create various wrapping and spacing elements. Disabling these modules give me slightly different results (however still and issue) This seems like it must be a jQuery firing order issue and these other DOM changes are interfering with the parallax.js calculations?
To confirm I have tested the following:

I have tested with versions 1.3.1 and the most recent 1.4.2 of the
parallax.js library with the same result
it is not a background colour issue :-p
Disabling the Responsive Menu module and viewing as an anonymous user  the parallax image is still being miscalculated but the number is about 15K pixels less than my initial test.

Can anyone else confirm having issues with these or similar DOM altering modules?
Also How can I alter the module firing weight?
Answer: For anyone coming across this issue, the real problem was not having a value in the 'speed' field.