TypeInitializationException while getting fingerprint scanner list in Windows 8 Metro App using Neuro technology SDK

Question: I am using trial VeriFinger SDK. I have added all the supported DLLs from dotNET_Portable folder. I have changed AnyCPU to x64. But I am getting exeption while initializing NDeviceManager object. My code is given below. Can anyone please tell me what I am doing wrong ?

System.TypeInitializationException : The type initializer for
  "Neurotec.Devices.NDeviceManager" threw an exception. Exception
  message : The type initializer for "Neurotec.Devices.NDeviceManager"
  threw an exception. InnerException : Unable to load DLL "NDevices":
  The specified module could not be found. (Exception from HRESULT:
  0x8007007E)

<code>using Neurotec.Devices;

private NDeviceManager _deviceMan;

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    _deviceMan = new NDeviceManager(NDeviceType.FingerScanner, true);
}

private void btnRefreshScannerList_Click(object sender, RoutedEventArgs e)
{
    var Scanners = _deviceMan.Devices;
    //TODO:
}
</code>
Comment: **WinRT**? It seems it's a **not supported environment** (see [this page](http://neurotechnology.com/verifinger-system-requirements.html)).
Comment: I asked their support team they told me the trial SDK has "dotNET_Portable" folder which contains DLLs supported to x86 & x64 WinRT not ARM WinRT.
Comment: Based on [this post](http://social.msdn.microsoft.com/Forums/vstudio/en-US/14dc569b-b761-4021-b3a7-559138daaf71/the-specified-module-could-not-be-found), you may be missing the driver DLL as a reference, either in your PCL or WinRT project. It further suggests you check out [Dependency Walker](http://www.dependencywalker.com/) to try and track down which DLL it is.
Comment: No, I don't think I am missing any module. As I am following it's Winform app. I added all the DLLs same (name wise only) as WinForm app.
Answer: In addition to dotNET_Portable dlls, you also need to add native libraries NDevices.dll, NCore.dll, NMedia.dll & other dependencies from Bin\Win64_x64 (or Bin\Win32_x86, depending on what platform you are targeting). Please refer to picture how this should be done:
Comment: You need to use both DLLs from dotNET_Portable (which you're probably using correctly, as they are like any other .NET assembly), and also native DLLs, which should be added as content to project (see edited answer for screenshot how this is done in Visual Studio).
Comment: Where do I need to copy ? When I try to add reference of those DLLs, I am getting error that "it's not valid assembly or COM components". Do I need to use DLLs from "dotNET_Portable" or from "Bin\Win64_x64 or Bin\Win32_x86". I am creating Windows 8 metro app, not the WinForm or WPF app.


Is batsman allowed to "score" leg byes by kicking the ball while pretending to hit it with the bat?

Question: If the ball strikes the striker's person, any runs scored are credited as leg bye extras provided that the striker was either attempting a shot or trying to avoid getting hurt.
For balls whose trajectory would clearly miss the stumps (hence, LBW doesn't apply), the batsman can line up his bat alongside his leg, and then kick the ball while moving the bat in sync with the leg. This makes it appear he was attempting a bat-pad shot, making him "eligible" to score leg byes while eliminating any possibility of getting out caught. There could be other "creative" ways of faking a shot while deliberately hitting it with the leg, as well.
Is this kind of misuse allowed, and if not, what is the provision in the laws against it?
Answer: This is covered in Law 26 - Bye and Leg Bye section 2 A(i) - the striker must make a genuine attempt to play the ball with his bat, and the umpire is the sole judge of this. If he or she feels the player has not made a genuine attempt (by hiding the bat behind the leg, for instance), they call "dead ball" (after completion of the first run), and return the batsmen to their original ends.
The custom of allowing completion of the first run is to allow the fielding side attempt a run-out, which will be valid if achieved.


Transferi uma image de uma imageview para outra imageview em outra fragment

Question: Galera tenho uma grid view que exibe imagens de um servidor, quando se clika na imagem eu tenho que recarregar a imagem de novo mais alguns detalhes, eu queria que invés de ter que baixar a imagem de novo, ou seja eu queria passar a imagem da imageview já carregada para outra imageview.
A GridView
   lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                //String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();

                String pid = productsList.get(position).getPid();

                  ImageView iv = (ImageView) view.findViewById(R.id.flag);
                  Bitmap bitmap = ((BitmapDrawable)iv.getDrawable()).getBitmap();

                        DetailFragment f = new DetailFragment();
                        Bundle args = new Bundle();

                        args.putParcelable("SEU_BITMAP", bitmap);

                        f.setArguments(args);

                boolean singlepane = MainActivity.getPane();
                if(singlepane== true){
                    /*
                     * The second fragment not yet loaded.
                     * Load DetailFragment by FragmentTransaction, and pass
                     * data from current fragment to second fragment via bundle.
                     */

                    DetailFragment detailFragment = new DetailFragment();
                    Fragment myListFragment = getFragmentManager().findFragmentByTag("ListFragment");

                    Bundle bundle = new Bundle();
                    bundle.putString("TAG_PID",pid);
                    detailFragment.setArguments(bundle);

                    FragmentTransaction fragmentTransaction =
                            getActivity().getFragmentManager().beginTransaction();

                    fragmentTransaction.setCustomAnimations(
                            R.anim.fadein, R.anim.fadeout, R.anim.fadein, R.anim.fadeout);

                    //This could use some improvement, but it works, hide current fragment, show new one
                    fragmentTransaction.hide(myListFragment);
                    fragmentTransaction.add(R.id.phone_container, detailFragment);
                    //fragmentTransaction.show(myDetailFragment);

                    /*
                     * Add this transaction to the back stack.
                     * This means that the transaction will be remembered after it is
                     * committed, and will reverse its operation when later popped off
                     * the stack.
                     */
                    fragmentTransaction.addToBackStack(null);

                    fragmentTransaction.commit();

A Segunda fragment
getActivity().runOnUiThread(new Runnable() {
                                public void run() {

                                    //creating the variables
                                    String description;
                                    String name;
                                    String tags;
                                    String downloads;
                                    String created;
                                    try {
                                        //filling the variables with json content
                                        url = (product.getString(TAG_URL));
                                        //description = (product.getString(TAG_DESCRIPTION));
                                        name = (product.getString(TAG_NAME));
                                        tags = (product.getString(TAG_TAGS));
                                        downloads = (product.getString(TAG_DOWNLOADS));
                                        created = (product.getString(TAG_CREATED));

                                        // Getting the tags in a gridview
                                        stringArray = tags.split(",");

                                        for (int i = 0; i < stringArray.length; i++)
                                            stringArray[i] = stringArray[i].trim();

                                        mylistview = (ExpandableHeightGridView) getActivity().findViewById(R.id.listViewTags);

                                        ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(getActivity(),
                                                R.layout.tag_gridview_item, R.id.tagbutton,
                                                stringArray);
                                        mylistview.setAdapter(listAdapter);
                                        Bitmap bitmap = getArguments().getParcelable("SEU_BITMAP");

                                        imageView.setImageBitmap(bitmap);

Answer: Você pode recuperar o Bitmap da ImageView e passar por argumento via Arguments da classe Fragment. A classe Bitmap implementa a interface Parcelable, logo é possível passa-lá para um Bundle.
Para recuperar o Bitmap de uma ImageView basta usar:
Bitmap bitmap = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();

Para passar via Intent para um outro Fragment:
SeuFragment f = new SeuFragment();
Bundle args = new Bundle();

args.putParcelable("SEU_BITMAP", bitmap);

f.setArguments(args);

Para recuperar no SeuFragment:
Bitmap bitmap = getArguments().getParcelable("SEU_BITMAP");

E para setar o Bitmap ao seu ImageView:
ImageView imageView = ...;

imageView.setImageBitmap(bitmap);

Comment: Acontece isso The method putExtra(String, Bitmap) is undefined for the type Bundle
Comment: Engano meu, o método correto é `putParcelable`, corrigido na resposta.
Comment: Ta passando uma image nula, não exibe nada.
Comment: Poderia incluir na pergunta como ficou o código?
Comment: Coloquei uma parte.
Comment: @AlissonHirle, pelo que vi do código você instancia o `DetailFragment` duas vezes, uma com a variável `f`, que possui o Bitmap e outra com a variável `detailFragment` que não tem o `Bitmap` e ai acaba apenas usando o `detailFragment` para fazer o `replace`.
Comment: Funcionou, obrigado.


Symmetric chain decomposition of cartesian product

Question:
Let $A,B$ be finite posets. Define '$\leq$' for the cartesian product
  $A\times B$ as $(a,b) \leq (a',b') \Leftrightarrow a \leq a' \wedge  b
  \leq b' \forall a \in A, b \in B $.
Show that there is a symmetric chain decomposition (partition into
  symmetric chains) for $A\times B$ if there is any for $A$ and $B$.

I played around with some examples, but didn't find any beginning for a proof. Could you please help me to go on?
Answer: Do this in a few steps:
(1) Take the assumed symmetric chain decompositions of A and B, say A_1, A_2, . . . , A_s for
A and B_1, B_2, . . . , B_t for B and create the s x t chain products A_i x B_j ;
(2) Argue that each of the chain products is a "symmetric" and "saturated" subposet of A x B;
(3) Prove that a product of two chains has a symmetric chain decomposition;
(4) Argue that the union of these SCD's provides an SCD of A x B.


How to add class to teaser P?

Question: In Drupal 8, how can I add a class to teaser p html tag. I want to style the paragraph in teaser only, not when whole content is shown.
Answer: We can style that with simple css,
.node--view-mode-teaser .node__content p {
  /* write you style */
}

I think, you don't need to add separate class in P tag for that. and it would also affect only the teaser mode content :)
Comment: This answer is good, assuming he doesn't need to add a specific class name. Ex: [Boostrap](http://getbootstrap.com/) or [Foundation](http://foundation.zurb.com/) class names.
Answer: Assuming you're talking about the default front page teasers:
Edit the Frontpage view, and Instead of Show: Teaser, click on teaser and change it Show: Fields
Then you basically create your own custom teaser.
Add Fields: title, body (summary or trimmed), post date, comments link, etc...

Then click on Style Settings and the classes to your body (re-using pic from another answer)

How to add class to teaser P?


Variable name in dot notation in Swift

Question: I want to use variable names in dot notation in Swift.
I'm wrestling with trying to make sense of JSON in Swift, and having a really hard time doing things that are so easy in JS (like cycling through objects, etc).
I have variables of custom types:
var questionConfiguration: QuestionConfiguration
var priorityConfiguration: PriorityConfiguration

Each of these types has an attribute, displayOrder, I want to access this dynamically. I have tried various things, including the following (i is a variable of type Int):
var configs = [self.questionConfiguration, self.priorityConfiguration]
print([configs[i]].displayOrder)

var configs = ["questionConfiguration", "priorityConfiguration"]
print([configs[i]].displayOrder)

How can I achieve this?
EDIT:
struct QuestionConfiguration: Codable {
    var displayOrder: Int
}

struct PriorityConfiguration: Codable {
    var displayOrder: Int
}

Comment: Can you add the declarations of `QuestionConfiguration` and/or `PriorityConfiguration` to your sample code?  The extra brackets around `configs[I]` look wrong.
Comment: @ScottThompson, sure, I've edited the post. There are a couple more variables in each but that wouldn't affect the MWE. No other code (just `import Foundation`).
Answer: You can create a protocol for same property name then you can access it easily
protocol SameProp {
    var displayOrder: Int {get set}
}

class QuestionConfiguration : SameProp {
     var displayOrder : Int = 4
}

class PriorityConfiguration : SameProp {
     var displayOrder : Int = 6
 }

var questionConfiguration: QuestionConfiguration = QuestionConfiguration()
var priorityConfiguration: PriorityConfiguration = PriorityConfiguration()

var configs = [questionConfiguration, priorityConfiguration] as [SameProp]
for elements in configs{
    print(elements.displayOrder) // will print 4 and 6
}

Answer: Swift is very particular about data types and I suspect you are experiencing challenges because of it.
When you do this:
var configs = [self.questionConfiguration, self.priorityConfiguration]
In Swift, all the elements in an array have to have the same type. You've not given Swift any hints about what types this array should contain so the compiler has to infer a type. QuestionConfiguration and PriorityConfiguration are two different types. So the compiler is likely to infer that configs is of type [Any] also called Array<Any>.
Then you try something like this:
configs[i].displayOrder (not sure why your code has the extra brackets)
But configs[i] is inferred to be of type Any and that type doesn't have a displayOrder property so the compiler complains.
You need to tell the compiler that these types share some properties.  One way to do that would be to add a protocol that describes what they share:
protocol DisplayOrderable {
  var displayOrder: Int { get }
}

struct QuestionConfiguration: DisplayOrderable, Codable {
    var displayOrder: Int
}

struct PriorityConfiguration: DisplayOrderable, Codable {
    var displayOrder: Int
}

then you could use
var configs: [any DisplayOrderable] = [self.questionConfiguration, self.priorityConfiguration]

And configs[i].displayOrder should work.

Variable name in dot notation in Swift


How to Remove and create a input field with its parent Elements if Select tag change its value

Question: I have a table with with four fileds as shown in figure
Semester | Exam Status | GPA | Fee Status

My question is that: When I change the value in Exam_Status the Select tag-> is not cleared then G.P.A field can be removed on this, and when I select Cleared it can show me G.P.A field.

HTML code which generate folloing piture output is following

           Semester
           Cleared/Not Cleaerd
           G.P.A
           Fee Status

           1st Semester

               <select name="fexam_status" id="waqas">
                   <option selected="selected">Select Here</option>
                   <option value="Cleared">Cleared</option>
                   <option value="Not Cleared">Not Cleared</option>
               </select>

                     <input class="spin-dec" type="text" name="fgpa" value="3.00" min="1.00" max="4.00" />

        <select name="ffee_status">
                                <option value="Cleared">Cleared</option>
                                <option value="Not Cleared">Not Cleared</option>
                                </select>

                                2nd Semester

                                <select name="sexam_status">
                                <option selected="selected" value="Cleared">Cleared</option>
                                <option value="Not Cleared">Not Cleared</option>
                                </select>

                                <input class="spin-dec" type="text" name="sgpa" value="3.00" min="1.00" max="4.00" />

                                <select name="sfee_status">
                                <option selected="selected" value="Cleared">Cleared</option>
                                <option value="Not Cleared">Not Cleared</option>
                                </select>

                                3rd Semester

                                <select name="texam_status">
                                <option selected="selected" value="Cleared">Cleared</option>
                                <option value="Not Cleared">Not Cleared</option>
                                </select>

                                <input class="spin-dec" type="text" name="tgpa" value="3.00" min="1.00" max="4.00" />

and similarly when i select Fee_Status-> not cleared it can show me a input tag insteat of SELECT TAG in FEE STATUS
Comment: Use the select boxe's `onchange` event for example: `...` as you can see i pass the current select tag object reference to the function `showHideGPA()` so that the function will be able to determine which select box was changed and traverse the dom to change the appropriate table cell.  Also of course you could use the select box reference to check its value and act accordingly.
Answer: Here's a quick solution:
http://jsfiddle.net/y45ZF/2/
It currently only works for the Cleared/Not Cleared drop downs, not for the Fee drop downs, but you get the point. The only change to your HTML code was that I added the "examStatus" class to the select elements to be able to treat them all in a unified way.


To add shareable link on apps without login func

Question: I have a project to make English learning apps.
There is four layer of users; headquarters, admins, classes and students. For better UX, I want to add shareable links to students my page. So no need for login func. to students. Students can use app without login.
Gem called forward is similar to this func. Is there another way to implement this func.?
Gem called forward is the best solution...?
https://rubygems.org/gems/forward
Comment: Forward isn't what you're looking for - it merely exposes localhost
Comment: Oh I was thinking it too difficult. Thank you!
Answer: Rails views require no login by default. To get a link that doesn't require users to log in you simply do not add a feature that requires login. You can then in the view check if there is a user signed in and add extra buttons for admin features.
Comment: Oh I was thinking it too difficult. Thank you!


Is there any difference between CIDR & VLSM?

Question: As I understand it, the terms Classless Inter-Domain Routing (CIDR) and Variable-Length Subnet Masking (VLSM) effectively refer to the same thing.  Is there any noteworthy difference between the proper definitions of these terms?  What is the history or relation between the two?
Answer: read this How does IPv4 Subnetting Work?
I believe it is explain in one of the answers there.
Comment: yes indeed, it is there for certain, hopefully that sets you straight.
Comment: Thanks for the link, but could you actually include the appropriate content in your answer?


Erro BABEL_PARSE_ERROR utilizando array no ES6

Question: Olá!
Sou novo utilizando ES6, fiz a instalação do Babel, portanto ao utilizar array o Bundle acusa BABEL_PARSE_ERROR. Aparece assim:
SyntaxError: C:\xampp\htdocs\ES6\main.js: Unexpected token (3:20)
O código que estou utilizando é o seguinte:
class todoList{
    constructor(){
        this.todos[];
    }

    addTodo(){
        this.todos.push("Novo todo");
        console.log(this.todos);
    }

}

const MinhaLista = new todoList();

document.getElementById('novotodo').onclick = function(){
    MinhaLista.addTodo();
}

O erro está justamente no array que fica dentro do constructor:
constructor(){
        this.todos[];
    }
Alguém sabe me dizer se há alguma atualização que tenha modificado isso, ou se estou fazendo algo errado?
Answer: Toda a atribuição de valores às variáveis no Javascript é feita utilizando um sinal de igualdade. Sejam elas strings, inteiros... ou arrays.
No código em questão faltou apenas o sinal mesmo.
constructor() {
   this.todos = [];
}

Comment: Realmente, estava faltando o sinal de igual entre todos e []. Obrigado! Falta de atenção minha xD


How do I insert HTML just before the body closing tag?

Question: I am looking for the best way to insert arbitrary HTML content into a page before the closing body tag, similar to the way drupal_add_js() adds JavaScript to the bottom of a page.
I am coming from a Wordpress background, and in Wordpress this could be accomplished by using the wp_footer() hook.
I have looked into using hook_page_alter(), but I was wondering if this was the correct way to do this or if there is a better way of accomplishing this task.
Comment: Similar questions like this one pops up every now and then, and I always wonder _why_, is it necessary to "insert HTML just before the body tag". It seems to me like you're approaching whatever you are doing in the wrong way?
Comment: I can't speak for why others want to do it, but in my case I am adding Underscore JS templates to the page for blocks that require them. However, multiple blocks may utilize one template so I wanted to add all templates to the bottom of the page so that I could easily see if they had been loaded or not. For me it is basically an aesthetics / convenience thing.
Comment: Sorry if I'm being slow, but that doesn't make sense to me? With the cache/aggregation/etc benefits of [#attached](http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/7#attached), that can be used on more than forms, I still don't understand the why.
Comment: I was not aware of the versatility of #attached, so thank you for introducing it to me. However in my case I am writing the contents of those template files to the page (not just linking to the files), so correct me if I am wrong but I don't think the cache/aggregation benefits of #attached matter in this case because the actual page caching will take care of it.
Answer: The equivalent of hook_footer() that was used in Drupal 6 is to implement hook_page_build(), and alter the content of $page['page_bottom'], using code similar to the following one:
function mymodule_page_build(&$page) {
  $page['page_bottom']['devel'] = array(
    '#weight' => 25,
    '#markup' => '
' . devel_query_table() . '
',
  );
}

The content of $page['page_bottom'] is output from html.tpl.php, using the following code:
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

The value of $page_bottom is initialized from template_process_html() using the following code:
  // Render page_top and page_bottom into top level variables.
  $variables['page_top'] = drupal_render($variables['page']['page_top']);
  $variables['page_bottom'] = drupal_render($variables['page']['page_bottom']);
  // Place the rendered HTML for the page body into a top level variable.
  $variables['page'] = $variables['page']['#children'];
  $variables['page_bottom'] .= drupal_get_js('footer');

The difference between hook_page_alter() and hook_page_build() is that hook_page_alter() is executed after hook_page_build() and should be used to alter, or remove content added by another module, while hook_page_build() should be used to add new content to the page.
Comment: Thank you for going above and beyond with this answer. This is very helpful.


Mineração de texto com R (stringr)

Question: Tenho um string de lenght 15 e quero remover os primeiros 70 charac. e os últimos 200 charac. de cada um.
Tentei o seguinte código para remover os começos e não deu certo:
 texto2009a <- texto2009 %>% map(str_sub(., 1, 72) <- " ")

Comment: Bem-vinda ao StackOverflow em Português! Infelizmente, esta pergunta não pode ser reproduzida por quem for tentar respondê-la. Por favor, [dê uma olhada neste link](https://pt.meta.stackoverflow.com/questions/824/como-criar-um-exemplo-m%c3%adnimo-reproduz%c3%advel-em-r) e veja como fazer uma pergunta reproduzível em R. Assim, as pessoas que desejarem te ajudar conseguirão fazer isto da melhor maneira possível.
Comment: 1) O que é que acontece quando o texto tem menos de 70 caracteres? 2) E menos de 200? 3) E, já agora, menos de 70 + 200?
Answer: Exemplo fictício, que talvez possa ser reproduzido para o seu caso:
x<-c('Bem-vinda ao Stack Overflow em Português')

library(stringr)

str_sub(x, 2, -10) # as aspas do texto também contam como strings. Por isso, adicione uma unidade a mais
#[1] "em-vinda ao Stack Overflow em "

Onde, 2 e -10 são, respectivamente, as quantidades de caracteres iniciais e finais que deseja remover.
Answer: A partir da resposta do @Giovani, escrevi uma pequena função para resolver o problema da diferença entre o que str_sub faz e o que a pergunta pede.
Da página help("str_sub"), secção Details:

Details
Substrings are inclusive - they include the characters at both start
  and end positions. str_sub(string, 1, -1) will return the complete
  substring, from the first character to the last.

Ora a pergunta pede (editado por mim)

remover os primeiros m caracteres e os últimos n caracteres

É portanto preciso começar em m + 1 e no fim será n - 1.
library(stringr)

str_sub_als <- function(s, primeiros = 70, ultimos = -200){
    str_sub(s, primeiros + 1, ultimos - 1)
}

x <- c("1234567890", "abcdefghijklmnopqrstuvwxyz")

str_sub(x, 3, -4)
#[1] "34567"                 "cdefghijklmnopqrstuvw"

str_sub_als(x, 3, -4)
#[1] "456"                 "defghijklmnopqrstuv"

Mineração de texto com R (stringr)


How can i show and interact with points of interest (pois) on Here Maps on an Android application?

Question: I'm creating an application on Android in JAVA which is uses Here Maps.
What I'm trying to do is to add pois by categories when zooming in and get coordinates when clicking on one of them.
I tried to create a custom map style using Map Style Editor to add it in the app via loadScene method, but I can't understand how that ΥΑΜL thing works.
Is this the right way to do it?
What other choices do I have?
Comment: Please provide enough code so others can better understand or reproduce the problem.
Comment: Which edition are you using? For Explore / Navigate you can pick the embedded POIs that are shown by default on any map. Of course, you can also add your own POIs by using MapMarker class.
Comment: @Datasun i'm using the lite version but i'm interesting in what you say. could you give me a link or generally further information?
Comment: @Tomjs2400, the Lite Edition does not allow to pick the default POIs, but with Explore/Navigate, you can see here how it can be done: https://developer.here.com/documentation/android-sdk-navigate/dev_guide/topics/map-items.html#pick-embedded-pois
Answer: Map Styling is one the key factor to make the map more  interactive and meaningful. Styling varies from customer to customer. Keeping all these points in mind ,we have   made the architecture in such a way that the customer can give his own
Styling configuration file and that could be loaded on run time. The most flexible solution to customize the map is to create your own map styles using a configuration file written in the YAML markup format. YAML is a digestible data serialization language that is often utilized to create configuration files and works in concurrence with any programming language.
Currently we are providing two options for custom Styling.
1>Create and Load Custom Map Styles.
The most flexible solution to customize the map is to create your own map styles using a configuration file written in the YAML markup format. Which is similar to JSON format.Such files can be generated with a WYSIWYG map style editor provided by HERE. For login, please use your HERE credentials (access_key_id / access_key_secret).
https://enterprise.here.com/map-style-editor/#12.528/52.5309/13.3848
2>Load Custom Raster Layers.
Another alternative to customize the map's look is to add your own raster tile service on top of the HERE map styles. This can be your own server where you host tiles that you want to show as an overlay on top of selected areas of the world - or a public tile server such as OpenStreetMap.
For more details and examples please refer below link.
https://developer.here.com/documentation/android-sdk-lite/126.96.36.199/dev_guide/topics/custom-map-styles-lite.html


Como decodificar entidades html (entity)?

Question: Tenho uma string que me retorna do banco no seguinte formato:

Recebido por estagiários do projeto Memória

Gostaria de converte-la para o formato sem as marcações e conversões das acentuações, ficando desta forma:

Recebido por estagiários do projeto Memória

Como eu devo fazer?
Comment: **Relacionado:** [Codificador e Decodificador de caracteres especiais em HTML](http://pt.stackoverflow.com/q/91774/3635) e [Como resolver problema de busca com palavras acentuadas](http://pt.stackoverflow.com/q/57315/3635)
Answer: Para remover entities da string:
Basta usar a função html_entity_decode
$dec = html_entity_decode( 'Recebido por estagiários do projeto Memória' );

Se precisar especificar um charset, use o terceiro parâmetro:
html_entity_decode( 'estagiários', ENT_QUOTES, 'UTF-8' );

Veja funcionando no IDEONE.
Mais detalhes no manual:

http://php.net/manual/pt_BR/function.html-entity-decode.php

Para remover tags da string:
Você tem a opção de remover as tags usando strip_tags
$dec = strip_tags( 'do projeto' );

Veja funcionando no IDEONE.
Mais detalhes no manual:

http://php.net/manual/pt_BR/function.strip-tags.php
Comment: Muito obrigado deu certo.
Comment: Ótimo exemplo! +1


Monitoring number of request going through a port in linux servers

Question: Im trying to set up a monitoring service to get the results of request going through a specific port. What i did was netstat -anp | grep :8000 | grep ESTABLISHED | wc -l in the command line. however i would like to display the results on a dashboard similar to grafana but i cant seem to find any solutions online in doing that
Answer: Grafana support lot of data sources https://grafana.com/docs/grafana/latest/datasources/ and there are lot of agents to collect data as well. In our company we use InfluxDB and telegraf (https://docs.influxdata.com/telegraf/v1.17/introduction/installation/) as agent


Irreducibility of polynomial P(X) = X

Question: I have the following exercise:
Let $R$ be the integral domain of all polynomials $P(X)$ with real coefficients whose constant term is a rational.
Is the poly $P(X) = X$ irreducible in $R$?
My question is: Is this similar to showing that $P(X+c)$ is irreducible if and only if $P(X)$ is irreducible. I do not understand the role on the constant term being rational.
Comment: The only units in $\mathbb R[x]$ are the non-zero constants.  Not the degree $1$ polynomials.  Can't invert them.
Comment: No. You are forgetting that the units may differ. $2X \in \mathbb{Q}[X]$ is irreducible, but it is reducible in the subring $\mathbb{Z}[X]$. Thus, the statement "If a polynomial is irreducible in $K[X]$, then it is irreducible in all subrings it contains" is wrong. (All my comments refer to comments by Jean-Claude which have been deleted. Sorry if this is confusing.)
Comment: But isn't a poly of degree 1 a unit. Hence a unit is not irreducible?
Comment: @Jean-ClaudeArbaut Be careful. The ambient ring is important. In $K[T^2,T^3]$ (a subring of $K[T]$), the polynomial $T^3$ is irreducible. Also, it should not be omitted that irreducible elements are required to be non-zero and non-invertible. This is why we have to determine the units as well.
Comment: @Jean-ClaudeArbaut Also, the correct Wikipedia article here is this one: https://en.wikipedia.org/wiki/Irreducible_element
Comment: It does not disprove the statement. But (as you can also see from my answer) stating that polynomials of degree $1$ are irreducible is **not enough**, since the ring in question is not the full polynomial ring - it is a ring of polynomials. My example just shows by analogy that we need to distinguish these cases properly.
Comment: @MartinBrandenburg Ah, yes, units. I did miss something important. Thanks for the clarification.
Answer: Yes. First, observe $\mathbb{R}[X]^{\times} = \mathbb{R}^{\times}$ and $R^{\times} = \mathbb{Q}^{\times}$. Notice that $X$ is a non-zero non-unit in $R$. If $X = A \cdot B$ with $A,B \in R$, this equation also holds in $\mathbb{R}[X]$. Since $X$ is irreducible there, we get $A \in \mathbb{R}^{\times}$ or  $B \in \mathbb{R}^{\times}$. The claim now follows  from $\mathbb{R}^{\times} \cap R = \mathbb{Q}^{\times} = R^{\times}$.
Comment: I am sure that you will find the proof of $K[X]^{\times} = K^{\times}$ (where $K$ is a field, or just an integral domain) in your algebra textbook and via a simple google search ("units of polynomial ring") and of course also here on MSE.
Comment: How can I prove that $\mathbb{R}[X]^{\times} = \mathbb{R}^{\times}$?

Irreducibility of polynomial P(X) = X


Qual a melhor forma de começar a desenvolver uma app mobile

Question: Boa tarde,
Gostava de saber qual a melhor linguagem para desenvolver uma aplicação para mobile e qual plataforma para começar a desenvolver.
Obrigado desde já.
Answer: Antes de tudo, depende muito do que você procura, não existe a melhor linguagem, e sim a que se adequa mais a sua necessidade atual. Se quiser desenvolver para multi-plataformas (Android e iPhone ao mesmo tempo), você conta com as seguinte opções:

Ionic Framework (JavaScript)
Phonegap ou Apache Cordova (JavaScript)
Unity (C#)
React Native (JavaScript)
Xamarin (C#)
Flutter (Dart)

Leve em consideração que as plataformas citadas acima muitas vezes transpilam o código escrito para a linguagem nativa da plataforma, exemplo do React Native no Android(que vai de JSX para Java), o que muitas vezes ocasiona num código nativo "sujo".
Se preferir programar "nativamente" para Android:

Java
Kotlin

(Essas duas opções de linguagens são fortemente tipadas, se forem do seu interesse, tudo bem, caso não, alternativa anterior)
"Ah mas eu posso passar de Kotlin para JavaScript e transpilar para outras liguagens."
- Ok, mas ainda sim é focada na Máquina Virtual Java.
E por fim, para dispositivos iOS, você conta com:

Swift
Objective-C
Cocoa Touch


O que é e como funciona o Pós-Processamento de CSS?

Question: O que seria um pós-processamento de CSS? Eu já tinha ouvido falar em CSS pré-processado, como o Gulp faz quando compila um SASS em CSS. Mas recentemente escutei o termo CSS pós-processado e fiquei sem entender direito o que é e como ele funciona.
O que seria esse prática de pós-processar o CSS, quais vantagens ela traz para o CSS? Melhora a performance ou a manutenção do código?
Como de fato funciona esse pós-processamento, o que ele faz com o meu .css?
Comment: @hugocsl pode ser gerados outputs diferentes, muitas ferramentas possuem um build de produção e outro de desenvolvimento
Comment: Olá, meu caro! Talvez seja interessante ler isso daqui: https://postcss.org/
Comment: Parece um pré-processador sem transpilador, tem a mesma ideia, exceto transpilar de SCSS, SASS, etc para CSS
Comment: @Costamilam parece, mas é bem mais que isso, ele retira um monte de coisas tipo comentários, classes que não são usadas, classes repetidas, propriedades repetidas, as vezes dependendo do que vc configurar ele faz o short-hand de tudo, e pode até mudar nomos grandes tipo, `header-btn-btn-active{}` para `hba{}`. Lógico que só se usa quando sobre o projeto para produção, não é usado em desenvolvimento pq mais atrapalharia do que ajudaria
Comment: @hugocsl isso também poderia ser feito durante pré-processamento, não?
Comment: @Costamilam alguma parte sim, porém normalmente o pré apenas converte o sass/less/scss em css, acredito que a maioria das ferramentas de pré tenham algumas limitações. E o pós processamento é só na parte final do projeto mesmo, imagina como seria ruim ficar trabalhando em um CSS minificado e com nome de classe diferente do que está no seus SCSS só pq vc fez algo errado. Tipo imagina que vc errou algo no SCSS e foi no CSS conferir o output e está tudo compilado/minifica. Ia mais te atrapalhar do que ajudar
Comment: @Costamilam pode até ser sim, essa não é muito minha área, até por isso que deixei a pergunta rss, e tb nuna vi falando de compilado pré css que faça esses tratametos, mas pode ser que exista tb, mas eu desconheço...
Answer: Um pós-processador de CSS nada mais é que um programa para ajudar no desenvolvimento de códigos CSS.
Igual o SASS?
Não.
pré-processamento vs pós-processamento
Diferente do pré-processamento de códigos (Sass, Lass e Stylus) que, quando processado, seu código é interpretado e é transformado em CSS, o pós-processamento pode atuar diretamente no código CSS para melhorá-lo de alguma forma.
No pré-processamento você instrui a construção do código css. Aqui você tem um controle grande do que será produzido.
No pós-processamento você manda analisar o código e o interpretador altera seguindo suas próprias regras. Você não tem muito controle, até porque o pós-processamento serve para te proteger de si mesmo como veremos a seguir...

[...] quais vantagens ela traz para o CSS? Melhora a performance ou a manutenção do código?
Depende do pós-processador. O cssnano por exemplo, apenas compila o código CSS, apagando comentários e deletando coisas inúteis. Ou seja, pode melhorar a performance.
Um pós-processador que tem o intuito de ajudar na manutenção e na produção do código é o stylelint...

"que ajuda a evitar erros e impor convenções em seus estilos"

Existe também o autoprefixer, o mais famoso, que ajuda no desenvolvimento, gerando os códigos para navegadores distintos e suas respectivas versões. Exemplo:
entrada.css
body {
    display: flex;
}

saida.css
body {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
}


How can I make my email code work PHP?

Question: Hey this code is suppose to add an error message when an input was not typed on the email form and its suppose to remove the error message when you finally input the code. I have 2 of them working with the following code:
//Generate a unique code
function getUniqueCode($length = "")
{
$code = md5(uniqid(rand(), true));
if ($length != "") return substr($code, 0, $length);
else return $code;
}

//Generate an activation key
function generateActivationToken($gen = null)
{
do
{
    $gen = md5(uniqid(mt_rand(), false));
}
while(validateActivationToken($gen));
return $gen;
}

and this code:
//Checks if an email is valid
function isValidEmail($email)
{
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    return true;
}
else {
    return false;
}
}

I have made my own code which puts the error messages when there are no inputs on the email form but when I input something right on the email form it does not take the error messages out of the error message box. Here is the code:
//Checks if a name is valid
function isValidName($name)
{
if (filter_var($name, MAIL_NAME_ERROR)) {
    return true;
}
else {
    return false;
}
}

So to summarize all 5 are working when there is no input like this:

Please enter your full name
Please enter a valid email address
Please enter your telephone number
Please enter your password
Failed security question

But only my security and email are working when I input my email address and security code like this:

Please enter your full name
Please enter your telephone number
Please enter your password

The name, telephone and password are not working right they only work by showing the code but they do not remove the code when I input the right information.
How can I fix my code so that all 3 will go away 1 by 1?
Comment: `MAIL_NAME_ERROR` ? That's not an existing filter name. All valid filter names can be found here: http://www.php.net/manual/en/filter.filters.validate.php
Answer: To make your own callback you can't just pass the constant MAIL_NAME_ERROR. If you want to pass your own function you have to do something like:
function mail_name_error(){
  //do your thing here
}
function isValidName($name){
  if(filter_var($name, FILTER_CALLBACK, array('options' => 'mail_name_error'))){
    return true;
  }
  else {
    return false;
  }
}

See the options section at http://php.net/manual/en/function.filter-var.php .
Comment: Its not working you can check out the page at http://blanky-store.net/access/new_reg_e.php
Comment: Maybe you should just download the PHPglue Library at http://www.PHPglue.com . Review the Documentation and Click the `Downloads` tab. It automatically tests to see if your field is empty, by default. Actually, it will generate your HTML and handle your Sticky Form, both Client and Server Side. You will have to make an email regular expression though. Here's one for you: `'/^.{1,62}@.{1,62}\.[a-zA-Z]{2,4}$/'`. It should go in the `errorDiv()` method. You may never have to write complex code to handle your Stick Forms again. Of course, I wrote it!

How can I make my email code work PHP?


Probability of a girl given 2 boys

Question: I recently had a test on Probability Distributions and got this question wrong. Some help would be appreciated. If I recall correctly, the question was :
In a family of 4 children, the probability of a boy and girl is equal.
Then what is the probability of a girl given there are already 2 boys.
I attempted to use binomial distribution with X ~ Bin(2, 0.5) but this wasn't right; I'm not sure what else to do.
Comment: This is, I think, going to depend on what you mean by "already". Do you mean "given that the first 2 kids were boys, what is the probability that one of the next two kids is a girl?" One exactly or one or more? Or only the third child? Or do you mean "given that there are at least two boys in a family, what is the probability that one of the other two is a girl?" Or something else? Once you define the terms, you can do as @LaksanNathan and draw  a tree.
Comment: I don't know how these questions are usually posed, but to me, the answer is just 50%.  It doesn't matter how many boys came before.  But I don't know what knowledge is being tested here.
Comment: Have a look at the monty hall problem. You can then apply the same logic to get the correct answer (and yes that might be counterintuitive).
Comment: @SalMangiafico It does matter. You can basically just draw a tree of every possible combination and then remove possibilities given "there are already 2 boys".
Comment: Okay.  I guess I don't understand the question being posed.
Answer: There are at least 4 possible answers, dependent on how to interpret this question:

If the probability for a girl is determined by the fact that there are 2 boys and 2 girls in this family of 4 children. Then the probability for the 3rd child to be a girl, given the first 2 are boys, is 100%.
If the probability for a child being a girl is interpreted as a constant 50%, then the probability for the 3rd child being a girl is 50% no matter the gender of the first 2 children.
The same as interpretation 2, but here you want to determine the probability that there is at least 1 girl in the spot of child 3 and 4. This probability is 1-0.5x0.5 = 0.75!
If you interpret the question in a way that you have 2^4=16 possible combinations of the 4 childrens gender and out of these you only look at cases with boys >= 2, then you see that there are only 11 possibilities of which only 1 contains 0 girls.   Pr(≥1∣≥2)= 10/11
Comment: Possibly none of these is the intended interpretation, though.  The question seems to be an effort to test a pupil on conditional probabilities and, as such, reads like (a poorly phrased) request to compute $\Pr(G \ge 1\mid B\ge 2)$ where $B$ has a Binomial$(4,1/2)$ distribution and $G=4-B.$ *That* probability is $10/11.$
Comment: @whuber I think you're correct. The question was phrased poorly and I wasn't able to understand exactly what was wanted from me, but knowing it was conditional probability I should have been able to deduce the question. However, I still don't think this is the correct answer since it was a MCQ and I'm pretty sure there wasn't an option so high
Comment: About the only way to figure out the intended question, then, would be to survey the options that were provided and determine which of them are consistent with some reasonable interpretation.  Right now we're all just guessing.
Comment: I am just ashamed that I forgot the most likely interpretation of all.. Yes, 10/11 is correct in this case! I just calculated it myself.
Comment: I know the question is closed, but maybe for sake of completeness you might want to edit your answer to add that option too.
Comment: @HuyPham: Good idea, I just did!
Answer: Assuming the samples are independent (i.e. the genders of previous children don't affect the probabilities of the following) and p(G)=p(G=F)+p(G=M) (i.e. only boys and girls as classes), you have four possible realizations:
FF|FM|MF|MM where M=male, F=female
If you're trying to find the probability of at least one girl, you need to sum probabilities for the first three, but we can equivalently do 1-p(MM).
p(MM) is Binom(2, 0.5) or equivalently Bernoulli(0.5) + Bernoulli(0.5), which is 0.5*0.5 == 0.25.
So, 1-that gives you the probability of at least one girl of 0.75.
Both being girls is given by the same Binom(2, 0.5) since the gender probabilities are equal, which we already know is 0.25.

Probability of a girl given 2 boys


Distribution of digits across all factorials

Question: Show that the distribution of zeroes across all digits of all n! for $n\in \mathbb{N}$ converges to $ \frac{1}{6} $ and hence, $\frac{5}{54}$ for all other digits 1 through 9.
In other words, let's say we take the factorial of 1,2,3 and 4. We get the digits 1,2,2,4 and 6. In this case the probability of 2 would be $\frac{2}{5}$. We can keep doing this all the way to infinity.
I wrote a python script and checked from 0 to 10000, and all probabilities converge to 0.09259259259.. = $\frac{5}{54}$ except zero, which converges to 0.16666... = $\frac{1}{6}$.
Can you prove mathematically why this is the case?
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be put on hold. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: I have edited the question for further clarification.
Comment: have you thought anout ways to get a 0 ?
Comment: I wrote a python code too, but the ratios are different. 0 converges to rather large ratio.
Answer: I doubt this is true
Using Stirling's approximation, the number of decimal digits in $n!$ is about $\frac1{\log_e(10)}\left(n \log_{e}(n) -n +\tfrac12 \log_{e}\left(n \right)+ \tfrac12 \log_e(2\pi)\right)$
while the number of trailing $0$s on the right hand side of $n!$ is close to $\frac n4-1$
suggesting that the proportion of digits of $n!$ which are $0$ might be estimated as being of the order of $$ \frac1{10} + \frac{9}{10} \frac{\frac n4-1}{\frac1{\log_e(10)}\left(n \log_{e}(n) -n +\tfrac12 \log_{e}\left(n \right)+ \tfrac12 \log_e(2\pi)\right)}$$ with some natural variation about this
With $n=10000$ this estimate is about $0.163$, which may help explain your empirical result of $\frac16$
But as $n$ increases further, this estimate tends to $\frac1{10}$, essentially because $n\log_e(n)$ grows faster than $\frac n4$.  For example with $n=10^{10}$ the estimate would be about $0.123$, while for $n=10^{100}$ it would be about $0.102$
Comment: Have you accounted for the fact that the first digit must necessarily not be a zero and there must necessarily be another non zero digit if the number of digits is greater than the total digits minus the number of trailing zeros, or is this insignificant? Also, is there a reason why your error is not written as on value, i.e., 2 * pi * n??
Comment: @matt We are looking at the number of decimal digits of $n!$, which is $\log_{10}(n!)$ rounded up, i.e. $\frac1{\log_e(10)}\log_e(n!)$.  Taking the logarithm of the multiplicative $\sqrt{2\pi n}$ in Stirling's approximation gives the $+\tfrac12 \log_{e}\left(n \right)+ \tfrac12 \log_e(2\pi)$ terms
Comment: @matt Your two known non-zero digits becomes insignificant for large $n$.  You are talking about the difference between $2$ (inevitably non-zero) and $1.8$ (digits non-zero with estimated rate $\frac9{10}$), which you then divide by about the number of digits of $n!$.  So perhaps you could change the $\frac n4-1$ to $\frac n4-\frac{46}{45}$ to take account of this, but it is not material in the context of the other approximations and natural variation


How to "filter" out one specific user in a view?

Question: I've a question regarding some of my blocks which I've made in views (using Drupal 6 and Views 2). One of the users on the site is the sites "manager" and so this user of cause writes a lot of posts, comment on a lot of posts and "likes" a lot of posts.
In some of my blocks I display the most contributing users and this "manager" is almost always on top of the list and I would like to display the most contributing users, but "ignore" this user.
My views are very simple and basic created. For example in one I list the most commenting users right now (that be, the last 24 hours) and I sort according to the comment count.
In this example, how do I "filter" out the one user?
Thanks
Sincere
- Mestika
Answer: In your view filter out the user:

Add relationships: Node revision: User
Label: user
Require this relationship: (checked)
Add filters: User: Name
Relationship: user
Is not one of: manager
Comment: Thank you so very much Jan, it works perfectly.
This is a nice snippet to save and you saved me a bunch of work trying to figure out a solution.

How to “filter” out one specific user in a view?


Does one still need to report p-value & effect size if one has reported the confidence interval (CI)?

Question: I am unclear about the degree of overlap in the information contained by the CI as opposed to that contained in the p-value and effect size of that same statistic/estimate.
I know of course that if a 95% CI does not include the zero value of a particular effect, then it can be inferred that said effect is statistically significant, in the same way that this would be inferred from a p<0.05. And, of course, that CIs can be calculated from p-values, and vice-versa.
But what is unclear to me is:
1) if the CI is reported, is there any need at all to still provide the p-value? In other words, does it give any extra information that the CI does not already give?
2) if I want to describe, say, the difference in means between two groups, does it still make sense to provide a measure of effect size such as Cohen's d if I have already provided the CI of the sample point-estimate?
Reading the paper "Confidence Interval or P-Value?" by du Prel et al. (2009) has left me still in doubt unfortunately, so further reading that addresses my question would be appreciated in an answer - thanks in advance.
I should also mentin that this question follows on from an earlier one to which I never obtained a satisfactory answer, just as searching previous questions on here was not entirely enlightening.
Answer: While information such as differences in means and p-values can often be back-calculated from a confidence interval (especially if it is of the form $\hat{\delta}\pm c_{1-\alpha/2} \text{SE}(\hat{\delta})$) potentially after some transformation), it is not easy for people to do this in their head. So, it is better to do these calculatons for them. Particularly the difference in means should really be provided in my opinion, while it is in many fields expected to also be provided p-values (even if people usually mis-interpret them).
Talking for my specific field, for controlled clinical trials the standard set of information I would always expect is difference in means (or some other point estimate), confidence interval (or something else such as a credible interval) and p-value (especially if it is multiplicity adjusted - multiplicity adjusted confidence intervals are rarely reported and hard to obtain). In addition, I would normally expect to see something like adjusted least-squares means (or some similar measure) for each group with confidence interval or standard error, as well as information on the number of patients in each group. This covers a diverse set of needs: an idea of the effect size, an idea of the uncertainty around it, what people are used to seeing, what you would need to include the trial into a meta-analysis, what you would need to construct a historical prior for a new trial, what you need to get an idea of the variability of the outcome (useful for sample size calculations for new trials) etc.
Answer: I will share what I tell my students: our job in conveying statistical information to our "clients" is to quantify what was observed and to provide some measure of how this evidence can be assessed. I would argue that the sample statistics and effect sizes address the former, and confidence intervals (CI) or $P$-values address the latter.  Thus, I would suggest reporting both the CI and the effect size, such as $d$ or $R^2$. However, reporting both the CI and the $P$-value would be redundant.
Regarding the 2nd query, the size of the CI depends on $n$, and thus can be misleading. That is, you can have two CIs with the same distance from zero and the same $d$.  One CI could be very large and the other very small. Thus, you do provide additional information by reporting the effect size, as well.
Lastly, regarding additional readings, I can't think of any right now. But, there is a lot that shows up in most modern statistics/research-design textbooks (particularly with applied focus, like for social science researchers).


Ajustar lista de produtos no woocommerce, para ficar alinhados corretamente

Question: Minha loja está com o seguinte visual

E eu gostaria de alinhar corretamente os produtos, pois o visual não está legal.
Como conseguiria fazer isso?
Comment: Vc já tem o link da página? Mas já te adianto que o problema é pq cada produto tem um tamanho de texto. Se vc colocar todos os textos com mesmo tamanho não tera problema. Falo do texto verde na descriçaõ do produto, uns tem 2 linhas, outros 4 linhas, se todos tiverem 2 ou se todos tiverem 4 acho que não vai dar problema. Mas para resolver sem o código não da...
Comment: Vc está usando boostrap? Só com a imagem fica difícil te ajudar. A página já está publicada, vc tem o link?
Comment: Estou usando o Tema AccessPress Store do Woocommerce, não estou usando bootstrap @hugocsl , e ainda não está publicada, está em fase de manutenção
Comment: @hugocsl, era isso mesmo o problema, ja foi solucionado, se quiser colocar como resposta eu aceito ela
Comment: Valeu a força Tiago, deixei uma resposta com mais detalhes e um exemplo pra vc testar e ver melhor pq essa quebra acontece. []'s
Answer: Tiago muito provavelmente seu Grid é baseado em Floats por isso ele está quebrando.
Resumindo meio que grosseiramente, quando os elementos não têm a mesma altura (no seu caso quando cada produto tem um tamanho de texto) o encaixe dos elementos uma abaixo do outro não da certo e o layout quebra.
Fiz esse exemplo pra vc entender melhor e ver a quebra e como corrigi-la. No seu caso para corrigir basta colocar a descrição de todos os itens com a mesma quantidade de linhas, obtendo a altura igual para todos.
OBS: Deixei os comentários no código

body {
    width: 100%;
    height: 100%;
    margin: 0;
}
div {
    width: calc(100% / 3);
    float: left;
    height: 50px; /* todos os itens devem ter a mesma altura  */
    background-color: aquamarine;
    box-sizing: border-box;
    border: 1px solid black;
}
div:nth-child(2) {
    height: 55px; /* esse item com a altura diferente faz seu layout quebrar  */
}

height: 50px;

esse tem altura diferente height: 55px;

height: 50px;

height: 50px;

height: 50px;

height: 50px;


FullCalendar: borderColor/backgroundColor not working for month view

Question:

In Fullcalendar,
I have used eventDataTransform to set borderColor & backgroundColor.
For Month view event's borderColor & backgroundColor is not taking effect.
i am expecting to take borderColor/backgroundColor effect for month view.
Current event object:
events = [{
    title: 'Timed Event',
    start: '2020-06-23T16:00:00+00:00',
    borderColor: 'red',
    backgroundColor: 'green'
}]

Please suggest some solution for the issue.
Comment: Please provide enough code so others can better understand or reproduce the problem.
Comment: events = [{
    title: 'Timed Event',
    start: '2020-06-23T16:00:00+00:00',
    borderColor: 'red',
    backgroundColor: 'green'
}]

i am using this event format to set color for event. it is not working for month view.
Comment: setting "display": "block" for event, let us set color for the month view event
Answer: If we use event's display property to "block",
then it sets the backgroundColor and borderColor of the event for all views, including month view.
Example:
events = [{
    title: 'Timed Event',
    start: '2020-06-23T16:00:00+00:00',
    display: 'block',
    borderColor: 'red',
    backgroundColor: 'green'
}]


reference to findViewById is ambiguous

Question: I tell you a few days ago that I could not debug my application, then I reinstalled the android studio and updated the latest version, now that I want to continue with my project in each of the activities where I use "findViewById (R.id.nombre )" the following error appears:
Error: (23, 31) error: reference to findViewById is ambiguous
both method findViewById (int) in Activity and method <T> findViewById (int) in AppCompatActivity match
where T is a type-variable:
T extends View declared in method <T> findViewById (int)

I have already searched here, but my problem is still I hope you can help me, I attach some captures
exception
code
Answer: You're using findViewById (R.id.nombre ). Where nombre is defined in two activities(Activity and AppCompatActivity) with same name. You should assign different name for nombre in each activity.
Comment: This is not correct. `R.id` fields are not defined in `Activity` classes, and even if they were, those would be in completely separate scopes. Furthermore, the conflict is coming from the method, not the argument.

reference to findViewById is ambiguous


Newbie at visualforce

Question: I am newbie at visualforce and i have a few questions. I was able to create a basic visualforce page:
<apex:page standardController="Campaign">
<apex:sectionHeader title="Campaign" subtitle="Campaign Edit"/>
           <apex:form id="theForm">
           <apex:pageBlock title="Campaign" mode="edit">
           <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save"/>
                <apex:commandButton action="{!cancel}" value="Cancel"/>
                <apex:commandButton value="Save & New" action="{!'save & new'}"/>
            </apex:pageBlockButtons>
           <apex:pageBlockSection title="My Content Section" columns="2">
            <apex:inputText value="{!Campaign.name}" id="name"/>
                 <apex:inputfield value="{!Campaign.Campaign_Type__c}">
                    <apex:actionSupport event="onchange" reRender="theForm" />
                 </apex:inputField>
                 <apex:inputtext value="{!Campaign.PPC__c}" rendered="{!Campaign.Campaign_Type__c == 'Campaign Type 1'}" />
                 </apex:pageBlockSection>
       </apex:pageBlock>
    </apex:form>

https://ibb.co/iWSVVS
The field "Campaign name" is a required field how can i add the red bar next to the field?
How can I "combine" several fields together and insert them as a value to the field Campaign name? for example i have a dropdown field "Campaign_Type__c=Type 1" and i also have a text box field "Campaign_textbox1__c=alex" I want to combine them as "Type 1 alex" and set this as a value for the field name  "Campaign name".
Thank you
Answer: For the required just set the attribute to the tag:
<apex:inputText value="{!yourVaue}" id="yourid" required="true" />

Answer: Can you not do a formula field for the Campaign name?
One that concatenates the fields together. So create a formula field called Campaign name, then use my formula below:
Campaign Name = Campaign_Type__c & " " & Campaign_textbox1__c
The reason for the space is that otherwise it'll stick it together like "Type 1Alex"

With your other question, i'd just use HTML formatting to get this. Maybe use a pipe? | - one that's bold and red - but i'm lazy
Answer: Add the attribute required="true" to make it required i.e. red bar next to the field.
Therefore, you can achieve this by
<apex:inputText value="{!Campaign.name}" id="name" required="true"/>

Comment: I followed your ideas. But it did not help.

Newbie at visualforce


Como calcular a soma de um grupo em MDX

Question: Eu preciso criar um Calculation no SQL Server Data Tools.
Imagine que na minha estrutura OLAP Eu tenho as Dimensões Cidade e Revendedor, e uma Fato Vendas. Na dimensão Cidade eu tenho Cidade, Estado e a População, e essa População é uma medida em uma dimensão, tornando a dimensão cidade uma Fato e uma Dimensão ao mesmo tempo.
Eu preciso somar a População nas cidades das quais um revendedor teve vendas. Mas eu não consigo somar apenas a população das cidades com vendas, eu consigo apenas mostrar o total do estado. Lembrando que um vendedor pode vender em varias cidades e em mais de um estado.
Eu filtrei pelo revendedor John e a consulta retornou isso:

STATE  |   CITY            |     POPULATION

CA     |   Los Angeles     |     10.000.000
CA     |   San Francisco   |      1.000.000
CA     |   Sacramento      |      1.000.000
CA     |   San Diego       |      1.000.000
CA     |   Bakersfield     |        500.000

Total                          37.000.000

A soma deveria retornar 13.500.000, mas para mim, a soma retorna 37.000.000, que é a população total da Califórnia.

O calculo que uso atualmente, é
SUM([Measures].[Population])

Eu não tenho conhecimentos avançados em MDX, Eu não consegui montar o calculo ainda apenas isso:
SUM(FILTER([Measures].[Population],[Sales Amount]>0))

ou isso
SUM(NONEMPTY((  [CidadesRadiografia].[Cidade].[Cidade],
                [Measures].[População],
                [RepresentantesRadiografia].[Representante].[Representante] )))

Resumindo, eu preciso retornar apenas a soma da população para as cidades que o revendedor teve vendas, mas atualmente ele mostra o total da população, por exemplo, se eu selecionar o pais e a cidade, retorna a soma do total do pais, e se eu selecionar o estado e a cidade, retorna a soma da população do estado.

Pregunta no StackOverflow
Answer: Agora após ler o livro SQL Server 2008 MDX Step by Step consegui montar um cálculo que está retornando o que eu precisava, ele está com ótima performance no SQL Server Management Studio e no Visual Studio Data Tools, porem no Excel não é muito performático, mas isso não vem ao caso. o cálculo MDX é o seguinte:
CREATE MEMBER CURRENTCUBE.[Measures].[Populacao]

AS SUM(NONEMPTY((Filter([Measures].[População],[Measures].[Valor Total] >0),
   FILTER([CidadesRadiografia].[Cidade].[Cidade],[Measures].[Valor Total] > 0)))),

FORMAT_STRING = "#,##0;-#,##0;0;0",
NON_EMPTY_BEHAVIOR = { [Valor Total] },
VISIBLE = 1;

Aconselho o livro acima para alguem que como eu nunca tinha trabalhado com MDX.

Como calcular a soma de um grupo em MDX


"TypeError: 'int' object is not subscriptable"

Question: Why am i getting this error when trying to remove dupes from a list?

"TypeError: 'int' object is not subscriptable"

trying to remove duplicate valuse from a list
numbers=[5,2,1,7,2,4]
numbers.sort()
i=0
for item in numbers:
    if i==len(numbers)-1:
    break
    elif item[i]==item[i+1]:
    numbers.remove(item)
i+=1

Answer: Actually the problem is in your for loop it is not for removing duplicate numbers. i recommend that you must define a empty list in which you append elements one by one using loop and check if the element is already present in your list then don't append. here is the code:
numbers=[5,2,1,7,2,4]
numbers.sort()
sorted_num=[]
i=0
for i in range(0,len(numbers)-1):
    if numbers[i] in sorted_num:
        continue
    else:
        sorted_num.append(numbers[i])
        i+=1
print (sorted_num)
#     elif item[i]==item[i+1]:
#         numbers.remove(item)
# i+=1

i only edited your piece of code
Comment: interesting approach. Thank you
Answer: use set see more here

numbers=[5,2,1,7,2,4]

list(set(numbers))
[1, 2, 4, 5, 7]

Comment: My problem was from a homework and i don`t think i can use "set". But it is good to know this command exists. thank you.
Answer: Use dictionary:
numbers=[5,2,1,7,2,4,5,5,1]
numbers=list(dict.fromkeys(numbers))
print(numbers)


SAN volumes not showing in new cluster

Question: Some background....
We have
Two hyper-v hosts running server 2012r2 with a number of guests.
Msa1040 SAN with two disk pools
The hosts are a two server cluster
The two hosts connect to the san via iScsi for cluster storage.
We've had an OS fail on the two host servers and one guest (stuck on black screen on boot up). So I've had to reload them.
I've created a 3rd host server to get things up and running.
The san is mapped to svr3 and Svr3 can see the luns via iscsi connector.
I've brought the disks online in disk management.
I'm trying to add the volumes to a failover cluster.
The problem is that I cannot see the contents of either of the storage in the cluster storage folder.
The cluster died when the two hosts failed so I'm starting from scratch
Any ideas on things to check or anything obvious that I've missed?
Thanks
Comment: If you add/create a CSV in FoC does it show you the disk as being available for a CSV?
Comment: When I try to add them, it says no suitable disks are available
Answer: All sorted.
The volume had a persistent registration on it to the old cluster.
R emove that via PowerShell and happy days
C:\PS>Clear-ClusterDiskReservation -Disk 2

SAN volumes not showing in new cluster


My guitar pupil is a pregnant woman. Should she keep playing classical guitar?

Question: What are the consequences for the baby ? Are there any studies that would have noticed positive / negative consequences on the baby of the vibrations a classical guitar induces on the belly and the chest ?
Should the avoid playing dissonant chords ? Playing loud ? Playing notes that would be near the resonance frequency of her belly ? (frequency that should get lower and lower as the belly gets larger)
Comment: My Guitar Wants To Kill Your Mama!   OK, seriously, there is absolutely no risk from the incredibly low energy output of a guitar. Compare with, e.g., the output of the ultrasound monitor used prenatally.  Meanwhile, lots of people swear that playing music calms (or even educates!) the fetus.
Comment: Surely she should *only* play dissonant chords? Got to avoid too much resonance! :)
Comment: Skippy,  I sure hope you get the reference!  :=)
Comment: Check out Weasels Ripped My Flesh.
Comment: I was assuming this question had more to do with technique and a big baby belly getting in the way!  Very interesting to consider dissonance and resonant frequencies in the womb though.  Also, Frank Zappa ftw!
Comment: @carlwitthoft : the pregnant woman is the guitarist :)
Comment: No I don't sorry...
Answer: This is a positive thing. Studies have shown the positive effect music has on unborn babies, see:
Whitwell, Giselle E. "The importance of prenatal sound and music." Journal of Prenatal and Perinatal Psychology and Health 13 (1999): 255-262.
http://intraspec.ca/music.pdf
Answer: In the case of a catastrophic fall from 20 feet in height, A mother's body will protect the unborn child from harm.  The mother might not survive, but the baby likely will.  Given that, I find it impossible to imagine how playing classical guitar could harm the baby.
When my wife was pregnant, she used to sit on my bass amplifier as I was playing, which would make the baby rouse and kick. That baby went on to become an extremely intelligent adult with absolutely no rhythm.  :)
The only possible downside to playing classical guitar while very pregnant is posture difficulties for mom.


Determinant of non-triangular block matrix

Question: We have the following determinant property
$$\det
\begin{bmatrix}
    U & O \\
    V & W
  \end{bmatrix} = \det(U) \cdot \det(W)$$
where $U \in R^{n\times n}$, $V \in R^{m\times n}$, $W \in R^{m\times m}$ and $O \in R^{n\times m}$ (the zero matrix).
Now suppose the zero block appears in the top left corner instead. Does there in that case also exist a rule to calculate the determinant of the matrix more easily?
The matrices I am thinking of here are of the form
$$Z = \begin{bmatrix}
    O & A \\
    A^T & B
  \end{bmatrix}$$
with all matrices conformable. An example would be
$$Z = \begin{bmatrix}
    0 & 0 & 0 & 1 & 1 & 1 \\
    0 & 0 & 1 & -9 & 0 & 1 \\
    0 & 1 & 1 & 0 & 0 & -1 \\
    1 & -9 & 0 & -1 & 2 & 0 \\
    1 & 0 & 0 & 2 & 1 & 0 \\
    1 & 1 & -1 & 0 & 0 & 1
  \end{bmatrix}$$
Comment: @daw Doesn't it have a 2x2 zero block?
Answer: There is no such rule to calculate determinant easy as in the case the zero block is in the top right or bottom left corner.
Here you can see all rules you can apply on block matrices https://en.wikipedia.org/wiki/Determinant.
Instead, you can transform your matrix with Gaussian transformations to an upper triangular matrix and just multiply elements on diagonal.
Comment: Ah that's a pity. Thanks for the hint.
Answer: Let us assume that all matrices are square and $n \times n$. Permuting the columns,
$$\det \begin{bmatrix} \mathrm O_n & \mathrm A\\ \mathrm A^{\top} & \mathrm B \end{bmatrix} = \det \begin{bmatrix} \mathrm A & \mathrm O_n\\ \mathrm B & \mathrm A^{\top}\end{bmatrix} \cdot \underbrace{\det \begin{bmatrix} \mathrm O_n & \mathrm I_n\\ \mathrm I_n & \mathrm O_n\end{bmatrix}}_{= \pm 1} = \pm \left( \det (\mathrm A) \right)^2$$
Comment: But you cannot calculate the determinant of the nonsquare matrix A right?
Comment: Is there any way to determine the determinant of the matrix $Z$ above more easily?
Comment: This idea does not seem to work for $Z$. The determinant of $AA^T$ is 313 or -313 while the determinant of $Z$ should be 24.
Answer: Let $\mathrm A \in \mathbb R^{m \times n}$ and $\mathrm B \in \mathbb R^{n \times n}$. Assuming that $\mathrm B$ is invertible, we use the Schur complement
$$\begin{bmatrix} \mathrm O_m & \mathrm A\\ \mathrm A^{\top} & \mathrm B \end{bmatrix} \begin{bmatrix} \mathrm I_m & \mathrm O_{m \times n}\\ -\mathrm B^{-1} \mathrm A^{\top} & \mathrm I_n\end{bmatrix} = \begin{bmatrix} -\mathrm A \mathrm B^{-1} \mathrm A^{\top} & \mathrm A\\ \mathrm O_{n \times m} & \mathrm B\end{bmatrix}$$
and, taking the determinant, we obtain
$$\det \begin{bmatrix} \mathrm O_m & \mathrm A\\ \mathrm A^{\top} & \mathrm B \end{bmatrix} \cdot \underbrace{\det \begin{bmatrix} \mathrm I_m & \mathrm O_{m \times n}\\ -\mathrm B^{-1} \mathrm A^{\top} & \mathrm I_n\end{bmatrix}}_{=1} = \det \begin{bmatrix} -\mathrm A \mathrm B^{-1} \mathrm A^{\top} & \mathrm A\\ \mathrm O_{n \times m} & \mathrm B\end{bmatrix} = \color{blue}{(-1)^m \det (\mathrm A \mathrm B^{-1} \mathrm A^{\top}) \, \det(\mathrm B)}$$


How many integer numbers from 0 to 100000 contain 2 or more digits 5?

Question: How many integer numbers from 0 to 100000 contain 2 or more digits 5? I know that I need to apply some kind of formula to this problem, but I can't choose which one.
Can you please help me?
Comment: How many contain no $5's$?  How many contain exactly $1$?
Comment: not exactly one, more or equals to 2 5's, example - 55 535 553 355
Comment: I understand that.  But it's easier to work with the complement:  if your number fails to have two or more $5's$ than either it has none or exactly one.
Comment: To clarify the total count:  are you looking at integers $n$ with $0≤n≤100000$ or with $0<n<100000$?  It doesn't change the answer much, but you ought to clarify what you meant.  The posted solution from @Sarah below assumes you meant the former...if instead you meant the latter, then the $100,001$ ought to be $99,999$.
Comment: Sarah was right, including 0 and 100000.
Answer: For numbers that don not contain digit 5, we have 9 options (0,1,2,3,4,6,7,8,9) for each digit. And we have 5 digits in total, so number of numbers that do not contain digit 5 would be $9\times 9\times 9\times 9\times 9=9^5$.
Number of numbers that contain at least one digit 5 = All numbers - Number of numbers that do not contain digit 5 = $100001-9^5$
(Note: we put $100001$ here because there's $100001$ numbers from 0 to $100000$)
Number of numbers that contain only one digit 5 = $5\times 9^4$
So, number of numbers that contain at least two digit 5 = $100001-9^5-5\times 9^4=8147$


How to get Doveconf to reload its config or read from `/etc/dovecot/`?

Question: Edit
Ok, so if you care to read the original question, you'll see I've had a fun time with this.
I'm running Ubuntu 13.10 - Dovecot v2.1.7 -
And it seems my original problem was due to some misconfiguration - so, I re-configured this and that in /etc/dovecot/ - to no avail ~
So, today, I noticed that the output of doveconf does not reflect my changes no matter what I do -
service dovecot reload
dovecot reload
doveconf reload

How do I get it to read the load the .conf's in /etc/dovecot/ -and probably more importantly -- the .conf's in /etc/dovecot/conf.d/ -?

Original Question:
Our small business moved our email service to an un-managed server, recently - and it works perfectly - !
Except about three days this week, when the imaps port closes, and no one can receive email.
The first time, simply reloading dovecot did the trick - the second time, it worked for a split second and stopped... and ever since then, the only way I can figure out how to get it working again is to restart the whole server.
After Googleing around a bit, I added
login_process_size = 64
to dovecot.conf - restarted dovecot, but this morning, I found that it had crashed again.
Also, I noticed an error that said that setting was being overridden, but I can't find where.
mail.err gives this:
Apr 11 09:27:50 Mary dovecot: imap-login: Error: read(anvil) failed: EOF
Apr 11 09:27:50  dovecot: last message repeated 11 times
Apr 11 09:27:50 Mary dovecot: auth: Error: read(anvil-auth-penalty) failed: EOF
Apr 11 09:27:50 Mary dovecot: imap-login: Error: read(anvil) failed: EOF
Apr 11 09:27:55 Mary dovecot: lda: Error: userdb lookup(firstname.lastname@example.com): Disconnected unexpectedly
Apr 11 09:27:55 Mary dovecot: lda: Fatal: Internal error occurred. Refer to server log for more information.

I'm not sure what would be relevant in doveconf - but, one thread mentioned setting a value that is not present in mine -
Also - I've set auth_max_worker_count to 60, just now - and I'm hoping that'll work ---
But if anyone can clue me in on what I need to tweak, what I should look at, or how I should adjust
10-logging.conf to give me more clues on this matter, I would greatly appreciate it..
As per NickW's comment, the output of
cat /proc/{dovecot/anvil pit}/limits is:
Limit                     Soft Limit           Hard Limit           Units
Max cpu time              unlimited            unlimited            seconds
Max file size             unlimited            unlimited            bytes
Max data size             268435456            268435456            bytes
Max stack size            8388608              unlimited            bytes
Max core file size        0                    unlimited            bytes
Max resident set          unlimited            unlimited            bytes
Max processes             63651                63651                processes
Max open files            1024                 4096                 files
Max locked memory         65536                65536                bytes
Max address space         268435456            268435456            bytes
Max file locks            unlimited            unlimited            locks
Max pending signals       63651                63651                signals
Max msgqueue size         819200               819200               bytes
Max nice priority         0                    0
Max realtime priority     0                    0
Max realtime timeout      unlimited            unlimited            us

Now, There are about 15 people connecting - most of which also connect via their cell phone -
Those limits look fine to me, but I'm relatively inexperienced in this..
Comment: What do you get back from this command? `cat /proc//limits` ?
Comment: What is your `default_client_limit` set to, and `default_process_limit`?
Comment: That could be the case, do you have any idea about how many connections you have going before the problem shows up?
Comment: Also, what version of dovecot, and what OS are you on?
Comment: You may want to ramp up the log level, add this into your dovecot.conf:  `debug_log_path = path/to/debug/log`
Comment: Well, `ps -ef` lists two processes for anvil - assuming dovecot/anvil - I will edit the question accordingly -
Comment: 1000 and 100, respectively --- I ran across something that said "dovecot spawning multiple processes per user" -- when I was researching this - perhaps that is the case? - thanks for your assistance, btw -
Comment: No, I don't, but it shouldn't be anymore than 50, at the very most (~40, realistically).  - Ubuntu 13.10 - Dovecot 2.1.7 -
Comment: I ramped up the logging, but its not actually outputting anything at all - any other ideas on what I could do?
Comment: `syslog` doesn't report any errors, either --
Comment: Oh, hey, I noticed that `doveconf` doesn't report the same thing that I've put in my config file - How can I force `doveconf` to read from the `.conf` files in `/etc/dovecot/*` -?
Comment: The answer was that dovecot.conf was missing the `!include ~` statement.
So, if you make an answer, that mentions something about checking the output of doveconf - I'll happily award you the points.
Comment: Sounds like a plan to me :)
Answer: I'm not exactly sure what the problem is, but you can obtain more information about what is going wrong by enabling the debug log debug_log_path = path/to/debug/log and by ensuring that the changes you've made to the configuration are actually seen by dovecot. The easiest way to verify what dovecot is actually using at runtime is the doveconf command, dovecot -a will show you these values.
Comment: can you believe it wound up being fail2ban ? e_e

Thanks for all the help - !


How to change arrow and text on click?

Question: So i have this Demo  I want when user click on Advanced it will expand menu and it will change text "ADVANCED" to "BASIC" and it will change arrow from down to UP. Any suggestion?
function toggleChevron(e) {
    $(e.target)
   .prev('.panel-heading')
   .find("i")
   .toggleClass('fa-angle-up fa-angle-down')
}

$('#accordion').on('hidden.bs.collapse shown.bs.collapse', toggleChevron);

Answer: I think you are looking for something like following.
function toggleChevron(e) {
    var link = $(this);
    if (link.text().trim() == 'ADVANCED')
        link.html('BASIC ')
    else
        link.html('ADVANCED ')
}

$('#headingOne a').on('click', toggleChevron);

DEMO
Answer: You'll have to bind click event on your accordion instead of the ones you did. Then you change the text depending on what is already displayed.
function toggleChevron(e) {
    var text = $(e.target).html();

  if( $(e.target).find('i').hasClass('fa-angle-down') ) {
    $(e.target).html( text.replace('ADVANCED', 'BASIC') );
  } else {
    $(e.target).html( text.replace('BASIC', 'ADVANCED') );
  }

  $(e.target)
    .find('i')
    .toggleClass('fa-angle-up fa-angle-down');
}

$('#accordion').on('click', toggleChevron);

https://jsfiddle.net/L03e5hty/2/
EDIT : better answer here

How to change arrow and text on click?


Error on a simple https get test

Question: I'm following the mkyong tutorial from https://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/
But instead of calling localhost, I'm using this website: https://httpbin.org/get
I was able to make it work with HTTP, but not with HTTPS. When I try to run it with HTTPS, I get this error:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderExce
ption: unable to find valid certification path to requested target
        at sun.security.ssl.Alerts.getSSLException(Unknown Source)
        at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
        at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
        at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
        at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
        at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
        at sun.security.ssl.Handshaker.processLoop(Unknown Source)
        at sun.security.ssl.Handshaker.process_record(Unknown Source)
        at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source
)
        at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
        at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
        at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect
(Unknown Source)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown S
ource)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown So
urce)
        at java.net.HttpURLConnection.getResponseCode(Unknown Source)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unk
nown Source)
        at com.my.app.HTTPSGetTest.main(HTTPSGetTest.java:22)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed:
 sun.security.provider.certpath.SunCertPathBuilderException: unable to find vali
d certification path to requested target
        at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
        at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
        at sun.security.validator.Validator.validate(Unknown Source)
        at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
        at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
        at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Sour
ce)
        ... 15 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to
 find valid certification path to requested target
        at sun.security.provider.certpath.SunCertPathBuilder.build(Unknown Sourc
e)
        at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown
 Source)
        at java.security.cert.CertPathBuilder.build(Unknown Source)
        ... 21 more

