Boost Cache, External CDN?

Question: I have been thrown into a Drupal 6 environment, helping a client whose site has been running terribly for some time now. Among other issues, they had a ton of traffic and were serving it all locally, so we aim to implement a CDN.
Our CDN of choice is Incapsula, who operate much like Cloudflare if you're familiar with them. At their most basic, they can cache static content. Should be simple.
What I'm finding is that when Incapsula's caching is enabled, the cache never updates. If you go through the public address to the site, you will see old content. It's not just old images and CSS, entire pages will be missing if they are added after the cache is enabled. If you bypass the proxy, you see the correct content. Manually clearing the cache from within the Incapsula control panel does not resolve the problem, I can only do that by actually disabling the cache. Of course, while it is enabled, the site flies!
Complicating this, they have Boost installed and enabled. I am new to Drupal, newer to Boost, and I am attempting to understand how the caching works but have not made much progress. Are there specific settings within Boost that might affect this? It feels like a header is misconfigured. Any thoughts and advice are appreciated!
Answer: If the CDN caches whole pages you can most likely disable boost.
https://drupal.org/project/advagg - Needed for D6 CSS/JS
https://drupal.org/project/imageinfo_cache - Should help with imagecache generation
Comment: Excellent, that's a big help. I installed those modules and disabled the relevant sections of Boost. Is removing Boost completely just a matter of removing its directory from modules and removing its section from .htaccess?
Comment: Be sure to uninstall it from drupal and then yes, remove the cache dir & module and its sections from .htaccess
Answer: I work at Incapsula.
This does sound like a cache header issue. (perhaps Drupal Boost assigns prolonged "maxage" values?)
One way or another, you can override these settings using our Advance Control options.
http://www.incapsula.com/blog/popping-the-hood-on-website-acceleration.html
One of the selectors there allows Incapsula to automatically override existing maxage and no-cache directives, using its own cache header logic.
You can also manually set your own caching settings: for all resources and for specific resource groups (e.g. all resources set to refresh each 5 minutes and all *.jpg files set to refresh once a day)
Moreover, you can also configure refresh rates for specific resources (e.g. all resources are refreshed every 5 min, all images are refreshed once a day and a homepage banner updated once a month)
I'll be happy to provide more case-specific assistance but, to do that, I`ll need to know the domain name.

Boost Cache, External CDN?


How do I protect random people pointing their domain to my server?

Question: I just found out that flashsale.info is pointing to my server. How do I stop this from happening? Is there anything I can do?
Answer: There is nothing you can do to forcibly stop other people from pointing their domains at your server. It may not be malicious; it may be that they have simply made a typo in their zone file, or that they have forgotten to delete an old entry. So the first thing to do is to simply contact them and politely inform them of the error.
If they don't respond appropriately, the simplest solution is to create a virtual host or a redirect rule that will simply respond with an error message to anyone requesting the wrong hostname.
Since you haven't specified what web server software you're using, I can't help with any configuration options. If it's apache, you should start by reading this explanation of how apache handles hostnames and the canonical answer about how rewrites work in apache.
Comment: Thanks for pointing me in the right direction. I'm using nginx and have configured it successfully. Thank you


Datepicker ngx-bootstrap

Question: I am trying to apply locale on old datepicker
https://valor-software.com/ngx-bootstrap/#/datepicker
I have tried evrything and i dont know where to look further, i can use the new one, but i have big solution that i have to stay on old datepicker
Here is what i have
my.module.ts
import { CommonModule } from '@angular/common';
import { DatepickerModule } from 'ngx-bootstrap/datepicker';

@NgModule({
    imports: [
        DatepickerModule.forRoot()
    ],
    declarations: [

    ],
    providers: [

    ],
    schemas: [
        CUSTOM_ELEMENTS_SCHEMA
    ]
})
export class MyModule {
}

my.component.ts
import { defineLocale } from 'ngx-bootstrap/bs-moment';
import { de } from 'ngx-bootstrap/locale';
defineLocale('de', de);

@Component({
    templateUrl: './my.component.html',
    styleUrls: ['./my.component.scss']
})

export class MyComponent implements OnInit {}

my.component.html
  <datepicker formControlName="effectiveDate" [showWeeks]="false" [locale]="de">