Here is the code I'm using:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class HTTPSGetTest {

  public static void main(String[] args) {

    try {

      URL url = new URL("https://httpbin.org/get");
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");

      if (conn.getResponseCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
      }

      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      String output;
      System.out.println("Output from Server .... \n");
      while ((output = br.readLine()) != null) {
        System.out.println(output);
      }

      conn.disconnect();

    }
    catch (MalformedURLException e) {

      e.printStackTrace();

    }
    catch (IOException e) {

      e.printStackTrace();

    }

  }
}

I tried running InstallCert.java like described here: http://www.mkyong.com/webservices/jax-ws/suncertpathbuilderexception-unable-to-find-valid-certification-path-to-requested-target/, but I get the following error doing that:
Loading KeyStore C:\Program Files\Java\jre1.8.0_31\lib\security\cacerts...
Opening connection to localhost:3128...
Starting SSL handshake...
Exception in thread "main" java.net.SocketException: Connection reset
        at java.net.SocketInputStream.read(Unknown Source)
        at java.net.SocketInputStream.read(Unknown Source)
        at sun.security.ssl.InputRecord.readFully(Unknown Source)
        at sun.security.ssl.InputRecord.read(Unknown Source)
        at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source
)
        at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
        at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
        at InstallCert.main(InstallCert.java:105)