Can't bind to 'locale' since it isn't a known property of 'datepicker'. :(
Comment: For the legacy version of this datepicker, I do not see `locale` listed as an available input.
Comment: Yes, but how to add locale for legacy version, that is my question?
Comment: You can't just simply add inputs to a third-party library without forking it and modifying the source.  Why not use the updated version?  It contains a `locale`.
Comment: I can not update
Comment: It looks like both the legacy version and new version are in the exact same library, just change which module you import.  One is `DatepickerModule`, the new one is `BsDatepickerModule`.
Comment: If i import new i got this error
Error: Template parse errors:
'datepicker' is not a known element:
1. If 'datepicker' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("

                                                    [ERROR ->]
Comment: @MiomirDancevic that last suggests you don't DatepickerModule imported into your module. Can you check that?
Comment: It is not working legacy datepicker does not support locale
Answer: The legacy version of this datepicker does not contain a locale input.  Documentation states This is a legacy version of datepicker without support of daterangepicker, locales, themes, etc.  The newer version does have a locale, but it cannot be modified as an input property.  Instead you use the BsLocaleService to change the locale.  It should look something like this:
my.module.ts
import { CommonModule } from '@angular/common';
import { BsDatepickerModule, BsLocaleService  } from 'ngx-bootstrap/datepicker';
import { de } from 'ngx-bootstrap/locale';
defineLocale('de', de);

@NgModule({
    imports: [
        BsDatepickerModule.forRoot()
    ],
    declarations: [

    ],
    providers: [
        BsLocaleService
    ],
    schemas: [
        CUSTOM_ELEMENTS_SCHEMA
    ]
})
export class MyModule {
}

my.component.ts
import { BsDatepickerConfig, BsLocaleService } from 'ngx-bootstrap/datepicker';
import { listLocales } from 'ngx-bootstrap/bs-moment';

@Component({
    templateUrl: './my.component.html',
    styleUrls: ['./my.component.scss']
})

export class MyComponent implements OnInit {
   locale = 'de';

   constructor(private _localeService: BsLocaleService) {}

   ngOnInit(){
      this._localeService.use(this.locale);
   }

}

my.component.html
<input placeholder="Datepicker" type="text" formControlName="effectiveDate" class="form-control" bsDatepicker #dp="bsDatepicker">

Comment: Uncaught (in promise): Error: No provider for BsLocaleService!
Comment: Sorry, left that off the `providers`.  Updated.
Comment: I have changed to BsDatePicker as you write, but now i got this error

Error: Template parse errors:
'datepicker' is not a known element:
1. If 'datepicker' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("

                                                    [ERROR ->]
Comment: My bad.  I was trying to update your code, and left off that the new version is a directive not a component, so use the `bsDatepicker` directive.
Comment: This in not answer to my question, we have updated the datepicker, i dont need that i need to update locale on old datepicker
Comment: The legacy datepicker documentation is pretty clear that it does not support locale.

Datepicker ngx-bootstrap


When a subfield of a splitting field is a splitting field

Question: Look at the following proposition:

Let $K\subset L\subset M$ be three fields. If $M$ is a splitting field
  over $K$ of a polinomial in $K[X]$ and moreover if for every $\sigma\in G=Gal(M/K)$ we have that $\sigma(L)\subseteq L$, then $L$ is a splitting field over $K$.

My attempt of proof is the following, but I have problems in the last part:
if $M=K(a_1,\ldots, a_n)$ where $a_1,a_2,\ldots, a_n$ are the roots of $f\in K[X]$, then (rilabelling the roots if it is necessary) we have that $L=K(a_1,\ldots,a_t)$ with $t<n$. Now if $g=(X-a_1)\ldots(X-a_n)$, by the property of $L$, we can argue that $g\in Fix(G)[X]$, and so $L$ is the splitting field of $g$ over  $Fix(G)[X]$ but not over $K$.
In characteristic $0$ we could conclude that $Fix(G)=K$, but what about the general case?
Answer: I think the following may work:
First, note that if $\sigma \in \operatorname{Gal}(M/K)$ and $\sigma(L) \subseteq L$, then since $L/K$ is algebraic, $\sigma|_L$ is actually an automorphism $L\to L$ (Lang's Algebra, Lemma 2.1, p. 230).
I assume based on your other questions that you are familiar with normal extensions, but just for reference (this is taken almost verbatim from Morandi's Field and Galois Theory):

Let $L/K$ be an algebraic extension. The following are equivalent:
  (1) $L/K$ is normal (i.e., $L$ is a splitting field over $K$).
  (2) If $N$ is an algebraic closure of $L$ and if $\tau: L \to N$ is a $K$-homomorphism, then $\tau(L)=L$.
  (3) If $K \subseteq F \subseteq L \subseteq N$ are fields and if $\tau: F \to N$ is a $K$-homomorphism, then $\tau(F) \subseteq L$, and there is a $\sigma\in \operatorname{Gal}(L/K)$ with $\sigma|_F = \tau$.

We shall show $L/K$ satisfies (2). Let $N$ be an algebraic closure of $M$; then since $N/M$ and $M/L$ are both algebraic, $N$ is also an algebraic closure of $L$. Let $\tau: L \to N$ be a $K$-homomorphism. Now, $M/K$ is normal, so we may apply (3): There is a $\sigma \in \operatorname{Gal}(M/K)$ such that $\sigma|_L=\tau$ . In particular, we have $\tau(L) = \sigma(L)= L$ (by the first paragraph).


What is an RKO in wrestling?

Question: I'm not much of a wrestling fan, but I often hear about a RKO.
I know KO (Knock Out) and TKO (Technical Knock Out, where it's not a KO in itself, but the fight is considered one).
What is an RKO?
Answer: An "RKO" is Randy Orton's finishing maneuver (named after his initials), a variation of the "Jumping Cutter." This is not a "technical" wrestling term like KO or TKO.

This was popularized in pop culture through Vines known as "RKO Outta Nowhere."

https://www.washingtonpost.com/news/early-lead/wp/2014/10/19/rko-out-of-nowhere-meme-is-everywhere-including-this-awesome-goal-celebration/?utm_term=.ea5255ea9cfb
https://www.youtube.com/watch?v=Qz-rsqEaa_s

What is an RKO in wrestling?


Iranian Grade Average Regex

Question: I need a regex to handle the Iranian Grade average, regex should cover all these rules

Range of number should be between 0 to 20.
Numbers could be decimal except 20.
Integer part and decimal part should include one or two numbers.
If you use '.' you should have at least one decimal number.

examples:
20      true
19.99   true
14.5    true
12      true
4       true
0.22    true
00.02   true
10      true
14.23   true
09.23   true

21      false
30      false
123     false
12.222  false
09.     false
4.      false
.2      false
099     false
1.123   false
Answer: I tested this pattern and it works:
/(?<!\S)(([0-1]?[0-9])(.)([0-9]?[0-9])|([0-1][0-9])|\d{1}|(20))(?!\S)/
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: If it's to match a string with an Iranian Grade Average, then this regex pattern will match only the true ones.
^(?:[01]?[0-9]|20)(?:[.][0-9]{1,2})?$

^ : start of a line or string
(?:[01]?[0-9]|20) : number from 00 or 0 to 19, or 20
(?:[.][0-9]{1,2})? : optional 1 to 2 decimals
$ : end of line or string

Iranian Grade Average Regex


View that display single node which has id the same as last part of url (from last / to the end)

Question: I have an urls:

website.com/portfolio-entries/23
website.com/portfolio-entries/25

I would like to make an view for them to display node which has id the same as last part of url (from last / to the end).
I have red the description for View > Url (administration panel > Content > Views > My_view):

This view will be displayed by visiting this path on your site. You may use "%" in your URL to represent values that will be used for contextual filters: For example, "node/%/feed". If needed you can even specify named route parameters like taxonomy/term/%taxonomy_term

So I set it to portfolio-entries/%entry_id (I hope I understood it right).
But how now make this view display only sinlge entry which has the id set to %entry_id?
I've tried with View > Filters (add) > ID but I can only set there hard-coded values (e.g. 23 makes this view display only entry #23). How can I place there my %entry_id?
In other words I was reproducing steps from https://www.ostraining.com/blog/drupal/views-specific-node/ (it's for Drupal 7 but it works the same way in Drupal 8) but instead of har-coding the id value I want to take it from last part of the url.
Answer: Normally the parameter is not named, it is a single % without name:
portfolio-entries/%

The example node/%/feed is also a single % in the middle part of the url. The third part of the url is a fixed feed, so that only urls with a /feed at the end will match.
To use this parameter for filtering you need to set a contextual filter in the advanced settings. If you only have one parameter, this filter will automatically get this, when selecting the field you want to filter.


Proof of an infinite series formula

Question: If $$|x| < 1$$ Prove that
$$\begin{align}\large 1 + 2x + 3x^2 + 4x^3 + \dots = \frac{1}{(1 - x)^2}\end{align}$$
Comment: Hint: $1+x+x^2+x^3+\cdots=\frac{1}{1-x}$ if $|x|\lt 1$.
Answer: Differentiate the geometric series
$$\frac{1}{1-x}=\sum_{n=0}^\infty x^n$$
This yields directly
$$\frac{1}{(1-x)^2}=\sum_{n=1}^\infty nx^{n-1}$$
Answer: HINT: Let
$S= 1+2x+3x^2+4x^3+\cdots$. Then
$$S-Sx=1+(2x-x)+(3x^2-2x^2)+\cdots=1+x+x^2+\cdots.$$
Answer: Another$^2$ approach:
Since
$\sum_{i=0}^{\infty} x^i
= \frac1{1-x}
$,
differentiating both sides
we get
$\sum_{i=1}^{\infty} ix^{i-1}
= \frac1{(1-x)^2}
$.
Answer: Another approach:
As @Andre said, you have $$S=\sum_{i=0}^\infty x^i=\frac1{1-x}.$$ You wanted to calculate $$T=\sum_{i=1}^\infty ix^{i-1}.$$
Final job: Consider the difference $$xT-S$$ and use the explicit form of $S$.

Proof of an infinite series formula


How to pass an ImageView which is selected from the internal Storage between Activities

Question: I uploaded an Image from my Internal Storage and want now to pass this
selected Image to a new Activity. I do not pass an Image from the
drawable. I pass an Image which I selected from my Internal Storage. I
tried to pass this Image via the R.id
ImageView imageView_selectedImage;

imageView_selectedImage =(ImageView)findViewById(R.id.imageView_selectedImage);

Button button_goToNextActivity = (Button) findViewById(R.id.button_goToNextActivity);

button_goToNextActivity.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
       Intent intent = new Intent(this, nextActivity.class);
       intent.putExtra("resId", R.id.selectedImage);
       startActivity(intent);
      }
}

Comment: You are a bit confused. an `ImageView` is just a UI widget. The widget is part of the layout and you cannot pass it from one `Activity` to another. You probably want to pass the actual image (a `Bitmap` or similar) from one `Activity` to another. To do this you can put the `Bitmap` in the `Intent` as an "extra", but if it is large, you probably want to store it somewhere and just pass a reference (URI, filename, etc.) instead.
Answer: imageView.invalidate();
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();

ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, baos);
        byte[] b = baos.toByteArray();
        String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

Then pass the byte array to the next activity.
Intent intent = new Intent(this, nextActivity.class);
   intent.putExtra("image", imageEncoded);
   startActivity(intent);

Get the byte from the intent second activity.
Bitmap bmp;

byte[] byteArray = getIntent().getByteArrayExtra("image");
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

Set the bitmap to the imageview of the second activty

imageview.setImageBitmap(bmp);

Comment: hallo thanks for the reply!
But this part is not working:

byte[] byteArray = getIntent().getStringExtra("image");

it shows me a error in the code
Comment: Due to the following line:
byte[] byteArray = getIntent().getStringExtra("image");

it shows the following error:
error: incompatible types: String cannot be converted to byte[]
Comment: oops sorry! My bad. I have updated the answer please check the updated answer
Comment: There are no more errors but the programm  ist not working. Even it is not switching to the next activity.
Comment: Activity 1 looks like:
imageView.invalidate();
                BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
                Bitmap bitmap = drawable.getBitmap();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, baos);
                byte[] b = baos.toByteArray();
                String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Intent intent = new Intent(this, addNewClothes.class);
intent.putExtra("image", imageEncoded);
startActivity(intent);
Comment: Activity 2 looks like:
 imageView = (ImageView)findViewById(R.id.imageView_image);

        Bitmap bmp;
        byte[] byteArray = getIntent().getByteArrayExtra("image");
        bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
        imageView.setImageBitmap(bmp);
Comment: I think the Problem is how to declare the selected Image from my Internal Storage of my mobile into a bitmap or drawable element which can be than pass to the next activity via the line: intent.putExtra("image", bitmap or drawable);
Answer: Don't pass imageview to next activity.
You can pass uri of  Image which is selected from gallery.\
Get Uri for selected image in onActivityResult method like below code:
@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
       if (requestCode == SELECT_GALLERY) {
            if (data != null) {
                imageSelectedFromGallery(data);
                pictureUri=data.getData();
                imageView_selectedImage.setImageURI(pictureUri);
            }
        }
    }

Note**:  make pictureUri instance variable instead of local variable.
Pass Image Uri to next Activity like below code:
 Intent intent=new Intent(Main2Activity.this,NextActivity.class);
 intent.putExtra("pictureUri",pictureUri);
 startActivity(intent);

Get Image Uri in Next Activity and set into imageView :
 ImageView imageview=findViewById(R.id.imageview);
 Bundle bundle=getIntent().getExtras();
 if(bundle!=null) {
      String pictureUri = bundle.getString("pictureUri");
      imageview.setImageURI( Uri.parse(pictureUri));
 }

I hope its work for you.


How can I use Mootools with Drupal 6?

Question: I am looking for a way to use Mootools with Drupal 6, without disabling jQuery, of course.
Answer: You will need to load JQuery in "noConflict mode" or MooTools in "Dollar Safe mode"; your best bet is to use "Dollar Safe mode" to avoid effecting Drupal.
See MooTools, Framework Compatibility, and Dollar $afe Mode, and The Dollar Safe Mode.

How can I use Mootools with Drupal 6?


Playing game optimally

Question: There are $n$ players in your team and for every player you know health and damage, say for $i$th player is $h_i$ and $dmg_i$. Given two types of spells:
$1$: Doubles health of one player, i.e., $h_1 := 2 h_1$
$2$: Assigns value of health of the creature to its damage, i.e., $dmg_i :=  hp_i$
For any game given $n,$number of spells of type $1$ and type $2$(say $a$ and $b$ respectively) and health($h_1,h_2,\cdots,h_n$) and damage($dmg_1,dmg_2,\cdots,dmg_n$).
To find: Maximal possible sum of damages after using all the spells.
Also, Spell can be used on a certain creature multiple times. Spells can be used in arbitrary order. It isn't necessary to use all the spells.
My strategy:
Using all spells of type $1$ on a single player is more efficient.
Say two players $i,j$ having health $h_i,h_j$ repectively.
For $i \neq j$, say optimal solution is
$h_i' = h_i*2^x$
$h_j' = h_j*2^{a-x}$
say $h_i \geq h_j$
$\implies h_i*2^{x+1} +h_j*2^{a-x-1} \geq h_i*2^x + h_j * 2^{a-x}$
Now, I just sorted the $h_i*2^a - dmg_i $ and if $(b\geq 1)$ replaced $dmg_i$ with the max difference from the sorted list[Here one spell of type $2$ is used]. And for rest of the spells of type $2$ i just sort the new list $h_i - dmg_i$ and used spells till either no spells left for $h_i - dmg_i \geq 1$
But I am doing something wrong and i didn't figure out what. Any help will be appreciated!
Thanks
Edit:
As pointed out by @RideTheWavelet, I am now using spell of type $1$ only if it can increase damage ($h_i*2^a - dmg_i > 0$ then only i use spell of type $1$)
But there is some more mistake in my method.
Answer: Consider $h_{i}=1$ for all $i,$ $a\leq 9,$ $b=$anything, and $dmg_i=1024$ for all $i$. Then the best strategy is clearly not to use any spells (unless boosting health is otherwise useful, in which case the available Type I spell should be used).
Comment: yeah i missed this case, but there is some more mistake in my method. Is there anything else going wrong?
Comment: What kind of unexpected behavior are you encountering?

Playing game optimally


(#200) Permissions error facebook

Question: Estou tentando desenvolver uma aplicação que faça uma busca de conteudo no facebook, exemplo eu tenho uma lista de palavras chaves, e com estas eu faço a busca e o facebook irá retornar o conteudo na forma de JSON de onde estiver publicado e é claro a visibilidade de cada postagem tem estar publica para ser coletado, porém quando tento executar no browser a url abaixo não funciona, segue:
https://graph.facebook.com/search?q=comida&type=post
    Erro:
  {
     "error": {
     "message": "(#200) Permissions error",
     "type": "OAuthException",
      "code": 200
    }
  }

quando tento passar o access token ocorre outro erro:
https://graph.facebook.com/v2.2/search?type=post&q=comida&access_token=[token]
     Erro
 {
  "error": {
   "message": "(#11) Post search has been deprecated",
   "type": "OAuthException",
   "code": 11
  }
 }

Alguem já passou por isso?
Agradeço desde já.
Answer: Acho o primeiro erro irrelevante, pois para usar a API é obrigatório usar o TOKEN, então irei falar sobre o segundo erro.
(#11) Post search has been deprecated
Conforme esta resposta do SO-en
A versão 2.0 do GraphAPI não permite que você busque mensagens. Veja a documentação atualizada.
Você pode continuar a buscar por postagens se você mudar a chamada da API para:
https://graph.facebook.com/v1.0/search?q=search_query&type=post&access_token={access_token}

O exemplo adiciona v1.0/ após https://graph.facebook.com/
Porém conforme este comentário
A versão v1.0 não irá mais funcionar após 30/Abril/2015.
Em outras palavras, tal ferramenta não será mais disponível.
Leia sobre o upgrade: https://developers.facebook.com/docs/apps/upgrading
Endpoints já não disponíveis em v2.0

/me/locationsfoi removido. Use /me/tagged_places.
/me/checkins foi removido, juntamente com a permissão do user_checkins.
/me/questions foi removido, juntamente com a permissão do user_questions. Inclue também /{page-id}/questions, /{group-id}/questions, /{question-id} e /{question-option-id}.
/me/subscribers e /me/subscribedto foram removidos.
/me/username não mais disponivel.
/me/notes não mais disponivel, juntamente com a permissão do user_notes.
/{page-id}/notes não mais disponivel.
/{page-id}/questions não mais disponivel.
Public Post search não mais disponivel. (/search?type=post&q=foobar)
News Feed search não mais disponivel (/me/home?q=foobar)
Start Now não mais disponivel.
Comment: obrigado era exatamento isso que eu queria saber

(#200) Permissions error facebook


Where does couchdb store admin user data on MacOSX?

Question: I'm looking to remove all traces of couchdbx from a mac, and install couchdb from source. For some reason, though, the newly installed couchdb seems to still be using (older) admin user/login data.
Where is this data stored/how do I remove it?
Answer: You'll want to check that <code>~/Library/Application Support/CouchbaseServer</code> is empty as well.


How to remove domain name from the src URL attribute in Jquery

Question: I'm fetching img src attribute into a variable, while doing so I'm getting the complete url of the image, i want to remove domain name from the url
var imgurl = "http://nitseditor.dev/img/home/bg.jpg";

I want to have only img/home/bg.jpg. How can I achieve it?
Comment: Is the domain always the same?
Answer: You can use URL constructor.

This is an experimental technology

var url = new URL(imgurl);
console.log(url.pathname);

var imgurl = "http://nitseditor.dev/img/home/bg.jpg";
var url = new URL(imgurl);
console.log(url.pathname);

Browser Support
Comment: If IE is not your friend, this seems to be the best answer so far!
Comment: @Rayon Thanks, [This](https://github.com/Polymer/URL/blob/master/url.js) can be used for older browsers.
Comment: I think this is the [polyfill](https://github.com/arv/DOM-URL-Polyfill)
Answer: url = url.replace(/^.*\/\/[^\/]+/, '')

Comment: you try run code above it have result is: /img/home/bg.jpg
Comment: this will remove all the `/` string. Not appropriate for my question.
Answer: Get substring by getting the index of third /.

var imgurl = "http://nitseditor.dev/img/home/bg.jpg";

console.log(
  imgurl.substr(imgurl.indexOf('/', 7) + 1)
);
Comment: thanks. Does it have IE support as @Tushar's answer in not supporting IE.
Comment: @NitishKumar [YES](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf#Browser_compatibility).
Comment: This is not very stable


Using sql importer, how can I import schema details like PK/FK?

Question: I did a sql import (sql08) and it didn't import PK/FK type information.
It only transfered data and created the tables.
How can I make it do this?
Answer: SCript the tables including scripting indexes, constraints, foreign keys etc.
Run the script then use the wizard to transfer the data into the new empty table using append rather thant create.
You could also using the wizard click on Edit mappings (onthe Select Source Tables and Views page) and then edit SQl and add the code for those things yourself to the table definition script.


php parameters transfer

Question: I try to send some text from my app to php, but somehow I never receive text. What 's wrong here?
NSString *name = [[NSString alloc]initWithString: @"Hello World"];
NSString *email = [[NSString alloc]initWithString: @"Ohai2u"];
NSString *urlString = [NSString stringWithFormat:@"http://www.myhosturlxyz.com/tracktxt.php?name=%@ email=%@",
                       [name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                       [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSURL *url = [[NSURL alloc] initWithString:urlString];

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

NSData *urlData;
NSURLResponse *response;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil];
[url release];

The php I made is
<?php
    $name = $_REQUEST['name'];
    $email = $_REQUEST['email'];
    $myFile = "tracktxtf.txt";
    $fh = fopen($myFile, 'a') or die("can't open file");
    fwrite($fh, "my posted var is " .$name $email "\n");
    fclose($fh);
 ?>

Answer: Just a wild guess, but might you need & between name=%@ and email=%a, making it name=%@&email=%@?
Or, can you try using $_GET['name'] and $_GET['email'] instead of REQUEST? Perhaps try writing print_r($_REQUEST, true); print_r($_GET, true); to your debug file and see what it contains.
Comment: I added the "&" , changed POST/REQUEST same result.
Comment: What is contained in the $_REQUEST and $_GET variables? It shouldn't be a POST, but a GET.
Comment: odd when I look in  logs I see ....tracktxt.php name=.......  It is just like the "?" is not in the string. The content of the name and email variables is send through ok, but the connection between php and the variable is not made....hence the variables are never processed further in the php script.

php parameters transfer


Suppose that $V$ and $W$ are subspaces of $\mathbb{R}^n$ with $V \subseteq W$. Suppose that $\dim V = \dim W$.

Question: I am working on the following proof:

Suppose that $V$ and $W$ are subspaces of $\mathbb R^n$ with $V \subseteq W$ ( that is that every vector $\vec{v} \in V$ is also in $W$). Suppose that $\dim V = \dim W$. Prove that $V = W$.

I am not convinced that this is even true. Could anyone supply some assistance?
Comment: Try assuming that it's not true.  That is that there is some $\vec w \in W$ s.t. $\vec w \not\in V$.
Comment: What is your definition of dimension? The maximal size of a linearly independent set?
Comment: @user237799 Did I answer your question?  Is there something you'd like me to elaborate on?
Answer: Sketch of proof:
$V$ is $k$-dimensional means that $V$ contains at least one set of $k$ linearly independent vectors $v_1, v_2, \dots, v_k$ and cannot contain a set of $k+1$ linearly independent vectors.
$W$ is $k$-dimensional means that $W$ contains at least one set of $k$ linearly independent vectors $w_1, w_2, \dots, w_k$ and cannot contain a set of $k+1$ linearly independent vectors.
$V \subseteq W$ means that $\forall v \in V, v\in W$.  This implies that $v_1, v_2, \dots v_k \in W$.
Now suppose that $W$ has at least one vector $w_i$ that's not in $V=\operatorname{span}(v_1, \dots, v_k)$.  Then $W$ has at least one set of $k+1$ linearly independent vectors -- that set being $\{v_1, v_2, \dots, v_k, w_i\}$.  But $W$ is $k$-dimensional.  Contradiction.
So $\forall w\in W, w\in V$.  Thus $V=W$.$\ \ \ \ \square$


Append string element from class to array of strings

Question: I have class in which have variable hall and other variables. I need to need pull out and add variable hall in new array of strings.
All variables are now stored in a variable with type BookingHall.
How do I get and add a variable hall to a new variable?
For everything I use firestore.
My class implementation:
protocol BookingDocumentSerializable {

    init?(dictionary: [String:Any])

}

struct BookingHall {

    var contactInfo: [String: Any] = [:]
    ................
    var hall: String = ""

    var dictionary: [String: Any] {

        return [

            "contact_info": contactInfo,
            ................
            "hall": hall

        ]
    }
}

extension BookingHall: BookingDocumentSerializable {

    init?(dictionary: [String: Any]) {

        let contactInfo = dictionary["contact_info"] as? [String: Any] ?? [:]
        ................
        let hall = dictionary["hall"] as? String ?? ""

        self.init(contactInfo: contactInfo,
                  ................
                  hall: hall)

    }
}

Here i get all variable in class:
var hallArray: [String] = []

private var historyBooking: [BookingHall] = []

fileprivate func observeQuery() {

    guard let query = query else { return }

    listener = query.addSnapshotListener { [unowned self] (snapshot, error) in

        if let snapshot = snapshot {

            let bookingModel = snapshot.documents.map { (document) -> BookingHall in

                if let newHistoryBooking = BookingHall(dictionary: document.data()) {

                    return newHistoryBooking

                } else {

                    fatalError("Ошибка загрузки!")

                }
            }

            self.historyBooking = bookingModel
            self.document = snapshot.documents

            for index in 0...self.historyBooking.count {

                self.hallArray.append(self.historyBooking[index].hall)

                print("hall id \(self.hallArray)")

            }

            self.tableView.reloadData()

        }
    }
}

In here I get error index out of range, but in console I can see hall id.
self.hallArray.append(self.historyBooking[index].hall)

How do I correctly add hall to a new array of strings in...
var hallArray: [String] = []

Answer: A very common mistake.
Indexes are zero-based. Imagine your array has one element. The range 0...array.count has the indexes 0 and 1 but there is no element at index 1...

You have to write either
for index in 0..<self.historyBooking.count

or
for index in 0...self.historyBooking.count - 1

The first syntax is preferable.
Comment: Thank you for the detailed answer. I hope now I will no longer get this error.
Answer: To avoid Index out of bound you can use for...in loop
for obj in 0...self.historyBooking.count {

  self.hallArray.append(obj.hall)

  print("hall id \(self.hallArray)")

}


Creating a loop condition in Rules for Commerce Line items

Question: Certain products on the site can't be shipped using a certain shipping service as they are classified as dangerous goods.
So I need to be able to loop through all the items in the cart, check to see if the product has is marked as dangerous (field_dangerous_goods on the commerce_product entity), if any of the products in the order are marked as dangerous goods then that shipping service shouldn't be shown to the user.
I've tried with various different rule components to try and create what I need with not even a glimmer of hope.
Comment: Did you try using [Conditional Rules](https://drupal.org/project/rules_conditional)?
Answer: Figured it out.
Firstly, you'll need Conditional Rules.
Create a new rule component.
For the variables, add Commerce Line Item as a Parameter and add a Integer as Provided.
Under Conditions, add Entity has field, select commerce_product. Then add another Entity has field and select your field_dangerous_goods field from line-item:commerce-product. Lastly add a data comparison to check the status of the dangerous goods field. In my case I just had a checkbox, so I used Data value is empty and checked the Negate box.
This makes the condition return TRUE if the current line item is a dangerous item.
Under Actions, choose Add action and select the Set a data value option. For this set the parameter to the variable you created when you set up the component. Set the value to 1.
{ "rules_dangerous_goods" : {
    "LABEL" : "Dangerous goods",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "line_item" : { "label" : "Line Item", "type" : "commerce_line_item" },
      "dangerous_goods" : { "label" : "Dangerous Goods", "type" : "integer", "parameter" : false }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "line-item" ], "field" : "commerce_product" } },
      { "entity_has_field" : {
          "entity" : [ "line-item:commerce-product" ],
          "field" : "field_dangerous_goods"
        }
      },
      { "NOT data_is_empty" : { "data" : [ "line-item:commerce-product:field-dangerous-goods" ] } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "dangerous-goods" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "dangerous_goods" ]
  }
}

Then for your shipping service rule, under Actions, choose Add action. Select Add a variable, I called mine Contains Dangerous Goods (contains_dangerous_goods). Set the value to 0.
Add a loop.
Then Add action to the loop. Select your component. You'll need to set the variable name, this has to be different to the Contains Dangerous Goods variable from before, I just called mine Dangerous Good (dangerous_good).
Now choose Add conditional to the loop. Then for the conditional, choose Add if. Select the *dangerous_good* which we just set in the loop in the component action. Set the value to 1.
Within the If, choose Add action. Select Set a data value. For the field, choose the contains_dangerous_goods value. This is the initial variable we set for the shipping service rule. Set the value to 1.
Now outside of the loop, Add conditional. Then Add if. Choose the *contains_dangerous_goods* field and set the value to 0.
Then within the If, add your shipping rate.
{ "commerce_shipping_service_standard_up_to_0_5kg" : {
    "LABEL" : "Rate Standard - Up to 0.5kg",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "commerce_order",
      "commerce_physical",
      "rules",
      "rules_conditional",
      "commerce_shipping"
    ],
    "USES VARIABLES" : { "commerce_order" : { "label" : "Order", "type" : "commerce_order" } },
    "IF" : [],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "integer", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "contains_dangerous_goods" : "Contains Dangerous Goods" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "component_rules_dangerous_goods" : {
                "USING" : { "line_item" : [ "list-item" ] },
                "PROVIDE" : { "dangerous_good" : { "dangerous_good" : "Dangerous Goods" } }
              }
            },
            { "CONDITIONAL" : [
                {
                  "IF" : { "data_is" : { "data" : [ "dangerous-good" ], "value" : "1" } },
                  "DO" : [
                    { "data_set" : { "data" : [ "contains-dangerous-goods" ], "value" : "1" } }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : { "data" : [ "contains-dangerous-goods" ], "value" : "0" } },
            "DO" : [
              { "commerce_shipping_service_rate_order" : {
                  "shipping_service_name" : "standard_up_to_0_5kg",
                  "commerce_order" : [ "commerce-order" ]
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

Answer: I'd recommend a different route for this. Create a view of Commerce Line items with a conditional filter of Commerce Order ID.  Add a relationship to the Commerce Product to get access to the field (make it required).  Add a "Bulk Operations: Line items" field so that we can access this under conditions within views (this requires you to have Views Bulk Options installed).  Add a filter to show products with field_dangerous_goods.
Once you have created the view then add a condition "Check number of results returned by a VBO View". Specify the view you just created and then set the minimum number to evaluate to TRUE as 1.
This is a bit easier and there's only one condition to add to your rule.  Sorry if this is a bit late to the party but this seems like it's a bit easier to deal with.
Comment: I chose this option, which worked for me.

One point to note - the view described in this solution won't work for anonymous users unless you disable SQL rewriting for the view. It returns zero results otherwise, regardless of what's in the cart.
Comment: I'm wondering why that worked for me originally. I think my anonymous users have the ability to view products of certain types which is why this works for me. Can you narrow down which permission(s) are granted for authenticated but not anonymous that are leading to this behavior?
Comment: Disabling SQL rewriting on Views that interact with Commerce entities seems to be the best way to solve all sorts of problems. From what I've read, granting permissions to anonymous users to "View products of any type" is another. The most recent encounter I had with this was sending an order summary to anonymous users on a site where the rule to create new user account on checkout completion had been disabled. So if you've got this working without disabling SQL rewriting, I'd say that's the most likely scenario, although I'd be interested to know why you did that in the first place.
Comment: That site has "View product of any type" granted to the anonymous user.  Thanks for the follow-up.
Comment: Also, you're assuming someone is using Drupal as a front end view. I'm using it purely via services, so need a code-only based approach.


Semi-transparent highlights using PySide and QTextEdit (version 2)

Question: I'm trying to make a more complete example of semi-transparent highlights using lists for:
(1) aggregate R,G,B,A, and highlight counts (five lists)
(2) average R,G,B,A (four lists)
The values in the average list get assigned as background colors. The aggregate lists are used to compute the average by adding and subtracting highlight colors. Each list has as many elements as characters in the text widget.
I'm using a pandas dataframe to store the highlights in memory, since there may be a ton of them to process in various ways as well as other data eventually. Placing the mouse over a character prints out its location, number of highlights, and RGBA values. Except, a problem pops up sometimes--as if a paint brush gets dragged for a second when moving from one highlight location to another. Look at the turquoise color on the "e" at the end of the text "PySide.QtCore". I think the problem is how I'm using the set and move positions of the cursor--but I'm not certain. Do I need to reset the position of the cursor after adding each highlight? Am I not selecting a single character correctly?
import sys
import pandas as pd
import sqlite3
from PySide.QtCore import *
from PySide.QtGui import *

def connect_database(db_file):
    try:
        conn = sqlite3.connect(db_file)
        return conn
    except Error as e:
        print(e)
        return None

def create_data(connection): # database connection
    c = connection.cursor() # database cursor
    c.execute("CREATE TABLE sections(id INTEGER PRIMARY KEY, start INTEGER, end INTEGER, r INTEGER, g INTEGER, b INTEGER, a INTEGER)")
    c.execute("INSERT INTO sections VALUES(1,0,20,100,200,100,100)")
    c.execute("INSERT INTO sections VALUES(2,15,20,200,100,100,50)")
    c.execute("INSERT INTO sections VALUES(3,18,30,100,100,200,100)")
    c.execute("INSERT INTO sections VALUES(4,50,60,100,200,200,150)")
    db.commit()
    return c.lastrowid

class QTextEdit2(QTextEdit):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setMouseTracking(True)
        self.cursor = self.textCursor()

        self.length = len(self.toPlainText())
        self.bg_red = [0 for n in range(self.length)]    # stores aggregate values of all highlights (not averages)
        self.bg_green = [0 for n in range(self.length)]
        self.bg_blue = [0 for n in range(self.length)]
        self.bg_alpha = [0 for n in range(self.length)]
        self.bg_count = [0 for n in range(self.length)] # number of highlights. if this is 0 then don't display
                                                        # stored r,g,b just display white. in this example
                                                        # only highlights are written. everything else stays
                                                        # default

        self.display_red = [0 for n in range(self.length)]    # set to the value to display (average of highlights)
        self.display_green = [0 for n in range(self.length)]
        self.display_blue = [0 for n in range(self.length)]
        self.display_alpha = [0 for n in range(self.length)]

        self.sections = self.load_sections()
        self.color_sections()

    def mouseMoveEvent(self, event):
        point = QPoint()
        x = event.x()
        y = event.y()
        point.setX(x)
        point.setY(y)
        n = self.cursorForPosition(point).position()
        print("%d: Section Count: %d   RGBA: %d %d %d %d" % (n, self.bg_count[n],self.display_red[n], self.display_green[n],self.display_blue[n], self.display_alpha[n]))
        super().mouseMoveEvent(event)

    def load_sections(self):
        c = sqlite3.connect("qda_test_01.sqlite")
        df = pd.read_sql_query("SELECT * FROM sections", c)
        return df

    def blend_colors(self, start, end, r, g, b, a):
        for n in range(start,end):
            self.bg_red[n] = self.bg_red[n]+r
            self.bg_green[n] = self.bg_green[n]+g
            self.bg_blue[n] = self.bg_blue[n]+b
            self.bg_alpha[n] = self.bg_alpha[n]+a
            self.bg_count[n] = self.bg_count[n]+1
            self.display_red[n] = self.bg_red[n]/self.bg_count[n]
            self.display_green[n] = self.bg_green[n] / self.bg_count[n]
            self.display_blue[n] = self.bg_blue[n] / self.bg_count[n]
            self.display_alpha[n] = self.bg_alpha[n] / self.bg_count[n]
            if self.display_red[n] > 255:   # just in case RGBA data is weird...
                self.display_red[n] = 255
            if self.display_green[n] > 255:
                self.display_green[n] = 255
            if self.display_blue[n] > 255:
                self.display_blue[n] = 255
            if self.display_alpha[n] > 255:
                self.display_alpha[n] = 255
            if self.display_red[n] < 0:
                self.display_red[n] = 0
            if self.display_green[n] < 0:
                self.display_green[n] = 0
            if self.display_blue[n] < 0:
                self.display_blue[n] = 0
            if self.display_alpha[n] < 0:
                self.display_alpha[n] = 0

            print("LOCATION: %d | SECTION:     r:%d    g:%g    b:%d     a:%d      | DISPLAY:     r:%d    g:%g    b:%d     a:%d" % (n,self.bg_red[n],self.bg_green[n],self.bg_blue[n],self.bg_alpha[n],self.display_red[n],self.display_green[n],self.display_blue[n],self.display_alpha[n]))

            color = QColor(self.display_red[n], self.display_green[n], self.display_blue[n])
            color.setAlpha(self.display_alpha[n])
            cursor = self.textCursor()
            cursor.setPosition(n)
            cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor, 1)
            charfmt = cursor.charFormat()
            charfmt.setBackground(color)
            self.setCurrentCharFormat(charfmt)
            self.setTextCursor(cursor)

    def color_sections(self):
        for n in range(self.sections.id.count()):
            print("-----SECTION:%d-----" % (n))
            section = self.sections.iloc[n]
            self.blend_colors(section.start, section.end, section.r, section.g, section.b, section.a)

if __name__ == '__main__':

    # Create database and sections to highlight
    fn='qda_test_01.sqlite'
    db=connect_database(fn)
    id=create_data(db)
    db.close()

    app = QApplication(sys.argv)
    window = QTextEdit2(
        "In addition, the PySide.QtCore.QPoint class provides the PySide.QtCore.QPoint.manhattanLength() function which gives an inexpensive approximation of the length of the PySide.QtCore.QPoint object interpreted as a vector. Finally, PySide.QtCore.QPoint objects can be streamed as well as compared.")
    window.show()
    sys.exit(app.exec_())

Comment: What is the application for this? What exactly is the purpose of the highlighting? Your code is very hard to understand without any context.
Comment: My code is also hard to understand because I am new to Python and rusty at programming in general. Each highlight represents a category assigned by one or more researchers. Researchers will re-categorize and even delete highlights, which often overlap several layers deep. Users can change colors as they prefer. In the social sciences, this process is called "[coding](https://en.wikipedia.org/wiki/Coding_(social_sciences))" interviews. I suspect that my problem is in the setPosition, movePosition, set format lines. But, if the code is too unreadable, I can try a more basic example and re-post.
Comment: The code seems to work OK when there is only one highlight. So, something goes awry when the process it repeated.
Answer: If you had used the code I gave you in my previous answer, the current example would work correctly. As it is, your changes have introduced lots of off-by-one errors.
To debug this, you should have first checked to see exactly which blocks of text should be highlighted. Taking the first 65 characters of the text and the start/end values from the database, this gives:
>>> t = "In addition, the PySide.QtCore.QPoint class provides the PySide."
>>> t[0:20]
'In addition, the PyS'
>>> t[15:20]
'e PyS'
>>> t[18:30]
'ySide.QtCore'
>>> t[50:60]
'es the PyS'

If you compare this to the highlights in the actual output, you'll see that none of the sections match up correctly (e.g. look at "S" in each "PySide").
To get this to work properly, you must get the text-cursor once at the beginning, use that to make all the necessary changes, and then re-set it once at the end:
cursor = self.textCursor()
for n in range(start, end):
    ...
    cursor.setPosition(n)
    cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor)
    charfmt = cursor.charFormat()
    charfmt.setBackground(color)
    cursor.setCharFormat(charfmt)
cursor.clearSelection()
self.setTextCursor(cursor)

This is analogous to updating a database: you use a cursor to schedule a series of changes, and then commit them as a single operation at the end.
Comment: Your code corrects the issue and your explanation is very helpful, especially pointing out that setTextCursor is analogous to a database commit. Given that the context is a text editing widget, I expected the "cursor" to behave identically to the cursor in a word processor, with cursor.setCharFormat instantly having an effect. As I tried to get my code to work, I ventured further and further from your previous code.


How do I compile Qt5 dev branch from git repository for the Raspberry Pi?

Question: There are a few tutorials on the net, which explain how to compile Qt5 for the Raspberry Pi. Unfortunately all of them are a bit out of date. Usually one gets 'undefined references' for some GLIBC functions.
This question and answer explains how to create an up-to-date (March 2015) gcc cross compiler:
How can I create a modern cross compile toolchain for the Raspberry Pi 1?
And this question and answer explains what has to be done to prepare Raspbian itself to be used by this compiler:
How do I prepare a Raspberry Pi with Raspbian so I can cross compile Qt5 programs from a Linux host?
But how is the Qt5 itself compiled?
Answer: To create a Qt5 for the Raspberry Pi several steps are necessary:
Get the Qt5 sources from git. To checkout Qt5:

git clone http://code.qt.io/cgit/qt/qt5.git

or

git clone http://code.qt.io/qt/qt5.git

The repository might change from time to time. The qt project is still evolving.
Above command in done on the Linux host. To get the dev branch cd to qt5 and:

git checkout dev

followed by

./initRepository

This will take quite some time. In this time the Raspberry Pi root folder can be mounted. It is possible to use a card reader and mount the SD card. A much better solution is to use either nfs, samba, sshfs to mount a life Raspberry Pi. This way minor bugs, e.g. missing dev packages, are easily fixed 'on the fly'.
I use sshfs:

sshfs pi@raspberrypi:/ /home/me/rasp

If this mount is successful, The root file system of the Raspberry Pi is accessible under /home/me/rasp.
As soon as the Qt5 is checked out, the following changes must be made:
In qt5/qtbase/mkspecs the file linux-arm-gnueabi-g++ must be edited (or copied and edited)
<code>MAKEFILE_GENERATOR      = UNIX
CONFIG                 += incremental

QMAKE_INCREMENTAL_STYLE = sublib

include(../common/linux.conf)
include(../common/gcc-base-unix.conf)
include(../common/g++-unix.conf)

# modifications to g++.conf
QMAKE_CC                = <path to>/arm-linux-gnueabihf-gcc
QMAKE_CXX               = <path to>/arm-linux-gnueabihf-g++
QMAKE_LINK              = <path to>/arm-linux-gnueabihf-g++
QMAKE_LINK_SHLIB        = <path to>/arm-linux-gnueabihf-g++

# modifications to linux.conf
QMAKE_AR                = <path to>/arm-linux-gnueabihf-ar cqs
QMAKE_OBJCOPY           = <path to>/arm-linux-gnueabihf-objcopy
QMAKE_NM                = <path to>/arm-linux-gnueabihf-nm -P
QMAKE_STRIP             = <path to>/arm-linux-gnueabihf-strip

QMAKE_INCDIR_EGL        = $$[QT_SYSROOT]/opt/vc/include/EGL/
QMAKE_INCDIR_OPENGL_ES2 = $$[QT_SYSROOT]/opt/vc/include/GLES2/
QMAKE_INCDIR_OPENVG     = $$[QT_SYSROOT]/opt/vc/include/VG/

QMAKE_LIBDIR_EGL        = $$[QT_SYSROOT]/opt/vc/lib/
QMAKE_LIBDIR_OPENGL_ES2 = $$[QT_SYSROOT]/opt/vc/lib/
QMAKE_LIBDIR_OPENVG     = $$[QT_SYSROOT]/opt/vc/lib/

QMAKE_LIBS_EGL          = -lEGL -lGLESv2
QMAKE_LIBS_OPENVG       = -lOpenVG -lEGL -lGLESv2
QMAKE_LIBS_OPENGL_ES2   = -lEGL -lGLESv2

LIBS  += -L$$[QT_SYSROOT]/opt/vc/lib -lvcos -lbcm_host -lvchiq_arm
LIBS  += -lEGL -lGLESv2

INCLUDEPATH  += $$[QT_SYSROOT]/opt/vc/include
INCLUDEPATH  += $$[QT_SYSROOT]/opt/vc/include/interface/vcos

INCLUDEPATH  += $$[QT_SYSROOT]/opt/vc/include/interface/vcos/pthreads
INCLUDEPATH  += $$[QT_SYSROOT]/opt/vc/include/interface/vmcs_host/linux
</code>
<path to> has to be replaced with the cross compiler, which was created according to: How can I create a modern cross compile toolchain for the Raspberry Pi 1?
Next step is to configure Qt5:
<code>   ./configure -opengl es2 -device linux-rasp-pi-g++ -device-option CROSS_COMPILE=<path to>/arm-linux-gnueabihf- -xplatform linux-arm-gnueabi-g++ -sysroot /home/me/rasp -opensource -confirm-license -optimized-qmake  -release -make libs -prefix /usr/local/qt5pi -v -libinput -linuxfb -directfb -xcb  -fontconfig -ts
   lib -evdev -iconv -xinput2 -xkbcommon-evdev -eglfs -icu -qt-pcre -lpthread  -system-sqlite -no-sql-sqlite2 -gstreamer 1.0 -reduce-exports
</code>
Special attention need the following parameters:

-xplatform linux-arm-gnueabi-g++ This is the mkspec. Change name accordingly, if linux-arm-gnueabi-g++ was not edited, but a new mkspec was created.
-device-option CROSS_COMPILE=<path to>/arm-linux-gnueabihf- Not sure, if this is necessary. Found it in some tutorials. Everything worked fine without this option. Adjust <path to> to cross compiler just as in the mkspec.
-sysroot /home/me/rasp Very important. The mount point where the Raspberry Pi is mounted.
-prefix /usr/local/qt5pi Where the Qt5 is to be installed on the RPi

Now all there is to do is the usual:
make/make install. The command builds Qt5 and installs it in /usr/qt5pi on the Raspberry Pi. Make sure proper write permissions exist for this location.
One more thing:

qtwayland/src/hardwareintegration/client/brcm-egl/qwaylandbrcmeglintegration.h

contained a bug when I compiled my qt5.
A quick fix is to edit this file:
<code>#include <QtWaylandClient/private/qwaylandclientbufferintegration_p.h>

#include <wayland-client.h> <--- add this below the #include above.
</code>
One last thing: This qt5 is NOT suitable to be used from within the Raspberry Pi itself. When programs are created, the RPi must be mounted and the compilation must be done under the same host with the same cross compiler on which the Qt5 was compiled.
Another last thing: The RPi does not support xcb. So X11 forwarding is not possible.
EDIT: I have been told this is not true. No, it isn't. However, what is true, the RPi does not support xcb/X11 for programs, which use OpenGL. So no qtquick 2 programs: http://lists.qt-project.org/pipermail/qtonpi/2012-October/001087.html
Nothing to be done about this at the moment, its graphics driver simply don't support it. Wayland support is limited. Best platform to be used is eglfs.
Comment: The guide is almost complete, but it contains wrong information here and there.
Comment: There's absolutely no need to modify the mkspecs. The ones shipped with 5.3+ are just fine. Just be sure to pass the right compiler paths to `-device-option`.
Comment: It might be overkill to compile ALL of Qt, it's also possible to just compile the modules that one needs.
Comment: X11 works on RPi, so why saying it doesn't? Note how your configure command line asks for XCB support.
Comment: Your sshfs trick (lacking a proper sysroot) is neat, but 1) it's going to slow down the compilation *a lot*. You also need dummy ciphers to avoid overload the RPi's CPU. Plus, add the limited network bandwidth over it. 2) requires `transform_symlinks` or any absolute symlink on the RPi is going to point at non existing files on your host.
Comment: @pepe, this is what worked for me. And the mkspecs are not fine for the Raspberry Pi. As you can see, I added all kinds of LIBS and QMAKE variables to the mkspec. I also added the correct -device-option... did not work. My compiler was not found without the hack in this mkspec. I don't say, above tutorial is perfect. Usually there is more than one possible solution. This is more or less the result of a few days trial and at the moment I don't muss anything.
Comment: **X11 works on RPi, so why saying it doesn't?** Yes and no. You are right I have to reword this. X11 works on RPi, but is for many use cases absolutely worthless. It does not work for program, which use OpenGL: http://lists.qt-project.org/pipermail/qtonpi/2012-October/001087.html This means: No qtquick 2 on RPi using X11.
Comment: **transform_symlinks** I mentioned that in the previous part of the tutorial: http://stackoverflow.com/questions/30120871/how-do-i-prepare-a-raspberry-pi-with-raspian-so-i-can-cross-compile-qt5-programs?lq=1  Also: Probably other ways to handly this, but I am using my Qt5 on RPi for quite a while and don't see any drawbacks, yet.
Comment: The 'sshfs' slow... Yes and no... I still see people compiling qt5 on their RPi since they don't know how to setup a cross compile environment. Compared to them, the sshsf method is lightning fast. My qt5 was compiled in 6hrs. I read about 38hrs when compiled natively on an overclocked RPi.
Comment: Btw... such a tutorial should be a work in progress. If you would like to improve it.... :-) Btw2... do you think nfs or samba is faster than sshfs? As I wrote, in theory you can just mount the SD card, but I prefer to have my RPi 'life', e.g. to quick fix a path or missing package.


How to check if 2D array has three same values in a row

Question: I'm trying to find out how is it possible to check if 2D array contains 3 same values in a row. This 2D array will be generated by user, so function for checking must be dynamic.
For example let's say user types in 4x4. Result will be this
  let arr=[
    [" "," "," "," "],
    [" "," "," "," "],
    [" "," "," "," "],
    [" "," "," "," "]
  ]

Let me add some values to that array
  let arr=[
    [" "," ","x","x"],
    ["x","x","x"," "],
    [" "," "," "," "],
    [" "," "," "," "]
  ]

I've tried to solve this with this function, but yesterday I've noticed it doesn't for properly.
  function checkArray(arr){
    for(let i=0;i<arr.length;i++){
      let count = 0;
      for(let j=0;j<arr[i].length;j++){
        if(arr[i][j] === 'x'){
          count++;
        }

        if(count === 3 ){
          console.log('x wins')
        }
      }
    }
  }

  console.log(checkArray(arr)) //count will be 3 and console.logs 'x wins'.

At this moment I thought everything is working fine until I've tried to fill the array like this. As you can see there are not three X's in a row(I mean they don't go like this - x,x,x), and there is one blank space between them.
  let arr=[
    [" "," ","x","x"],
    ["x","x"," ","x"],
    [" "," "," "," "],
    [" "," "," "," "]
  ]

So condition shouldn't be fulfilled and function should not console.log('w wins'). But it does. My approach for this problem is working for whole row ,not only if there are 3 in a row (x,x,x).
I hope I've explained it clearly. Thanks for you advices.
Comment: Instead of looping over the hole array to look for 3 in a row, check every direction from the position that the user inserted the value at
Answer: You need to reset the count if you do not get an 'x'.

function checkArray(arr) {
  for (let i = 0; i < arr.length; i++) {
    let count = 0;
    for (let j = 0; j < arr[i].length; j++) {
      if (arr[i][j] === 'x') {
        count++;
        if (count === 3) {                    // place check after incrementing
          console.log('x wins')
          return true;
        }
      } else {
        count = 0;                            // reset
      }
    }
  }
  return false;
}

let arr = [
  [" ", " ", "x", "x"],
  ["x", "x", " ", "x"],
  [" ", " ", " ", " "],
  [" ", " ", " ", " "]
]

console.log(checkArray(arr));
Comment: thank you! Your solutions worked for me. I mean ,it works for horizontal and vertical. But now for diagonal it doesn't work.


Spring MVC Controller not resolving URI

Question: This is a similar question to those that have been asked before, but still different, and I simply can't figure it out.
I have a controller for a REST webservice implemented with MVC which should be handling requests for the path '/users/contacts', the problem is that in my client test app, when I try to hit that path I get:
No mapping found for HTTP request with URI /users/users/contacts in DispatcherServlet with name 'webservice'

Again, in my client test app, when I change the request path to something like '/WHATEVERusers/contacts', I'll get an error that it can't resolve '/WHATEVERusers/contacts'
I don't know why when I try to hit a path handled by a controller it get's mangled, but when I request some garbage path, it doesn't.
I don't have the code in front of me, but will be able to answer questions when I get home.
Here's code from my test client:
private static void TestGetContacts()
{
    UserCreateRequest request = new UserCreateRequest();

    Gson gson = new Gson();

    try

    {
        HttpClient client = new DefaultHttpClient();

        StringEntity string  = new StringEntity(gson.toJson(request), HTTP.UTF_8);
        string.setContentType("application/json");

        URI uri = URIUtils.createURI("http", "localhost", 8888, "/users/contacts", null, null);

        HttpPost post = new HttpPost(uri);
        post.setEntity(string);

        client.execute(post);
    }
    catch(Exception ex)
    {
        System.out.println(ex.getMessage());
    }
}

Here's my controller class:
@Controller
@RequestMapping("/users/contacts")
public class UserContactService
{
private @Autowired ApplicationContext appContext;

@RequestMapping(method=RequestMethod.POST, consumes="application/json", produces="application/json")
public GetContactsResponse GetContacts(@RequestBody UserCreateRequest request)
{
    GetContactsResponse response = new GetContactsResponse();

    return response;
}
}

Here's my servlet config:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
    xmlns:oxm="http://www.springframework.org/schema/oxm"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">

<context:component-scan base-package="com.impersonal.server.restservice.users"/>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonConverter" />

        </list>
    </property>
</bean>

<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes" value="application/json" />
</bean>

And here's my web config:
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/**/applicationContext.xml</param-value>
</context-param>

<servlet>
    <servlet-name>webservice</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>webservice</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

Update:
My requests are handled in my controller, but after the request is handled, the server prints out that it couldn't resolve /users/users/contacts.  For some reason another request is getting to DispsatcherServlet, and I don't know why..
Thanks,
Mark
Comment: Without more information, it's hard tell if the problem is in your client or in your web service. Post more details about your client test app, or take client confusion out of the picture by using a simple HTTP client such as cURL. Also post more details about your web service, including how you configure it to handle specific URLs.
Comment: Can you please provide the servlet-mapping for your Dispatcher Servlet, and the webapplications context name also - is either of these /users by any chance. Also, how have you initialized Spring MVC, is it just using mvc:annotation-driven or have you customized the handleradapter or handler mapping in any way
Comment: can you share your controller class?
Answer: Adding @ResponseBody to my method signature solved my issue.  Didn't realize I actually needed it, and not having it resulted in really odd side affects.
Answer: Have you tried putting the url in the @RequestMapping above your method instead of above your Class? I've noticed that it might solve URI Mapping issues from time to time.
You could handle more urls with different methods in the same class. You could even add @RequestMapping("/users") above your Class and add different methods with

@RequestMapping("/contacts") maps to /users/contacts
@RequestMapping("/customers") maps to /users/customers

Spring MVC Controller not resolving URI


numpy list comprehension and +=/-= operator

Question: I was trying to vectorize some list calculation, but find something weird when I attempting to use list as index, especially when I try to write back to the original list, repeated list index seems to be useless:
import numpy as np

x = np.arange(10)
y = np.array([1,2,3,4,5])
z = np.array([1,1,1,1,1])

print(x[y], x[z])

>>out: [1 2 3 4 5] [1 1 1 1 1], same as I expected
x = np.arange(10)
x[y] -= 1
print(x[y])

>>out: [0 1 2 3 4] this is good as no repeating in index list
x = np.arange(10)
x[z] -= 1
print(x[y])

>> out:[0 2 3 4 5], Here I am expecting [-4 2 3 4 5], which means x[1] should -- for 5 times, but it turns out to subtract only once
Comment: Perhaps a duplicate of this?: https://stackoverflow.com/questions/15973827/handling-of-duplicate-indices-in-numpy-assignments
Answer: There's a buffering issue.  ufuncs were given a .at method to resolve this:
In [392]: np.add.at(x,z,-1)
In [394]: x[y]
Out[394]: array([-4,  2,  3,  4,  5])

I think the documentation for ufunc.at explains this well
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.at.html
It's come up periodically in other SO questions.
x[z] -= 1

is evaluated like:
x[z] = x[z] -1

while you were expecting:
for i in z:
    x[i] -= 1


Module compatibility between major Drupal versions

Question: I am planning to use Drift chat on Drupal website, which is built in Drupal 7.
I could see Drift modules only for Drupal 8? Will this work with Drupal 7 as well?
Comment: It seems to me that the answer given by No Sssweat is correct and therefore should be accepted.
Answer:
Will this work with Drupal 7 as well?

Nope. D7 and D8 are vastly different under the hood; therefore, there is no backward and no forward compatibility across Core versions. If there are none for D7 you will have to build one or upgrade your site to D8 if you see fit.
Comment: Means Drift module for D7 is not available?
Comment: @GauravG correct
Comment: Can you please suggest me best chat bot for D7?
Comment: @GauravG I haven't used any chat bot, so I can't suggest you one.


How many solutions does the equation a+b+c+d+e+f = 2006 have where a, b, c, d, e , and f are all positive integers?

Question: I know that this is a combinatorical problem. I even have the solution which is given as follows:

Given that the variables are all positive integers, we can subtract 1 from each of
  them and subtract 6 from the other side to obtain a new equation where we are
  expressing 2000 as an ordered sum of 6 non-negative integers.  There are
  (2000+5 5) = (2005 5)
   ways to do this.

I can't understand why we have to subtract 1 ?
I can imagine the whole equation as a line of points which are separated by bars and the points to each bar are actually the number represented by the corresponding variable. So I would have  n-1 bars (if n is the number of variables). But here I can't get why we need to subtract 1 from all of the variables... Thank you in advance !
Comment: @barakmanos: Note that Wikipedia's [stars and bars](https://en.wikipedia.org/wiki/Stars_and_bars_%28combinatorics%29) article gives direct theorems both for the "positive" and the "non-negative" cases.
Comment: The starts 'n' bars method is suitable under the restriction of **non-negative** integers. The problem at hand is restricted to **positive** integers, so you need to reduce it to an equivalent problem with an appropriate restriction.
Answer: Write
$$ \underbrace{1+1+1+\cdots+1+1+1}_{2006} $$
Your task is to color $5$ of the $2005$ plus signs red and collapse the rest of them. (Since all of your variables are positive, the same plus sign can't be used twice).
This can be done in $\binom{2005}{5}$ ways.
Comment: @vidyarthi: No -- why would it be? If the six variables were allowed to be zero, the answer would be $\binom{n+r-1}{r-1}=\binom{2011}{5}$, but it is explicitly specified here that they _can't_ be zero. Why would that lead to the even higher number $\binom{2011}{6}$?
Comment: is not the answer $\binom {n+r-1}{r} = \binom{2011}{6}$ ?
Comment: thanks, the "positive" and "nonnegative " make a huge impact!


In how many ways can we put balls in drawers with the following conditions

Question: Say we have 5 drawers and 17 identical balls. In how many ways can we put the balls in the drawers that the upper drawer will have exactly 3 balls. The middle will have at least 4 balls and the lowest will have at most 5?
I tried to do it by the complementery way, I calculated all of the options and removed the bad options(when there are more than 5 balls in the lowest drawer) ${10+4-1\choose 4-1}(all) - {4+4-1\choose 4-1}(6 balls) - {3+4-1\choose 4-1}(7 balls) - {2+4-1\choose 4-1}(8 balls) - {1+4-1\choose 4-1}(9 balls) -1(10 balls) = 216$
Can someone confirm or fix me?
Thanks in advance!
Answer: Let's start by placing three balls in the top drawer and four balls in the middle drawer.  Since we can place no more balls in the top drawer, this leaves us with ten balls to distribute to the bottom four drawers, subject to the restriction that the number of balls placed in the lowest drawer is at most $5$.  Therefore, if we let $x_k$ denote the number of balls placed in the $k$th drawer from the bottom, then we obtain the equation
$$x_1 + x_2 + x_3 + x_4 = 10 \tag{1}$$
subject to the restriction that $x_1 \leq 5$.  Equation 1 is an equation in the nonnegative integers.  A particular solution corresponds to the placement of three addition signs in a row of ten ones.  For instance,
$$1 1 1 + 1 1 + + 1 1 1 1 1$$
corresponds to the solution $x_1 = 3$, $x_2 = 2$, $x_3 = 0$, and $x_4 = 5$, while
$$1 1 1 1 + 1 1 + 1 1 1 + 1$$
corresponds to the solution $x_1 = 4$, $x_2 = 2$, $x_3 = 3$, and $x_4 = 1$.  Therefore, the number of solutions of equation 1 in the nonnegative integers is the number of ways we can insert three addition signs in a row of ten ones, which is
$$\binom{10 + 3}{3} = \binom{13}{3}$$
since we must choose which three of the thirteen positions (ten ones and three addition signs) will be filled with addition signs.
However, we have counted distributions in which more than five balls are placed in the bottom drawer.  We must subtract these from the total.  If more than five balls are placed in the bottom drawer, then $y_1 = x_1 - 6$ is a nonnegative integer.  Substituting $y_1 + 6$ for $x_1$ in equation 1 yields
\begin{align*}
y_1 + 6 + x_2 + x_3 + x_4 & = 10\\
y_1 + x_2 + x_3 + x_4 & = 4 \tag{2}
\end{align*}
Equation 2 is an equation in the nonnegative integers with
$$\binom{4 + 3}{3} = \binom{7}{3}$$
solutions since we must choose which three of the seven positions (four ones and three addition signs) will be filled with addition signs.
Hence, the number of ways we can distribute $17$ balls to five drawers if exactly three are placed in the top drawer, at least four are placed in the middle drawer, and at most five are placed in the bottom drawer is
$$\binom{13}{3} - \binom{7}{3}$$
In your attempt, you subtracted off the number of cases with at least six balls, at least seven balls, at least eight balls, at least nine balls, and all ten of the remaining balls placed in the bottom drawer.  However, you only needed to eliminate those cases with at least six balls placed in the bottom drawer.
If you wanted to eliminate those cases with exactly six balls placed in the bottom drawer, you would need to count the number of solutions of the equation
$$x_2 + x_3 + x_4 = 4 \tag{3}$$
in the nonnegative integers.  To eliminate those cases with exactly seven balls in the bottom drawer, you would need to count the number of solutions of the equation
$$x_2 + x_3 + x_4 = 3 \tag{4}$$
in the nonnegative integers.  To eliminate those cases with exactly eight balls in the bottom drawer, you would need to count the number of solutions of the equation
$$x_2 + x_3 + x_4 = 2 \tag{5}$$
in the nonnegative integers.  To eliminate those cases with exactly nine balls in the bottom drawer, you would need to count the number of solutions of the equation
$$x_2 + x_3 + x_4 = 1 \tag{6}$$
in the nonnegative integers.  To eliminate the case with exactly ten balls in the bottom drawer, you would need to count the number of solutions of the equation
$$x_2 + x_3 + x_4 = 0 \tag{7}$$
in the nonnegative integers.  Notice that adding the number of solutions of equations 3, 4, 5, 6, and 7 yields
$$\binom{6}{2} + \binom{5}{2} + \binom{4}{2} + \binom{3}{2} + \binom{2}{2} = \binom{7}{3}$$


Linear Regression with heavy tailed noise

Question: The model is linear $y_i = a\cdot x_i + b + e_i,~ i = 1,2,\ldots,N  $. It is given that the noise is heavy tailed. However the distribution of noise conditional on $x$ is the same for all data points. My question is that how should I model the data generating process? Should I use a Student-t distribution for the noise process? Should I use M estimator in R?
Facts:
 1. OLS is not to be used.
 2. 2. The noise distribution can depend on $x$, but is independent across samples.
 3. conditioned on the value of $x$, noise's mean is 0.
 More clarification: the distribution of noise at $x$, i.e., $N(x)$ is a function of $x$. However for different data samples $i=1,2,\ldots,M$, the distribution of noise samples remains the same.
Comment: Is this an empirical problem (i.e. fitted model with assumptions being violated) or a theoretical (math) problem?
Comment: I am given a data set containing $x_i,y_i$ and I have to estimate $a,b$
Comment: See http://stats.stackexchange.com/questions/66173/regression-model-of-large-correlated-heavy-tailed-data   http://stats.stackexchange.com/questions/154489/pvalues-of-glm-coefficients-and-heavy-tailed-distributed-residuals   http://stats.stackexchange.com/questions/259772/how-to-analyze-random-variables-with-non-normal-distribution/259934#259934    http://stats.stackexchange.com/questions/26235/are-regressions-with-student-t-errors-useless
Answer: You could use iterative feasible generalized least squares.
Start by setting weights for each datapoint to 1, i.e. no weighting, and use the following algorithm:

Fit a weighted regression model for each dataset using weights.
Create a single dataset combining squared residuals/errors, $e_i^2$ and their respective $x$ values.
Fit $e_i^2 = a\cdot x_i + b$. If the noise is zero mean, $e_i^2$ is equal to the variance of the error at $x_i$.
Update your weights with the squared errors prediction model
Go back to 1 until convergence.
Comment: For the improvement of the community, please describe negative votes.


When does a control in Silverlight get released\destroyed?

Question: Is there any documentation around the life cycle of a control in Silverlight?
Specifically I'm interested when a control is released (memory garbage collected) when used as part of an item template in a listbox, so when new items are bound to the listbox when do the old controls (no longer bound) get released?
I'm not interested in the workings of the GC and the ideas behind a manageed environment.
Answer: The basic rule of thumb applies to control objects as well. They are collected when no one references them and GC starts collecting.
Just to make it clear, unloading of a control is different than garbage collecting.


Asymptotic distribution of the exponential of the sample mean

Question: I've needed to brush up on asymptotics recently, and I came across this interesting problem.
Let $(Z_{1}, Z_{2},...,Z_{N})$ be a random sample from a distribution from mean $\mu$ and variance $\sigma^2$. What is the asymptotic distribution of $Y=$ exp($\bar{Z}$)?
Here's what I've got so far. Just from the information of $Z$ alone, coupled with the fact that it's a random sample from some distribution, I can say $$E(\bar Z) = E(Z) = \mu$$ and $$Var(\bar Z ) = \frac{Var(Z)}{N} = \frac{\sigma^2}{N}$$.
I was wondering what $Y$ would look like. Intuitively, it looks like an exponential random variable, but I'm at a struggle as to why we would need an asymptotic distribution in that case. I would appreciate a hint or guidance as to what to do from here. I'm not very good with asymptotics, so if you could also give theorems or references, I would appreciate it (but it's not necessary).
Comment: Note that asymptotically, $\bar{Z}$ converges to $\mu$.
Comment: Use the delta method, as in @Alecos's answer. [For intuition](https://stats.stackexchange.com/questions/243510/how-to-interpret-the-delta-method/243525#243525), observe that in any tiny ball $(c - \epsilon, c + \epsilon)$, the function $f(x)  = e^x$ is just a line, an affine function $f(x) \approx e^c + e^c (x - c)$. So as $n$ gets larger, you're getting closer to an affine function of a normally distributed random variable (since the sample mean converges on the normal distribution). An affine function of a normally distributed random variable also follows the normal distribution.
Answer: By the Delta theorem, if
$${\sqrt{n}[\bar Z_n-\mu]\,\xrightarrow{D}\,\mathcal{N}(0,\sigma^2)}$$
then
$${\sqrt{n}[g(\bar Z_n)-g(\mu)]\,\xrightarrow{D}\,\mathcal{N}(0,\sigma^2\cdot[g'(\mu)]^2)}$$
I guess you can do the rest.


Alternative intervals power chords in just intonation

Question: I was wondering, distorted power chords tend to work really well because in 12 equal temperament the root and fifth are pretty close to just intonation. A detailed explanation can be found in the link below.
https://en.wikipedia.org/wiki/Power_chord#Analysis
Would 'power chords' with different intervals (like thirds) in just intonation create the same effect without sounding as messy?
Comment: I know it's not really a power chord, that's why I put it in quotes. What I'm getting at is, could you produce something like a [combination tone](https://en.wikipedia.org/wiki/Combination_tone) with different intervals used on a distorted guitar. Or maybe another way to put it. Would distorted intervals sound more clear in just intonation?
Comment: by definition a chord with a third would not be a power chord.
Comment: By the way we play 3rds all the time on the 12TET guitar with distortion and it's not "messy".
Comment: @ggcg - I'd have said 'messier' than 4ths or 5ths. I reckon the point of 'power chords' is they omit the 3, with its harmonics that clash.
Comment: But that's also true in just tuning.  Not as bad but still true.
Comment: Technically, any "chord" with only two notes is not a chord at all, but a double-stop.
Answer:
Would 'power chords' with different intervals (like thirds) in just intonation create the same effect without sounding as messy?

Yes. Crank up the gain and try playing e.g. G#4 on the 9th fret of the 2nd string and B4 on the 7th fret of the 1st string. You need to tune the 2nd string a bit lower, to bring it to just intonation. If you do it simultaneously (tune 2nd string while holding G#–B interval) you will hear a combination tone approaching low E2 note, thus creating E-major triad. (A bit easier, though slightly out of tune possibility is to bend B note rather than detune the 2nd string).
Another, even simpler, though maybe less striking example: play B4-E5 (fourth interval), e.g. on the 12th fret of the 2nd and 1st string. No detuning needed. Low E3 note will be produced.
Perhaps these are not what's normally called power chords (especially if you add chord components other than prime and fifth), but it's a similar class of sonic effect.
Some electric guitarists detune top strings in some songs to get better sound of chords. See e.g.

You may say it's for better sound of just intonation, but with distorted guitar the intervals created by the combination tones become actually audible so bringing them in tune makes a large difference.


How to subtract groups within a data frame?

Question: Take this data frame...
df <- data.frame(cat = rep(c('cat1','cat2','cat3'),each=3),
                 subcat = rep(c('a','b','c'),3),
                 y1 = c(rep(10,3),rep(1,6)),
                 y2 = c(rep(10,3),1:6))

df:
cat subcat y1 y2
cat1      a 10 10
cat1      b 10 10
cat1      c 10 10
cat2      a  1  1
cat2      b  1  2
cat2      c  1  3
cat3      a  1  4
cat3      b  1  5
cat3      c  1  6

I'm looking to subtract cat2 and cat3 from cat1... and calling the resulting cat something like new.cat1. The result I'm looking for should be a data frame that looks like this (or it could simply be appended to df.)
     cat subcat y1 y2
new.cat1      a  8  5
new.cat1      b  8  3
new.cat1      c  8  1

In this example, I have only one sub-category but I'm looking for a method which could have potentially several sub-categories. Any help?
Answer: You can try aggregate using formula as below.
df
##    cat subcat y1 y2
## 1 cat1      a 10 10
## 2 cat1      b 10 10
## 3 cat1      c 10 10
## 4 cat2      a  1  1
## 5 cat2      b  1  2
## 6 cat2      c  1  3
## 7 cat3      a  1  4
## 8 cat3      b  1  5
## 9 cat3      c  1  6

res <- aggregate(formula = cbind(y1, y2) * ifelse(cat == "cat1", 1, -1) ~ subcat, data = df,
    FUN = sum)
cbind(cat = "new.cat1", res)
##        cat subcat y1 y2
## 1 new.cat1      a  8  5
## 2 new.cat1      b  8  3
## 3 new.cat1      c  8  1

Comment: Hmmmm... This I think would work but my guess is that the more and more subcategories one has, the more intricate the ifelse expression would have to be. But this is a good step in the right direction so thanks!
Answer: You could use plyr::ddply.  Not sure how you want it appended to df though.
> library(plyr)
> ddp <- ddply(df, .(subcat), summarize,
        y1 = sum(y1[1], -y1[2:3]), y2 = sum(y2[1], -y2[2:3]))
> cbind(cat = 'new.cat1', ddp)
#        cat subcat y1 y2
# 1 new.cat1      a  8  5
# 2 new.cat1      b  8  3
# 3 new.cat1      c  8  1

Comment: Thanks for this. Though I think this would work for the example I provided, this relies on subtracting using row indices. I'd have to note and enter the relevant indices into the code to get this to work... further, I don't believe this would work well with multiple subcategories, eh?


How loud is an alto recorder?

Question: I was thinking of starting to learn an instrument. Many people on the internet say recorder is not a very difficult instrument and I can learn alone without a teacher. But I was wondering how loud a recorder is, because I don't want to disturb my neighbors above and below me (I live in an apartment) and my wife.
I have a blues harmonica and I find it not very loud. Is the alto recorder louder than a harmonica? Or can you compare its loudness to something else (acoustic guitar, the voice of a canary bird, etc.)?
Answer: It is less loud than a transverse flute. When played in the upper register, it will probably match your harmonica; it may be a touch more piercing, depending on the harmonica. In the lower register, which is what you will learn first, it is fairly soft. In general, the lower pitched a recorder is, the softer it gets: the alto is less piercing than a C soprano; an F bass is softer than the alto; a C tenor is somewhere between the alto and bass. (The only problem is that the price goes up as the pitch goes down, only faster. <wry grin>)
Comment: [This might also be of interest](http://physics.stackexchange.com/questions/87751/do-low-frequency-sounds-really-carry-longer-distances)
Comment: Yeah, but the lower recorders, and the lower notes on a given recorder, really are softer - lower decibel level. The lower registers take a large volume of air at a low pressure to produce a stable sound; the larger the recorder, the larger the volume of air, but _still_ at a low pressure. I used to play the F bass. I had a helluva time making myself heard over a piano playing ___mf___.
Comment: My mother has played her alto recorder outdoors in her hot tub practically every night (only a slight exaggeration) for more than 15 years, and so far I don't think the neighbors have complained, so you may be right (an owl even sat with her some nights, and she hasn't even learned the correct fingering yet! :) never miss a chance to pick on mom)
Answer: Patrx2's answer is spot on.
Playing a recorder in tune and on pitch requires a certain amount of breath pressure. If you don't put enough air into a recorder it will be flat and soft; too much air and you'll be louder and sharp. The fingering for each note also contributes -- the more fingers down the softer the note will be and the less pressure you need. The highest notes are the loudest by far.
Finally the voicing of the recorder, i.e, the combination of the design of the windway, hole placement and size, and bore characteristics determine how loud or soft it can be played and still be in tune.
Good plastics nowadays like Yamaha and Zen-on are fairly quiet, imho. Altos can easily keep up with acoustic guitars and harmonicas. Violins are a different story -- they have to be played with a little delicacy to not overpower a recorder. Because an alto is usually playing around C5-C6 (one/two octaves above middle C) they tend to be easily heard with/among singers.
It is true that the larger the recorder the quieter the sound. Tenors are much more mellow and the standard Yamaha plastic isn't that expensive, so may be a good choice for you.
There is also an easy trick to mute a recorder without interfering with the pitch: fold a tiny rectangle of paper into a V and carefully put it into the windway to cover a small part of the labium (the edge). Sort of like this: }- <- where } is your mouth, the first - is the mouthpiece, < is the piece of paper and - is the labium. I've used this trick to play in hotel rooms and have never had a complaint lodged against me.
Good luck with your journey. Recorders are wonderful instruments that are indeed easy to learn to play and are as rewarding as any other serious instrument.
Answer: Your question is full of mistakes.  The big mistake is that you think there is an easy instrument.  Any instrument you choose will be a lifelong challenge in pursuit of excellence.
Your choice of instrument could depend on the music you want to perform.  Although I can do "Jesus Joy of Man's Desiring" on harmonica, I do it much better on recorder.  I think you should learn both instruments.
You seem to want more volume from your blues harmonica.  Be advised that you have the wrong instrument.  For blues you should have a Hohner Golden Melody, a Huang Star Performer, or a Lee Oscar.  These have plastic combs that will not irritate your mouth.
For more power from the harmonica, drop your jaw and thrust it forward a bit.  Better yet, get some help from a professional harmonica teacher; some of them have excellent instructional web sites such as harmonicalessons.com.  Try to socialize with other musicians.
If you want LOUD, consider transverse flute, piccolo, or fife at the high end of its range.  Fifes were once used for military signaling because they could be heard through gun and cannon sounds.
Comment: "You seem to want more volume" It seems to me OP is looking for a *quiet* instrument!

How loud is an alto recorder?


getting location and running a function on a new window (following window.open) and not the old

Question: I'm a junior dev' and trying to open a new window following ng-click on a button, then run a function with setTimeout on the new window in order to parse a parameter from the new window url. This is my code, but it doesn't really work on the new window (nor console.log or alert):
<code> window.open("https://runkeeper.com/apps/authorize?client_id=499eec7e74084561ac8cd8018fd090f2&redirect_uri=http://localhost:3000/&response_type=code")
        setTimeout(function(){
            var wl = window.location
            alert(wl);
            wl = wl.href.split("/code")
            console.log("this is wl", wl);
            wl = wl[1]
            carrotService.connectRunkeeper(wl)
        }, 5000)
</code>
Appreciate your time and help,
Ark
Comment: *"it doesn't work"* is not a proper actionable problem statement. Why are you trying to split on `"/code"` when those characters don't exist together? What are you trying to pass to the function? This would be a good time to review [ask]
Comment: I think you need to attach `window.open` to a variable and use that. So `var opener = window.open(...`
Answer: Since you can easily call functions on a popup window's opener why not have your new window call a function on the opener once it resolves to your redirect URI
On the page it redirects to (defined as redirect_uri in your location string), you could have some on-load JS code that gets the parameter you need and sends it to the window.opener
ie:
<code>window.onload = function() {
    var val=getQueryVariable(PARAM_YOU_NEED)
    window.opener.myFunctionOnWindowLoad(val)
}

function getQueryVariable(variable) {
   var query = window.location.search.substring(1);
   var vars = query.split("&");
   for (var i=0;i<vars.length;i++) {
           var pair = vars[i].split("=");
           if(pair[0] == variable){return pair[1];}
   }
   return(false);
}
</code>
(Borrowed that non-jQuery param code from https://css-tricks.com/snippets/javascript/get-url-variables/)
Would that fix your wagon or did I misunderstand what you're trying to do?
Comment: Thanks a lot for the reply John! It didn't really help me, but I think it's me, not your advice. Meanwhile I was trying to do the following: add a route in the app.js to get the auth_code from the url, then send it to the services and from there to the server, but I keep getting 400