I'm behind a proxy and I'm using cntlm to access things outside the proxy. I don't know if this is the problem, or something else, since I was able to do the request without problems using HTTP.
Answer: You can follow the steps mentioned here www.grim.se/guide/jre-cert
Also, confirm if you have followed the steps mentioned here how-to-configure-tomcat-to-support-ssl-or-https
Comment: https://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers
Comment: @SteveSmith I did go through the links I have posted and it does seem that it will help the asker. Thanks for comment though. Good to know :)

Error on a simple https get test


What is a Golden set? and what is the difference with Bagel set?

Question: What is a Golden set on tennis?
Is there a tennis player who won a golden set?
What is the difference between Golden set and Bagel set?
Comment: Wikipedia: [Golden set](http://en.wikipedia.org/wiki/Golden_set)
Answer:
Golden set: Set which is won without dropping a single point.
Only one man in the history of top-tier professional tour tennis has
  ever achieved this: Bill Scanlon against Marcos Hocevar in the
  first round of the WCT Gold Coast Classic at Delray Beach on February
  22, 1983.    Scanlon won the match 6–2, 6–0. The achievement is
  recorded in the Guinness Book of World Records.
There are only 2 women to won golden set:   In 1943, Pauline Betz
  won the Tri-State tournament in Cincinnati, Ohio, defeating Catherine
  Wolf in the final, 6–0, 6–2, without losing a point in the first set.
  In the 2012 Wimbledon Championships, Yaroslava Shvedova achieved a
  golden set against Sara Errani. She later went on to win the match
  6-0, 6-4.

There is also a "Golden match": a match which is won without losing a single point, the entire match! but no one has won it until today..
Bagel set is a set which the winning player won 6-0, and the difference with Golden set is that you can lose points during the game as long as you win the game.

There is a Golden Bagel
  Award is an award
  established in 2004 that honors the professional male tennis player
  who has handed out more "bagels" (sets won 6-0), than any other player
  on the circuit.   Roger Federer holds the all-time record for most
  bagels in a single season with 18 going into the Tennis Master's Cup,
  and a total of 19 in 2006.


Relationship between gamma and chi-squared distribution

Question: If $$Y=\sum_{i=1}^{N}X_i^2$$ where $X_i \sim \mathcal{N}(0,\sigma^2)$, i.e. all $X_i$ are i.i.d. normal random variables of zero mean with same variances, then $$Y \sim \Gamma\left(\frac{N}{2},2\sigma^2\right).$$
I know the chi-squared distribution is a special case of the gamma distribution, but could not derive the chi-squared distribution for random variable $Y$. Any help, please?
Answer: Some background
The $\chi^2_n$ distribution is defined as the distribution that results from summing the squares of $n$ independent random variables $\mathcal{N}(0,1)$, so:
$$\text{If }X_1,\ldots,X_n\sim\mathcal{N}(0,1)\text{ and are independent, then }Y_1=\sum_{i=1}^nX_i^2\sim \chi^2_n,$$
where $X\sim Y$ denotes that the random variables $X$ and $Y$ have the same distribution (EDIT: $\chi_n^2$ will denote both a Chi squared distribution with $n$ degrees of freedom and a random variable with such distribution). Now, the pdf of the $\chi^2_n$ distribution is
$$
f_{\chi^2}(x;n)=\frac{1}{2^\frac{n}{2}\Gamma\left(\frac{n}{2}\right)}x^{\frac{n}{2}-1}e^{-\frac{x}{2}},\quad \text{for } x\geq0\text{ (and $0$ otherwise).}
$$
So, indeed the $\chi^2_n$ distribution is a particular case of the $\Gamma(p,a)$ distribution with pdf
$$
f_\Gamma(x;a,p)=\frac{1}{a^p\Gamma(p)}x^{p-1}e^{-\frac{x}{a}},\quad \text{for } x\geq0\text{ (and $0$ otherwise).}
$$
Now it is clear that $\chi_n^2\sim\Gamma\left(\frac{n}{2},2\right)$.
Your case
The difference in your case is that you have normal variables $X_i$ with common variances $\sigma^2\neq1$. But a similar distribution arises in that case:
$$Y_2=\sum_{i=1}^nX_i^2=\sigma^2\sum_{i=1}^n\left(\frac{X_i}{\sigma}\right)^2\sim\sigma^2\chi_n^2,$$
so $Y$ follows the distribution resulting from multiplying a $\chi_n^2$ random variable with $\sigma^2$. This is easily obtained with a transformation of random variables ($Y_2=\sigma^2Y_1$):
$$
f_{\sigma^2\chi^2}(x;n)=f_{\chi^2}\left(\frac{x}{\sigma^2};n\right)\frac{1}{\sigma^2}.
$$
Note that this is the same as saying that $Y_2\sim\Gamma\left(\frac{n}{2},2\sigma^2\right)$ since $\sigma^2$ can be absorbed by the Gamma's $a$ parameter.
Note
If you want to derive the pdf of the $\chi^2_n$ from scratch (which also applies to the situation with $\sigma^2\neq1$ under minor changes), you can follow the first step  here for the $\chi_1^2$ using standard transformation for random variables. Then, you may either follow the next steps or shorten the proof relying in the convolution properties of the Gamma distribution and its relationship with the $\chi^2_n$ described above.
Comment: $\chi_n^2$ denotes the Chi squared distribution function with $n$ degrees of freedom and also a random variable that follows such distribution. This is maybe an abuse of notation, but the meaning should be clear. I will edit the answer to clarify it nevertheless.
Comment: Nice description (+1).
But I am doubtful when you say that $Y_2\sim\sigma^2\chi_n^2,$ probably it should be  $Y_2=\sigma^2U,$ where $U\sim\chi_n^2.$ And finally, $
f_{\sigma^2 U}(x;n)=f_{\chi^2}\left(\frac{x}{\sigma^2};n\right)\frac{1}{\sigma^2}.$
Comment: Thanks @kaka. On the first point, actually with the notation $\sigma^2\chi_n^2$ I am referring to the random variable that arises when you multiply a $\chi^2_n$ variable by $\sigma^2$, so both of us are saying the same... On the second point, recall that $f_{\chi^2}(x;n)$ is the notation I used to refer to the density of a $\chi^2_n$ (the parameter $n$ appears as a second argument). With your notation, the density of $\sigma^2\chi^2_n$ will read as $f_{\chi_n^2}(x;n)$, which is also OK, but you are repeating twice the $n$.
Comment: But in the very first equation you defined $\mathcal{X}_n^2$ as a distribution of $\sum_{i=1}^N X_i^2.$
Comment: Yes, and in the equation for $Y_2$ the $X_i$'s have variance $\sigma^2$, so $\frac{X_i}{\sigma}$ is like $X_i$ in the first equation.
Comment: I mean this equation $Y_1=\sum_{i=1}^nX_i^2\sim \chi^2_n.$ ($\chi^2_n$ is a distribution-function and NOT a random variable)
Comment: I have not checked this in detail, but just thinking about scaling, shouldn't the the distribution be $\Gamma(N/2,2σ)$, not $\Gamma(N/2,2σ^2)$?
Comment: Yes, in case $\sigma=1$ :)
Comment: @NatKuhn : The parameters of the $\Gamma (\alpha , \beta)$-distribution are known as the shape parameter ($\alpha$) and scale parameter ($\beta$) respectively. The distribution has the nice property that the sum of two independent random variables with the same scale parameter is again $\Gamma$ with shape equal to the sum of the shapes.
Moreover, a $\Gamma$-distributed random variable multiplied by a scalar is again $\Gamma$ with the scale parameter multiplied by the scalar.

Note in particular that the scale parameter is not the variance.
Comment: @KetilBT, thanks. I was confused because although the $X_i$ scale by $\sigma$, the $\chi^2$ scales by $\sigma^2$
Comment: @NatKuhn : No worries. I guess I could have said it more compactly by noting that if $X \sim \Gamma ( \alpha, \beta)$ then $a X \sim \Gamma(\alpha, a \beta)$ for $a > 0$ and $V(X) = \alpha \beta^2$ meaning that $\sigma^2 X \sim \Gamma ( \alpha, \sigma^2 \beta)$ with $V(X) = \alpha (\sigma^2 \beta)^2$. Not sure if that helps though?


SQL Server Mirroring - Should Witness server be dedicated to mirroring?

Question: Scenario - SQL Server 2008 R2 Mirrored environment - High Safety synchronous with automated failover.
Witness Server is a SQL Server 2008 R2 Express Edition.
Question: Can the Witness server be used for other SQL purposes? In particular I am wondering if it is possible to complete test restores of database backups on the Witness and then run integrity checks (DBCC CHECKDB) on the restored database?
Thanks.
Answer: Yes, the witness server can do other tasks.
What you've suggested is quite useful.


Search Results page. Move the search form after the results?

Question: Apparently the only template file to edit is for an individual search result, located at core/modules/search/templates/search-result.html.twig. So you can't move the search form after the results and style accordingly?
Just want to double check this.
Answer: Short answer. If you're looking for a twig template to move around the search form, no you can't.
Long answer. Drupal core search dynamically builds its search routes for all searchable entities then handles the page render via SearchController::view(). The controller view method only defines the theme functions/templates for the search results, not the search page as a whole.
If you wanted to move these around the render form & results elements,
It's possible to override the search routes via a custom module so the  _controller property points to a custom controller that extends SearchController and defines a view() method that does something like:
// in my custom search controller:
public function view(Request $request, SearchPageInterface $entity) {
  $build = parent::view($request, $entity);
  // @TODO: alter $build render array so form / results are re-ordered
  return $build;
}

Comment: A full example of overriding the SearchController can be found at https://stackoverflow.com/a/44522792/6046296


Coldfusion cfcontent doesn't take me back to my calling page

Question: I'm calling this from a .cfm page to download the excel file and I have added a loading mask to prevent further clicks on the download button, however, once after downloading it doesn't go back to my .cfm page and never stops the loading masks.
cfheader( name="Content-Disposition", value="attachment; filename=#fileName#" );
cfcontent( type="application/vnd.ms-excel", variable="#spreadsheetReadBinary(spreadsheet)#", reset="true" );

Any help would be appreciated. Thanks!
Comment: Hate to break it to you but,that's how cfcontent works.
Comment: Are you opening a new tab/window to trigger download?
Comment: No, I'm downloading on the same page and that is why I have added the loading mask to prevent multiple clicks. The download and data is working fine but the mask doesn't go away because the cfcontent which is in .cfc file doesn't send back the response.
Comment: What makes you think the cfc isn't returning a response? Could you show us what you mean by "mask"?
Comment: @Agreax I have a .cfm page which is to download a file, so onSubmit all it does is call a .cfc file where the code is to download using cfcontent, once after the download it never returns back to my .cfm page. Since I started the loading mask onSubmit it never stops loading the mask.
Comment: @DanBracuk - Thank you for confirming me. I didn't find anything written on the website so I just wanted to know if there is a way to handle this.
Answer: You're not going to get to any redirect command when using cfcontent. The response from that command is based on the mime-type of the requested content.

application/json
application/xml
application/vnd.ms-excel

You don't get anything other than that content. In your case, once the file is downloaded, then no more CFML code is run on the page.
If your desired workflow is:

Click a link
Download file
Redirect once the file is downloaded.

then you should

Click a link that triggers a fetch request (or jQuery.ajax())
The download will be done via a separate page.
The fetch can redirect to another page once the file is downloaded.

Odds are, you don't need to actually redirect, you just want the file to download
(Sorry, this has been sitting not posted for a few days.)
Comment: Thank for the response. I only wanted to stop the loading mask. My only intention of using this to prevent a user from submitting it multiple times without waiting for the file to download.