I have a list of URL's and I want to know to which html div each URL belongs in a HTML page

Question: I have a list of URL's and I want to know to which html div each URL belongs in a HTML page
I have to do it using java
Comment: You need to provide a lot more details before anyone can even begin to answer your question.
Comment: Could you include what you tried and what didn't work?
Comment: use parsers like jsoup or apache html parser to parse the html and use comparision to find out the div.
Comment: I have  a webpage, I need to get all the urls from the page. I am able to do that. But I also want to know the url which I am taking belongs to which div
Comment: Yes, I'm using jsoup to get the elements
Comment: is there a way I can know the div name using jsoup?
Comment: For example:

I want something like this as a output

class="header"
URL http://ir.ebaystatic.com/rs/v/32q2wauokmyjletm4byq40w5s2i.css

I'm doing something like this:
Elements urls = doc.select("a[href]");
for(Element url: urls){
System.out.println(url.id());
}

But this is giving me the id of the link (a)
Comment: Welcome to SO. Your question needs improvement. For a start, please add the info to your question and not the comment section. Give the code your are using, what you get and what you expect. Then I am sure you get meaningful answers.
Answer: You can select all the divs and loop through the div's to get the links using jsoup.
Document doc = Jsoup.connect("url").get();
Elements divs = doc.select("div");

for (Element div : divs) {
        String linkHref = div.attr("name");
    Elements links = div.select("a[href]");
}

Answer: I am not sure if this is what you are asking, but here is my guess: You try to get the href attribute text of an anchor element. If this is so, you can simply access it like this whithin your loop:
String hrefStr = url.attr("href");


Como posso mudar o valor do input após uma condição?

Question: Tenho seguinte script

if ((modalidade == plano) && (produto == idproduto)) {
    //muda valor do input
}

Preciso mudar este valor :
<input type="text" name="desconto' + x + '" id="desconto' + x + '" value="0" class="form-control produtoCounter desconto" Size="2" onchange="somarTotais()" placeholder="Desc" />\

Quando uma condição for verdadeira.
Se for o value passa de 0 para 30.
Tem como fazer isso?
Comment: Resposta é sim, tem como. Agora você precisa nos dizer onde você quer colocar a condição, seria melhor explicar o que realmente quer fazer para obter um resultado melhor.
Comment: Qual é a condição exatamente?
Comment: Eu acabei de editar o código, coloquei a condição.peço desculpas acabei subindo o código antigo.
Comment: @FernandoTrilha procure sempre simplificar sua pergunta, colar toda sua lógica (ou boa parte dela) não vai te ajudar a econtrar a resposta. Entenda seu problema e coloque o trecho de codigo que apenas representa sua dúvida, assim você vai conseguir ajuda muito mais rápido. Além disso tavez você criar um contexto imaginário fora do seu problema real pode ser uma otima escolha também
Comment: Entendi, irei fazer isso nas próximas vezes.
Answer: Se você que criar o input já com o valor resolvido da condição você pode fazer isso direto no atributo value do elemento basta resolver essa condição em uma variável e concatená-la no value do input semelhando você fez com x;
/**
 * Variavel resolvida com a condição desejada
 */
var inputValue = ((modalidade == plano) && (produto == idproduto)) ? 30 : 0;

<input type="text" name="desconto' + x + '" id="desconto' + x + '" value="'+ inputValue +'" class="form-control produtoCounter desconto" Size="2" onchange="somarTotais()" placeholder="Desc" />

Veja o trecho do seu código alterado seguir:
$(add_button).click(function (e) { //on add input button click
    e.preventDefault();
    if (x < max_fields) { //max input box allowed
        x++; //text box increment
        /**
         * Variavel resolvida com a condição desejada
         */
        var inputValue = ((modalidade == plano) && (produto == idproduto)) ? 30 : 0;

        $(wrapper).append('
\
            <input type="text" name="idproduto' + x + '" class="form-control produtoCounter" id="idproduto' + x + '"  Size="1" placeholder="Id" readonly />\
            <input type="text" name="ean' + x + '" class="form-control produtoCounter" id="codigo' + x + '"  Size="10" placeholder="Código" readonly />\
            <input type="text" name="nome' + x + '" class="form-control produtoCounter" id="nome' + x + '"  Size="50" placeholder="Nome" required />\
            <input type="text" name="referencia' + x + '" class="form-control produtoCounter" id="referencia' + x + '"  Size="10" placeholder="Referencia" readonly />\
            <input type="text" name="quantidade' + x + '" id="quantidade' + x + '"  class="form-control produtoCounter quantidade" Size="2" placeholder="Quant." onchange="somarTotais()" required />\
            <input type="text" name="valorunitario' + x + '" id="valorunitario' + x + '" onkeydown="FormataMoeda(this,10,event)" onkeypress="return maskKeyPress(event)" class="form-control produtoCounter valorunitario" Size="5" placeholder="Valor" readonly />\
            <input type="text" name="desconto' + x + '" id="desconto' + x + '" value="'+ inputValue +'" class="form-control produtoCounter desconto" Size="2" onchange="somarTotais()" placeholder="Desc" />\
            <input type="text" name="desconto1' + x + '" id="desconto1' + x + '" class="form-control produtoCounter desconto1" Size="2" onchange="somarTotais()" style="display: none;" />\
            Remover\

');

        $("#nome" + x).autocomplete({
            source: "produtos.php",
            minLength: 2,
            select: function (event, ui) {
                event.preventDefault();
                $('#idproduto' + x).val(ui.item.idproduto);
                 idproduto = ui.item.idproduto;
                $('#nome' + x).val(ui.item.nome);
                $('#codigo' + x).val(ui.item.codigo);
                $('#referencia' + x).val(ui.item.referencia);
                $('#valorunitario' + x).val(ui.item.valorunitario);
                //$('#desconto' + x).val(ui.item.desconto);
                $('#desconto1' + x).val(ui.item.desconto);

            }
        });
    }
});

Comment: Ola Vinicius, obrigado pela ajuda.fiz uns ajustes e deu certo, muito obrigado pela ajuda amigo.


How do i find the overcommit ratio for CPU on a KVM host or for that matter on any hypervisor?

Question: I have a host and I have installed KVM on it.Now I need to know how much overcommiting of resources it allows, CPU, memory. Is there some command to get the ratios or it all exists in theory and no official documentation exists for it ?
Answer: KVM is just the hypervisor itself. It allows overcommitment without any artificial limit.
The limits are provided by any management tools installed on top of KVM, such as OpenStack.


Why are my elastic net and lasso r-squared measures negative?

Question: I'm using sklearn.linear_model.Lasso and sklearn.linear_model.ElasticNet on a model that includes a constant.
I don't expect a model with a constant to perform worse than the average of the data, ie an r-squared of 0.
I have p > n, but I have regressed on a few subset models and it's trivial to find an OLS subset with r-squared > .5.
Below are some of the model metrics. I'm baffled that the r-squared is negative at all, and further baffled that r-squared is below -1.
Lasso(alpha=0.1)
r^2 on test data : -1.609104
ElasticNet(alpha=0.1, l1_ratio=0.7)
r^2 on test data : -1.745874

Related code is open-source here.
I tried a variety of other alphas but did not achieve a non-negative r-squared. I did achieve an r-squared close to -0.003 with an alpha of 10.
Could anyone provide insight into how such metrics are observed?

Update, 10/20/21 - comparative sample scatter below
plt.scatter(y_train, y_train_pred_lasso, color='red')
plt.scatter(y_test, y_test_pred_lasso, color='blue')
plt.show()

Comment: PRESS is an out-of-sample measure, right?
Comment: If those are all your data (and your code suggests that they might be) then your train/test split is both losing power in the training and precision in the testing. Although such splits are taught in machine learning courses and are OK when there are tens of thousands of cases, they are [inappropriate for data sets of this size](https://www.fharrell.com/post/split-val/). Also, your code indicates that these are _adjusted_ $R^2$ values. What are the values of $n$ (number of cases) and $p$ (number of predictors) corresponding to the adjusted $R^2$ values that you report?
Comment: [A question of mine](https://stats.stackexchange.com/questions/494274/why-does-regularization-wreck-orthogonality-of-predictions-and-residuals-in-line) from last year may interest you. This lack of orthogonality means that $R^2$ lacks the usual "proportion of variance explained" interpretation, which is the big selling point $R^2$ has over $MSE$ and $RMSE$, an absolute measure of model performance. (I dispute that $R^2$ is an absolute measure of performance. $R^2$ values do not correspond to letter grades in school: $R^2 = 0.1$ could be quite good, and $R^2 > 0.9$ could be quite pedestrian.)
Comment: My predicted variable is continuous, so I see how to compute r-squared from PRESS [here](https://stats.stackexchange.com/a/123580/142294), but I still don't see how a negative number would be achieved unless the constant is dropped or something.
Comment: @Dave great point - I added a comparative scatter of the test/train split. There is a plausible negative intersample correlation, so I am happy to accept this as a partial answer. It seems to me that the best fit of blue is quite a good fit of red too though, and I still don't expect even a negative r-squared to go beyond -1. But great point and I will accept if you post as an answer and nothing more complete comes along within a few days. I did confirm the constant column is retained in X.
Comment: @EdM thanks for the link! n = 86, so 43 per split, p is 165. The r-squared are non-adjusted. My code has a `TODO` for adjusted r-squared but sklearn doesn't natively support it.
Comment: This is worth mentioning: If I predict on my training split data and compute the r-squared I get `-0.963746`. So I get the intuitive explanation that the worst model in sample 1 is the mean and that could correlate negatively with sample 2, but that explanation doesn't seem to account for predicting back on to the training split so poorly.
Comment: @Dave extremely useful link, very important comment. Thanks. I hadn't noticed that the usual interpretation isn't applicable here.
Answer: PRESS is an out-of-sample measure. Even when you have an intercept, out-of-sample $R^2<0$ is possible. It means that you would have been better off predicting the mean of $y$ every time, regardless of your predictors/features. In other words, you have a poor model that is outperformed by a naïve model.
You say that this is unexpected performance. You're doing machine learning, so prepare yourself to be surprised and disappointed by model performance.
Answer: Dave has addressed your specific question and I suggest you accept that answer. The point about "unexpected performance" in machine learning is quite on target.
What follows is more to get you headed toward better ways to handle your particular data set.
First, don't do a test/train split with so few cases. Build you model on the entire data set, then validate the model-building process by resampling. One accepted approach is to repeat the modeling on multiple bootstrap resamples of your data, and then test performance of the resulting models on the full original data set.
Second, LASSO or elastic net might not be a good choice here. You seem to have a lot of multi-level categorical predictors and at least 1 interaction. LASSO and elastic net won't necessarily keep all levels of a categorical predictor in the model, and might keep an interaction term while omitting the individual contributors to the interaction. That's not generally a good idea; see this thread. There is a group LASSO, explained in Statistical Learning with Sparsity, that can keep specified predictors together, but my guess is that your data set will be too small for that to work adequately.
Third, your many categorical predictors, some of them multi-level, pose a particular problem for penalized approaches like LASSO or elastic net. Continuous predictors in such models are usually normalized to zero mean and unit standard deviation so that they all start on similar scales. That doesn't always make sense with categorical predictors; with a multi-level predictor, the results might change depending on what you choose as the reference level! See this thread. Just jumping ahead into penalization without thinking hard about your categorical predictors is a too-easy way to get into a lot of trouble.
Before you go further with the mechanics of your modeling, see if you can use your knowledge of the subject matter to reduce the number of predictors or to combine multiple predictors into single predictors without first looking at their associations with outcome. Frank Harrell's course notes provide a lot of useful guidance for such predictor simplification and other aspects of multivariable modeling in Chapter 4.
I suspect that you will get the most reliable results by starting with such predictor combinations and then penalizing in a way that keeps all of those (combined) predictors in the model and avoids the unstable predictor selection you get with LASSO. Ridge regression is a choice, but a more general penalized estimation, adjusting relative penalization among predictors based on prior subject matter knowledge and handling categorical predictors intelligently, will probably work better.
Comment: Thanks to you both. Happy to accept Dave's answer as suggested.


ActionCable NoMethod Error

Question: I've added simple ActionCable to my toy rails app and discovered that I'm getting

Error: ProductsControllerTest#test_should_update_product:
  NoMethodError: undefined method server' for ApplicationCable:Module
      app/controllers/products_controller.rb:53:inblock in update'
app/controllers/products_controller.rb:44:in `update'
test/controllers/products_controller_test.rb:44:in `block in <class:ProductsControllerTest>'

when I start my rails unit tests. It's the only time when error occurs.
My code:
products_controller_test:
  test 'should update product' do
    patch product_url(@product), params: { product: @update }
    assert_redirected_to product_url(@product)
  end

config/application.rb
require 'action_cable'

/app/channels/application_cable/channel.rb
module ApplicationCable
  class Channel < ActionCable::Channel::Base
  end
end

/app/channels/application_cable/connection.rb
module ApplicationCable
  class Connection < ActionCable::Connection::Base
  end
end

/app/channels/products_channel.rb
class ProductsChannel < ApplicationCable::Channel
  def subscribed
    stream_from 'products'
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
end

/app/assets/javascripts/channels/products.coffee
App.products = App.cable.subscriptions.create "ProductsChannel",
  connected: ->
    # Called when the subscription is ready for use on the server

  disconnected: ->
    # Called when the subscription has been terminated by the server

  received: (data) ->
    $(".store #main").html(data.html)

/app/controllers/products_controller.rb
  # PATCH/PUT /products/1
  # PATCH/PUT /products/1.json
  def update
    respond_to do |format|
      if @product.update(product_params)
        format.html do
          redirect_to @product, notice: 'Product was successfully
          updated.'
        end
        format.json { render :show, status: :ok, location: @product }

        @products = Product.all
        ApplicationCable.server.broadcast 'products',
                                          html: render_to_string('store/index',
                                                                 layout: false)
      else
        format.html { render :edit }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

Thank you for any help!
Answer: in products_controller.rb. You should use 'ActionCable.server.broadcast' instead of ApplicationCable.server.broadcast
Have fun!

ActionCable NoMethod Error


$f(x)$ is onto?

Question: A function $f:R-{a_1,a_2}$ to $R$ is defined by $$f(x)=\frac{ Ax^2+6x-8}{A+6x-8x^2}$$
How many integral values of $A$  exist for which $f(x)$ is onto.
I tried finding the range of this function, but I did not find things working out. Please see- This is a problem from brilliant.org(I am not cheating, I have used all my chances).
Comment: Maybe you're not cheating, but are you encouraging others to cheat by coming here to look at the answers you get?
Comment: Please see that I am not asking for answers, I liked the answer mathgeek gave. He told me I was going right, but he didn't tell me the answer. I am discussing for different approaches.
Answer: I too solved that problem a couple of days back. You were on the right path, replace $f(x)$ by $y$ , cross multiply, make a quadratic in $x$ and make its $D>0$. Then, you must have a quadratic in $y$. A quadratic is always$>0$, only when its own $D<0$. Then, finally, you would have an expression in $A$, which you must be able to factorize, and with the method of solving inequality(probably the method of intervals), you will have your answer.

$f(x)$ is onto?


How to get specific posts from Graph API

Question: I'm working on the Facebook Graph API in PHP.
I am currently getting all posts from a specific page using an URL from this form:
https://graph.facebook.com/v2.5/{user-id}/posts?access_token={token}
I'd like to only get the posts from the user,that means not the posts from the visitors that are published on the page. I can make a first sort by checking the story field but I still get posts I don't need.
How do I make the difference between these posts ?
Thanks for your help.
Edit: I was using the wrong endpoint /feed and not /posts as I thought I was. Finally works
Comment: `/page-id/posts` should only give you posts made by the page itself in the first place; posts by others on that page should only be included in `/page-id/feed`
Comment: Thanks it finally works this way. I was mistaking and was using the feed endpoint.
Comment: i thought you were talking about user profiles, not pages - since you wrote "user-id" in your api call. people often say pages when they actually mean user profiles.
Comment: I removed  - Resolved from the question title. Accepting a posted answer closes the question and marks it as solved
Answer: There is no specific endpoint for this, so you have to do it on your own. You can use the "from" field to get the ID of the poster, just compare it to the ID of the authorized user:
me/posts?fields=message,from

If you are talking about Pages (not User Profiles), then /page-id/posts will deliver posts made by the Page anyway.
Comment: Thanks for you answer. I found out I made a simple mistake.
Hopefully this will help someone else.


Laravel Spatie/laravel-backup can't install

Question: I'm trying to implement automated backup in Laravel 8. I decided to go with the Laravel-backup package "spatie/laravel-backup".
The problem occurs when I try to install the package with "composer require spatie/laravel-backup".
I get this problem :
Problem 1 - spatie/laravel-backup[8.1.0, ..., v8.x-dev] require illuminate/console ^9.0 -> found illuminate/console[v9.0.0-beta.1, ..., 9.x-dev] but these were not loaded, likely because it conflicts with another require. - Root composer.json requires spatie/laravel-backup ^8.1 -> satisfiable by spatie/laravel-backup[8.1.0, 8.1.1, 8.1.2, v8.x-dev].
I tried running those commands from similar questions answers nothing changed:
-composer require spatie/laravel-backup "^8.1" --ignore-platform-reqs
-composer require spatie/laravel-medialibrary
Also I tried deleting vendor and composer.lock and then running composer install and the problem still persists.
I guess there is a problem in my composer.json file :
{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require": {
        "php": "^7.3|^8.0",
        "ext-gd": "*",
        "ext-json": "*",
        "aws/aws-sdk-php": "~3.0",
        "darkaonline/l5-swagger": "^8.1",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.75",
        "laravel/sanctum": "^2.11",
        "laravel/tinker": "^2.5",
        "league/flysystem-aws-s3-v3": "^1.0",
        "maatwebsite/excel": "^3.1",
        "tymon/jwt-auth": "^1.0",
      "ext-pdo": "*"
    },
    "require-dev": {
        "facade/ignition": "^2.5",
        "fakerphp/faker": "^1.9.1",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.4",
        "nunomaduro/collision": "^5.10",
        "phpunit/phpunit": "^9.5.10"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-update-cmd": [
            "@php artisan vendor:publish --tag=laravel-assets --ansi --force"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

Thanks to everyone who takes the time to look at my problem. :))
Comment: Have you tried' `composer require spatie/laravel-backup:7.0` which is the correct version for Laravel 8
Comment: @ManuelGlez I have no option to vote your answer, I'm new to using stack overflow as contributor, I will vote when i discover how to. Thanks a lot for your help !
Answer: Based on comments, install the correct version of Laravel Backup. Solved this problem.
composer require spatie/laravel-backup:7.0

Comment: Oh ok this is how it works, I have no reputation to vote unfortunately.
Answer: I am using Laravel 9.52 and php 8.2 while installing Spatie backup. Encountered same error and solved it by ignoring platform req. It was suggested in Git error description.
composer require spatie/laravel-backup --ignore-platform-req=ext-zip


Problem with Jetpack Compose Navigation in BottomNavigationBar

Question: Based on the following image, my App currently contains 2 main routes : Auth and Dashboard. When the user started the App, an observer will check whether the user is logged in and direct he/she to the Login Page/Dashboard.
Navigation Flow
From the image as you can see, I've set the NavGraph(which include all the Dashboard routes) in the MainActivity. The problem is when user click one of the bottom navigation items, he/she will be directed straight to the view page. Instead, what I wanted is to show the user the view inside the scaffold content of the Dashboard. Check the image below.
Problem Encountered
Based on the info, how can I get the composable view inside the scaffold content once the user click the item?
Any guidance will be much appreciated. Thanks!
Side Note: This is my first compose project and I am trying to implement the Single Activity architecture without any fragment used. I apologize prior if my code violate any design or programming convention as I am quite new into programming[self-learner aka Hobbyist here :( ].
MainActivity.kt
package com.example.firstcomposeproject

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navigation
import com.example.firstcomposeproject.authview.FirebaseUserViewModel
import com.example.firstcomposeproject.authview.LogIn
import com.example.firstcomposeproject.authview.SignUpFragment
import com.example.firstcomposeproject.dashboard.*

import com.example.firstcomposeproject.ui.theme.FirstComposeProjectTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val userViewModel: FirebaseUserViewModel by viewModels()

        setContent {
            FirstComposeProjectTheme(
                darkTheme = false
            ) {
                val navController = rememberNavController()

                /*
                Observing FirebaseUser LiveData to check if user is logged in. If yes, direct user
                to dashboard, else direct user to authenticate screen.
                */
                userViewModel.userMutableLiveData.observe(this, {
                        firebaseUser ->
                    if(firebaseUser != null){
                        navController.popBackStack()
                        navController.navigate("dashboard"){
                            popUpTo("auth"){
                                inclusive = true
                            }
                        }

                        userViewModel.clearFormField()
                    }else {
                        navController.navigate("auth"){
                            popUpTo("dashboard"){
                                inclusive = true
                            }
                        }
                    }
                })

                //Navigation Graph For The Whole App
                NavHost(navController = navController, startDestination = "auth"){
                    navigation(startDestination = "logInUI", route = "auth"){
                        composable("logInUI"){
                            LogIn(
                                userViewModel,
                                onNavigate = {
                                    navigateTo(it, navController)
                                }
                            ).FinalView()
                        }

                        composable("signUpUI"){
                            SignUpFragment(
                                userViewModel,
                                onNavigate = {
                                    navigateTo(it, navController)
                                }
                            ).FinalView()
                        }
                    }
                    addDashBoardGraph(userViewModel, navController)
                }
            }
        }
    }

    private fun navigateTo(
        dest: String,
        navController: NavController
    ){
        navController.navigate(dest)
    }

}

Dashboard.kt
package com.example.firstcomposeproject.dashboard

import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.navigation
import com.example.firstcomposeproject.authview.FirebaseUserViewModel
import com.example.firstcomposeproject.dashboard.helper.Screen

import com.example.firstcomposeproject.ui.theme.Teal200

fun NavGraphBuilder.addDashBoardGraph(
    userViewModel: FirebaseUserViewModel,
    navController: NavHostController
  ) {
    navigation(startDestination = "dashboardUI", route = "dashboard"){
        composable("dashboardUI"){
            Dashboard(
                navController,
                userViewModel
            )
        }

        composable("navigationUI"){
            Navigation()
        }

        composable("messageUI"){
            Message()
        }

        composable("historyUI"){
            History()
        }

        composable("profileUI"){
            Profile(
                userViewModel
            )
        }
    }
}

@Composable
fun Dashboard(
    navController: NavHostController,
    userViewModel: FirebaseUserViewModel
){
    val items = listOf(
        Screen.Navigation,
        Screen.Message,
        Screen.History,
        Screen.Profile
    )

    Scaffold(
        bottomBar = {
            BottomNavigation(
                backgroundColor = Color.White,
                contentColor = Teal200
            ) {
                val navBackStackEntry by navController.currentBackStackEntryAsState()
                val currentDestination = navBackStackEntry?.destination

                items.forEach{ screen ->
                    BottomNavigationItem(
                        label = { Text(text = screen.label)},
                        selected = currentDestination?.hierarchy?.any{ it.route == screen.route } == true,
                        onClick = {
                            navController.navigate(screen.route)
                            {

                                popUpTo(navController.graph.findStartDestination().id) {
                                    saveState = true
                                }
                                launchSingleTop = true

                                restoreState = true
                            }
                        },
                        icon = {
                            Icon(painterResource(id = screen.icon), screen.label)
                        }, unselectedContentColor = Color.Gray
                    )
                }

            }
        }
    ){
        //Scaffold Content - How to access the compose function from the MainActivity NavGraph here?
     }
}

Comment: Check [Nested navigation](https://developer.android.com/jetpack/compose/navigation#nested-nav)
Comment: @VygintasB if not mistaken, I've implemented nested navigation in the NavGraph with addDashBoardGraph func
Comment: @EverDream Did you find a solution to this?
Answer: Looking at your code, I think you need to set a NavHost in your Scaffold content in the Dashboard function, to tell the system you want to switch composables inside the layout with the bottomBar you created.
I see you already understand about nested navigation, so if you just want to reuse the same NavHost you can try to define it in a specific composable function.
@Composable
fun MyNavGraph(
    navController: NavHostController = rememberNavController(),
    userViewModel: FirebaseUserViewModel
){
    NavHost(navController = navController, startDestination = "auth"){
        navigation(startDestination = "logInUI", route = "auth"){
            composable("logInUI"){
                LogIn(
                    userViewModel,
                    onNavigate = {
                        navigateTo(it, navController)
                    }
                ).FinalView()
            }

            composable("signUpUI"){
                SignUpFragment(
                    userViewModel,
                    onNavigate = {
                        navigateTo(it, navController)
                    }
                ).FinalView()
            }
        }
        addDashBoardGraph(userViewModel, navController)
    }
}

I've not tried it, so let me know if fit your situation.
Hope it helps a little.
Answer: You should do it as follows -
In your MainActivity, call MyBottomNavApp
    class MainActivity : ComponentActivity() {
    lateinit var navController: NavController
    private val viewModel: MyAppViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        WindowCompat.setDecorFitsSystemWindows(window, false)
        installSplashScreen().apply {
            setKeepOnScreenCondition {
                viewModel.isLoading.value
            }
        }
        setContent {
            UnicornTheme {
                // Uncomment below and MyApp lines to use drawer navigation
                navController = rememberNavController()
                // MyApp(navController)
                // Uncomment MyBottomNavApp to get bottomnav navigation
                MyBottomNavApp(navController as NavHostController)
            }
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
    }
}

Then, implement MyBottomNavApp with a NavHost as below
@Composable
fun MyBottomNavApp(
    navController: NavHostController
) {
    Scaffold(
        modifier = Modifier.navigationBarsPadding(),
        bottomBar = { MyBottomNavigation(navController = navController)},
    ) { innerPadding ->
        Box(Modifier.padding(innerPadding)) {
            NavHost(
                navController = navController,
                startDestination = Home.route
                ) {
                composable(Home.route) {
                    DashboardScreen(navController = navController)
                }

                composable(Settings.route) {
                    NavigationScreen(navController = navController)
                }
            }
        }
    }
}

Then, implement Destinations as below -
interface Destinations {
    val route: String
    val icon: ImageVector
    val title: String
}

object Home: Destinations {
    override val route = "Dashboard"
    override val icon = Icons.Filled.Dashboard
    override val title = "Dashboard"
}

object Settings: Destinations {
    override val route = "Navigation"
    override val icon = Icons.Filled.Navigation
    override val title = "Navigation"
}

Then, implement MyBottomNavigation as below -
@Composable
fun MyBottomNavigation(
    navController: NavController
) {
    val destinationList = listOf<Destinations> (
        Dashboard,
        Navigation
    )

    val selectedIndex = rememberSaveable {
        mutableStateOf(0)
    }

    BottomNavigation(
        backgroundColor = colorResource(id = R.color.primary_contrast),
        contentColor = colorResource(id = R.color.secondary_contrast)
    ) {
        destinationList.forEachIndexed{index, destination ->
            BottomNavigationItem(
                label = { Text(text = destination.title)},
                icon = { Icon(imageVector = destination.icon, contentDescription = destination.title)},
                selected = index == selectedIndex.value,
                onClick = {
                    selectedIndex.value = index
                    navController.navigate(destinationList[index].route) {
                        popUpTo(Home.route)
                        launchSingleTop = true
                    }
                }
            )
        }
    }
}

You can see an example of this in the feature/develop_starter_kit_bottom_navigation branch of the following repo -
https://github.com/arunabhdas/unicorn-commerce/tree/feature/develop_starter_kit_bottom_navigation


An example of a group with a topology

Question: Do you know an example of a group with a topology satisfying both the following two conditions

the product is separately continuous but not jointly continuous
the inversion map is continuous.
Comment: One important example of a group with a topology is a Lie Group.  With that in mind, you might find [this post to be interesting](https://math.stackexchange.com/q/1258101/81360).
Answer: Take, for instance, $(\mathbb{Q},+)$, endowed with the Zariski topology (that is, a non-empty set $A$ is open if and only if $A^\complement$ is finite). Then the inversion ($x\mapsto-x$) is clearly continuous and addition is clearly separately continuous. But it is not jointly continuous since, for instance $\{(x,y)\in\mathbb{Q}^2\,|\,x+y=0\}$ is not a closed set.
Answer: Let $G$ be any infinite group and give it the cofinite topology.  Then the product is separately continuous as is inversion, since any bijection $G\to G$ is continuous.  But the product is not jointly continuous, since $\{1\}$ is closed but its preimage is not.  (Or, you can just cite the fact that any $T_0$ topological group is Hausdorff, so $G$ cannot be a topological group.)

An example of a group with a topology


Solving a matrix initial value problem

Question:
Let $A$ be a $2 \times 2$ matrix with $-3$ and $-1$ as eigenvalues. The eigenvectors are $v_1=[-1,1]$ and $v_2=[1,1]$. Let $x(t)$ be the position of a particle at time $t$.  Solve the initial value problem $x'(t)=Ax$, $x(0)=[2,3]$.

So this should be easy, we set up the system as two ODEs:
\begin{align}
x'(t) &= -e^{-3t}+e^{-t} \\
y'(t) &= e^{-3t}+e^{-t}
\end{align}
Integrating each eqn.:
\begin{align}
x(t) &= 3e^{-3t}-e^{-t} \\
y(t) &=-3e^{-3t}-e^{-t}
\end{align}
But without the coefficients there is nothing to discover.  So I insert the coefficients:
\begin{align}
x(t) &= C_13e^{-3t}-C_2e^{-t} \\
y(t) &=-C_13e^{-3t}-C_2e^{-t}
\end{align}
and apply the initial conditions:
\begin{align}
2 &= 3C_1-C_2 \\
3 &=-3C_1-C_2
\end{align}
but this gives:
\begin{align}
\frac{2+C_2}{3} &= C_1 \\
3 &= -2
\end{align}
which is clearly incorrect.
Any ideas?
Thanks
Comment: Check your linear system.
Answer: You made a mistake when you solved the linear system. Adding the two equations gives $5 = -2C_2$, hence $C_2 = -\frac{5}{2}$. Plugging this into one of the equations, we obtain $C_1 = -\frac{1}{6}$.
Comment: Thanks, though a simple small mistake, now at the least, we have a full example of solving a matrix equation with a correct procedure.
Answer: You misunderstood something from the start. The matrix $A$ is not explicitly given. From what is known of the general solution, you get
$$
\pmatrix{x\\y}=c_1v_1e^{-3t}+c_2v_2e^{-t}.
$$
There is no further differentiation or integration required. Just the solution of the linear system for the initial values
$$
\pmatrix{2\\3}=c_1\pmatrix{-1\\1}+c_2\pmatrix{1\\1}
\\~\\
2=-c_1+c_2\\
3=c_1+c_2
$$
which should be easily found as $c_1=0.5$ and $c_2=2.5$
Comment: Thanks Lutz, this was great.
Answer: Where you claim you "integrated each eqn.", you actually differenciated them instead:
\begin{align}
x(t) &= \frac13 e^{-3t}-e^{-t} \\
y(t) &=-\frac13 e^{-3t}-e^{-t}
\end{align}
The system for the constants after applying the initial conditions becomes:
\begin{align}
2 &= \frac13 C_1-C_2 \\
3 &=-\frac13 C_1-C_2
\end{align}
Add both to get $5=-2C_2$, then substract the second from the first to get $-1=\frac23 C_1$. Hence,
$$C_1 = -\frac32, \quad C_2 = -\frac52.$$

Solving a matrix initial value problem


Guardar valor em um input após inseri-los automaticamente usando Javascript

Question: Tenho um select box que define a quantidade de items vão ser exibidos pro utilizador preencher.
http://jsfiddle.net/thallysondias/dsqBf/55/
Contudo, quando ele deixa de preencher um dos inputs, exibe o erro: "undefined"
Se ele preencher os 5 cmapos, funcionam bem, o problema é quando o utilizador escolhe menos campo.
Como faço para poder recolher os value dos inputs e não exibir esse erro?
Answer: Ao invés de usar várias variáveis para preencher o resultado, você pode preencher somente uma contendo o texto, e verificar se a entrada é valida.
JSFiddle: http://jsfiddle.net/thallysondias/dsqBf/59/
Comment: Obrigado Lucas, realmente faz muito mais sentido. Mas eu não tinha nivel tecnico sufience para fazer. Contudo. Existe um erro no seu codigo que corrigi. [  if (i !== qtd - 1) { ] ao ter o "-1", ele não inseria o ultimo valor do input no input das idades totais, ao remove-lo, ja funciona bem.
Comment: Legal @ThallysonDias. Compartilha comigo a nova atualização do Fiddle que atualizo na resposta :)
Comment: aqui esta a versão alterada: http://jsfiddle.net/thallysondias/dsqBf/59/ na linha 19
Comment: Atualizei, obrigado.


POST request on GAE (status_code = 500)

Question: I am running the following code on Google App Engine Standard Python 2.7 version
import requests
import re
import datetime

ReviewsURL='https://play.google.com/store/getreviews'

payload =  { 'reviewType': '0'
                , 'pageNum': 0   #loads max 40 reviews for each page number
                , 'id': 'net.one97.paytm'
                , 'reviewSortOrder': '0'
                , 'xhr':'1'
           }

r = requests.post(
    url=ReviewsURL,
    data=payload,
    headers={
                'X-Requested-With': 'XMLHttpRequest'
            }
)

print r.text.encode('cp850', errors='replace').decode("unicode-escape")

This code used to run fine and output the latest 40 reviews but now it gives the following output:
Status_code = 500

When I run the same code on my Mac, it works fine as well.
Comment: Check your logs.
Comment: I am not seeing any error in my logs. The 500 status_code is the output of the request above. I got it from the command r.status_code
Comment: I tried to get more information and below is the error I get when I print r.raise_for_status()     "HTTPError: 500 Server Error: None for url: https://play.google.com/store/getreviews"
Comment: How are you authenticating? Can you try to recreate the authentication? Taking into account that it was working at the beginning but then it stopped, authentication expiration might be causing the issue.
Comment: There is no authentication needed for this code to run
Comment: I followed up with Google Cloud support and they told me that the GAE IP is blocked for this website play.google.com/store/getreviews
Answer: Taking into account the message "Server Error: None for url" looks like the URL cannot get reached. 500 are mainly caused by 2 reasons:

Dynamic responses, which are limited to 32MB. If a script handler generates a response larger than this limit, the server sends back an empty response with a 500 Internal Server Error status code.
Exceeded response time. A request handler has a limited amount of time to generate and return a response to a request, typically around 60 seconds. There are several root causes listed here.

There are many reasons that can cause a response time exceeding. I expect that you find yours in the documentation. I am not able to guess one of them based on the information we have.
Comment: Thanks I followed up with Google Cloud support and they told me that the GAE IP is blocked for this website https://play.google.com/store/getreviews

POST request on GAE (status_code = 500)


Representação de uma entidade em minha classe

Question: Tenho esse campo no banco: ID_LIBERACAO e na minha classe de domínio tenho assim:
[Table("Tabela")]
public class Tabela
[Key]
[DataBaseGenerated(DataBaseGeneratedOption.Identity)]
public int IdLiberacao {get; set; }

Mesmo com o nome sem o sinal de sublinhado, a minha classe entende que está se referindo ao campo da tabela? Eliminei todos os underscore dos nomes dos campos e padronizei desta forma. Não tenho como testar ainda, até receber a liberação do cliente.
Answer: Especifique o nome que está no banco, use annotation, veja:
[Table("Tabela")]
public class Tabela
[Key]
[DataBaseGenerated(DataBaseGeneratedOption.Identity)]
[Column("ID_LIBERACAO")]
public int IdLiberacao {get; set; }

Referência: DataAnnotation
Comment: Então, faço isso para todas as colunas que eu alterei o nome na classe? Eu fiz isso para todas
Comment: Sim, desta forma você terá o controle do mapeamento.
Comment: Edvaldo, caso o nome do atributo em minha classe seja igual ao do banco, eu não preciso usar o atributo Column, certo? Ou se já fiz em um, tenho que fazer em todos? Só uma dúvida.
Comment: Você pode fazer apenas nos casos que deseja customizar o mapeamento, não precisa fazer para todos.


Conditional independence regarding fourth event

Question: Let's two events $S1$ and $S2$ are conditionally independent given the event $A$, i.e.,
$P(S_1|S_2,A) = P(S_1|A)$ and $P(S_2|S_1,A) = P(S_2|A)$
If $B$ is an arbitrary event, does the following probability hold?
$P(S_1|S_2,A,B) = P(S_1|A,B)$?
Answer: No.  We can ignore $A$-let it be certainly true.  Let $S_1$ be a coin flip is heads and $S_2$ be a die roll is even.  Now let $B$ be coin flip heads iff die roll is even.  Then $P(S_1|S_2,B)=1, P(S_1|B)=\frac 12$


Sending more than one model to view MVC 4

Question: I have two model classes, each is a table in a database. One model is called 'Clothes' and the other 'Shoes'.
I want to display the contents of each table in the same razor view, but MVC is only letting me send one model to the view.
@model IEnumerable<Test.Models.Clothes>

Is there a way to send more than one model to a razor view?
If not, what is the normal way to display contents of another model in a view that has already got another model passed to it. Thanks for advice.
Answer: Either make a view model class which has both the class as its object. It would be then type safe.
public class ViewModelForDisplay
{
       public Clothes Clothes {get; set;}
       public Shoes Shoes {get; set;}
}

//on Controller
Clothes objClothes = GetClothes();
Shoes objShoes = GetShoes();

ViewModelForDisplay objViewModel = new ViewModelForDisplay() {Clothes = objClothes, Shoes= objShoes }

The other easy way to do it by using ViewBag.It uses the dynamic feature that was added in to C# 4. It allows an object to dynamically have properties added to it. Its also Type Safe
ViewBag.Shoes= objShoes ;
ViewBag.Clothes= objClothes ;

You could also use ViewData to pass objects to html. BUt this would not be type safe. It requires casting
ViewData["Clothes "] = objClothes ;
ViewData["Shoes "] = objShoes ;

Comment: View Model is the preferred approach.
Comment: Furthermore it's not a good idea to pass your model (the database object) to the view. Create a ViewModel only with the required fields
Comment: Thanks for replay and giving code sample, any chance of expanding on the controller? It doesn't work for me.
Answer: Make your own class aka View Model and have it composed of both models.
Answer: I have found this article very interesting :
https://workspaces.codeproject.com/user-10826818/using-multiple-models-in-a-view-in-asp-net-mvc-4
It presents different ways to send multiple models to a view :

ViewData
ViewBag
PartialView
TempData
ViewModel
Tuple


How to call a php function like in codeigniter using ajax?

Question: This one is very simple. In codeigniter I can have an ajax call like:
    $.ajax({
        type: "POST",
        url: base_url + "index.php/mycontroller/myfunction"
       //so in mycontroller.php  ^ there is function myfunction ()
        data:{id : id},
        success:function(data){

         };
       })

Since class Mycontroller extends CI_Controller.
So how can I do that in raw PHP if I have posted.php, how can I extend this file in order for me to call a function like this:
    <?php
        function test(){
           echo 'Hello World!';
         }

What i'm thinking is like:
    $.ajax({
        type: "POST",
        url: "posted.php/test", //go to posted.php and call test function if possible
        data:{id : id},
        success:function(data){

         };
       })

But this one is not working. So any help?
Comment: Well, you're gonna have to write your own framework that interprets the given URL and instantiates the controller and calls that function. Unless @Milanzor s method below is 'enough' for your application.
Comment: Are you wanting to call the `test()` function in posted.php? (I see by your edit that you do.)
Comment: @CWSpear Yes I am Sir
Comment: @AmazingDreams Yes Sir I just want to make it simple though.
Comment: extremely small and simple php framework you might want to look at is https://github.com/anandkunal/ToroPHP
Answer: You could change your ajax POST URL to something like this:
posted.php?call=test

then, in your posted.php, check the GET parameter 'call' and call the right function:
switch($_GET['call']){

  case 'test':
     test();
  break;
 }

 function test() {
     echo "Hello, world!";
 }

Comment: Explanation: You cannot call functions by the HTTP request alone. PHP still need to determine what you want to do. This is why its required to have handlers like this answer points you to. So either adapt this code or implement your own.
Comment: Or, you can just do , $_GET['call']() .
Comment: @adirohan Yeah, if you want your user to be able to call all functions available... Which no one would want.
Comment: @adirohan I'd recommend against that, very unsafe, that way I can call any function you define
Comment: It wouldn't be so bad if every function in that file was dedicated to being able to be accessed in that manner. It could cut down on a potentially large and unnecessary `switch`. But if you have other functions you *don't* want accessed, then yes, absolutely `$_GET['call']()` would be a bad idea.
Answer: CodeIgniter uses some $_SERVER variables to be able to get this information for you. It actually can vary from environment to environment, but it is commonly in $_SERVER['PATH_INFO'] (some environments don't even support this, and CI has a fallback to use query params).
Try a print_r($_SERVER); to see if you have an PATH_INFO variable. From there, CI can use the string value determine the name of the function and call it.
Here's a simple example:
function test ()
{
    echo 'Test success!';
}

$fn = trim(@$_SERVER['PATH_INFO'], '/');

if (function_exists($fn)) call_user_func($fn);
else die ("No function: {$fn}");

Additional Info: From the CI source (application/config/config.php) regarding what it uses for its routing:
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string.  The default setting of 'AUTO' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'AUTO'            Default - auto detects
| 'PATH_INFO'       Uses the PATH_INFO
| 'QUERY_STRING'    Uses the QUERY_STRING
| 'REQUEST_URI'     Uses the REQUEST_URI
| 'ORIG_PATH_INFO'  Uses the ORIG_PATH_INFO
|
*/

Comment: Ah, you're on Windows. Are you at `/posted.php/test` in that dump? `PATH_INFO` won't show up at all if it would be otherwise empty. Really though, you are actually probably better off with @Milanzor's solution, as it's a better solution to solve the problem of AJAXing content, but I was trying to answer your specific question about how CI does it and how you could roll your own.


How to extract specific elements with for-each in XSLT?

Question: For my exam in my class where we learned about things relating to XML, DTD, XSD, XSL, we were asked to create an XSLT that would extract from a document XML only the parks within the town of Saint-Malo and then turn the results into an XML document. My results were almost correct, but not quite. It's too late to change my grade, but I'm just really curious on how to do this.
Here's a snipit of the original XML:
<entry>
        <id>https://www2.mgcloud.fr/dataserver/tourismebretagne/data/jardins35fr('PCUBRE0351000100')</id>
        <title type="text">'PCUBRE0351000100'</title>
        <updated>2015-05-25T06:18:05Z</updated>
        <author>
            <name>https://www2.mgcloud.fr/dataserver/tourismebretagne/catalog/agents/17692</name>
        </author>
        <link rel="edit" title="jardins35frType" href="jardins35fr('PCUBRE0351000100')"/>
        <category term="fr.mgdis.odata.data.jardins35frType" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"/>
        <content type="parc">
            <properties>
                <num_id>PCUBRE0351000100</num_id>
                <titre>Le Domaine de la Briantais</titre>
                <theme>Parc</theme>
                <telephone>02 99 81 83 42</telephone>
                <fax>02 99 82 51 56</fax>
                <web>www.ville-saint-malo.fr</web>
                <mail>email@example.com</mail>
                <adresse>Rue Maurice Nogues</adresse>
                <code_postal>35400</code_postal>
                <insee>35288</insee>
                <commune>Saint-Malo</commune>
                <latitude>48.6194348</latitude>
                <longitude>-2.0147895</longitude>
                <pmr>Oui</pmr>
                <descriptif>Le Château a été construit à partir de 1864, en remplacement d'un vieux manoir du XVIIème siècle qui appartenait à  de notables armateurs malouins. La famille La Chambre en devient propriétaire en 1888. Il est entouré d'un parc de 27 hectares surplombant la Tour Solidor, et la vallée de la Rance. Parc ouvert de 9h à 19h en juillet et août. Ouvert de 14h à 17h ou 18h en semaine hors saison, et de 9h à 17h ou 19h les week-ends et jours fériés toujours en basse saison. Parc avec vues sur mer. Renseignements : ville de Saint Malo - Direction de l'Environnement et de l'Espace Public - Division des Espaces verts. 02 99 81 83 42 pour tout renseignement complémentaire.</descriptif>
                <photos>http://cdt29.media.tourinsoft.com/upload/4CECC4CF-0833-47A8-9B65-762C434CC0D0/Dinard-vu-de-la-Briantais.jpg</photos>
            </properties>
        </content>
    </entry>

Here's the XSLT I wrote:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="4.0" indent="yes"/>
    <xsl:template match="/">
        <parcs_et_jardins_de_Saint_Malo>
            <xsl:for-each select="//properties[commune='Saint-Malo']">
                <titre><xsl:value-of select="//titre"/></titre>
            </xsl:for-each>
        </parcs_et_jardins_de_Saint_Malo>
    </xsl:template>
</xsl:stylesheet>

Here's what I had for the resulting XML document:
<?xml version="4.0"?>
<parcs_et_jardins_de_Saint_Malo>
  <titre>Parc Oberthur</titre>
  <titre>Parc Oberthur</titre>
  <titre>Parc Oberthur</titre>
  <titre>Parc Oberthur</titre>
  <titre>Parc Oberthur</titre>
  <titre>Parc Oberthur</titre>
  <titre>Parc Oberthur</titre>
</parcs_et_jardins_de_Saint_Malo>

Obviously it didn't work for me, but I cannot understand why. The problem is is that the element "commune" can have other towns in it and we didn't want to bring those results into play -- only the ones with Saint-Malo. My XSLT generated the same town over and over -- though the number of elements is the correct number (there are as many elements "titre" as there are mentions of Saint-Malo).
I'd appreciate the help and hope this isn't too confusing.
Answer: Simply replace this....
 <titre><xsl:value-of select="//titre"/></titre>

With this....
<titre><xsl:value-of select="titre"/></titre>

By doing // at the start of the expression, you are searching the whole XML for titre, starting from the document node. So, it will select all titre nodes in the document. In XSLT 1.0, xsl:value-of will only return the value of the first node if multiple nodes are selected.
By doing <xsl:value-of select="titre"/> you are only selecting titre elements that are children of the current properties that you selected with the xsl:for-each.
Do note, if the intention is only to get titre nodes, then instead of doing this...
<xsl:for-each select="//properties[commune='Saint-Malo']">
  <titre><xsl:value-of select="titre"/></titre>
</xsl:for-each>

You can do this, to copy all matching nodes
<xsl:copy-of select="//properties[commune='Saint-Malo']/titre" />

Comment: I feel so silly!! I hope that doesn't mess up my grade a ton lol. I just got finished with a project where I was using "//" and it was working, and so that's why I just didn't understand, but they were definitely different scenarios. I just feel so silly for having not tried without the slashes. Thank you so much and thank you for the explanation!!


GlusterFS : When a node is down the second doesn't take over

Question: I just installed GlusterFS on two nodes it seems working fine the status is up and also the replication is working fine.
But when I stop the node1 volume cluster volume stop glustervol1` or shut down the server to simulate a failure, the second node doesn't take over.
I followed these instructions to install GlusterFS HERE
EDITED
I am using VMware with 7 Vm and CentOS 7.
App-Master : LampStack, Remote DB in Mysql-Master, Storage in Gluster 1.
gluster1:/glustervol1       /home/wordpress/  glusterfs   defaults,_netdev  0  0

App-Slave  : Lampstack, Remote DB in Mysql-Slave, Storage in Gluster 2.
gluster2:/glustervol1       /home/wordpress/  glusterfs   defaults,_netdev  0  0

Mysql-Master : Mysql.
Mysql-Slave  : Mysql (Replication).
Gluster 1    : GlusterFS server where the volume is created.
Gluster 2    : GlusterFS the Replica of Gluster 1.
LoadBalancer : Nginx Load Balancing between App-master & App-Slave
*****INFO*****
172.16.172.147 gluster1
172.16.172.148 gluster2
172.16.172.146 appslave
172.16.172.143 appmaster

Logs From App-Master server
After Switching Off Gluster1
[2016-11-21 16:36:18.532124] W [socket.c:642:__socket_rwv] 0-glusterfs: readv on 172.16.172.147:24007 failed (Connection timed out)
[2016-11-21 16:36:18.532125] W [socket.c:642:__socket_rwv] 0-glustervol1-client-0: readv on 172.16.172.147:49152 failed (Connection timed out)
[2016-11-21 16:36:18.532323] I [MSGID: 114018] [client.c:2042:client_rpc_notify] 0-glustervol1-client-0: disconnected from glustervol1-client-0. Client process will keep trying to connect to glusterd until brick's port is available
[2016-11-21 16:36:31.965015] E [socket.c:2332:socket_connect_finish] 0-glusterfs: connection to 172.16.172.147:24007 failed (No route to host)
[2016-11-21 16:36:31.965141] E [socket.c:2332:socket_connect_finish] 0-glustervol1-client-0: connection to 172.16.172.147:24007 failed (No route to host)

After Turning On Gluster1
[2016-11-21 16:39:02.258175] I [glusterfsd-mgmt.c:1512:mgmt_getspec_cbk] 0-glusterfs: No change in volfile, continuing
[2016-11-21 16:39:02.258595] I [rpc-clnt.c:1851:rpc_clnt_reconfig] 0-glustervol1-client-0: changing port to 49152 (from 0)
[2016-11-21 16:39:02.262348] I [MSGID: 114057] [client-handshake.c:1437:select_server_supported_programs] 0-glustervol1-client-0: Using Program GlusterFS 3.3, Num (1298437), Version (330)
[2016-11-21 16:39:02.299637] I [MSGID: 114046] [client-handshake.c:1213:client_setvolume_cbk] 0-glustervol1-client-0: Connected to glustervol1-client-0, attached to remote volume '/bricks/brick1/brick'.
[2016-11-21 16:39:02.299714] I [MSGID: 114047] [client-handshake.c:1224:client_setvolume_cbk] 0-glustervol1-client-0: Server and Client lk-version numbers are not same, reopening the fds
[2016-11-21 16:39:02.300513] I [MSGID: 114035] [client-handshake.c:193:client_set_lk_version_cbk] 0-glustervol1-client-0: Server lk version = 1

After Switching Off Gluster2
[2016-11-21 16:41:33.394122] C [rpc-clnt-ping.c:161:rpc_clnt_ping_timer_expired] 0-glustervol1-client-1: server 172.16.172.148:49152 has not responded in the last 42 seconds, disconnecting.
[2016-11-21 16:41:33.394943] E [rpc-clnt.c:362:saved_frames_unwind] (--> /lib64/libglusterfs.so.0(_gf_log_callingfn+0x186)[0x7fd4ad63c906] (--> /lib64/libgfrpc.so.0(saved_frames_unwind+0x1de)[0x7fd4ad40792e] (--> /lib64/libgfrpc.so.0(saved_frames_destroy+0xe)[0x7fd4ad407a3e] (--> /lib64/libgfrpc.so.0(rpc_clnt_connection_cleanup+0x9c)[0x7fd4ad4093fc] (--> /lib64/libgfrpc.so.0(rpc_clnt_notify+0x88)[0x7fd4ad409c08] ))))) 0-glustervol1-client-1: forced unwinding frame type(GlusterFS 3.3) op(LOOKUP(27)) called at 2016-11-21 16:40:50.706048 (xid=0x59e)
[2016-11-21 16:41:33.394973] W [MSGID: 114031] [client-rpc-fops.c:2971:client3_3_lookup_cbk] 0-glustervol1-client-1: remote operation failed. Path: / (00000000-0000-0000-0000-000000000001) [Transport endpoint is not connected]
[2016-11-21 16:41:33.395188] E [rpc-clnt.c:362:saved_frames_unwind] (--> /lib64/libglusterfs.so.0(_gf_log_callingfn+0x186)[0x7fd4ad63c906] (--> /lib64/libgfrpc.so.0(saved_frames_unwind+0x1de)[0x7fd4ad40792e] (--> /lib64/libgfrpc.so.0(saved_frames_destroy+0xe)[0x7fd4ad407a3e] (--> /lib64/libgfrpc.so.0(rpc_clnt_connection_cleanup+0x9c)[0x7fd4ad4093fc] (--> /lib64/libgfrpc.so.0(rpc_clnt_notify+0x88)[0x7fd4ad409c08] ))))) 0-glustervol1-client-1: forced unwinding frame type(GF-DUMP) op(NULL(2)) called at 2016-11-21 16:40:50.706053 (xid=0x59f)
[2016-11-21 16:41:33.395201] W [rpc-clnt-ping.c:204:rpc_clnt_ping_cbk] 0-glustervol1-client-1: socket disconnected
[2016-11-21 16:41:33.395211] I [MSGID: 114018] [client.c:2042:client_rpc_notify] 0-glustervol1-client-1: disconnected from glustervol1-client-1. Client process will keep trying to connect to glusterd until brick's port is available

After Turning On Gluster2
[2016-11-21 16:41:45.255081] E [socket.c:2332:socket_connect_finish] 0-glustervol1-client-1: connection to 172.16.172.148:24007 failed (No route to host)

NB : The Failover worked even even if Gluster1 or Gluster2 was down the App kept working.
Answer: This isn't exactly how GlusterFS works, as it doesn't "fail over". No single node acts as a master, as GlusterFS is masterless. The client is responsible for connecting to all Gluster peers, and it's the client that must maintain network visibility to servers in order to maintain sane volume activity. Inter-node communication is usually only used during volume heal operations and for negotiating peer trust.
If you're following that guide, I'm assuming you've created a replica 2 gluster volume from two bricks. What does your configuration look like, and what does the overall network look like that's connecting these Gluster nodes together, as well as what's connecting them to the clients? Most problems with Gluster have to do with client to server communication problems.
Comment: information added up
Comment: What do you mean by saying your app master has storage in Gluster 1 while your app-slave is in Gluster 2? They should both be in Gluster 1 and 2, and should be accessing them simultaneously. It's the *clients* that maintain volume replicas. Gluster 2 is not a replica of Gluster 1, they are replicas of each other and are read / written completely simultaneously.

A two node replica 2 Gluster volume doesn't have any concept of quorum, automatic self-heal, or read-only service freeze on peer loss. This isn't great for consistency, but it does stay up on a node failure.
Comment: Also, what exactly do you mean when you say that the second Gluster node doesn't take over? What is the exact failure, and what do your logs look like during this failure?
Comment: I added the fstab entry for each server to know where is each one storage.
All the write is done on Appmaster/Gluster1 and AppSlave/Gluster2 is the replica of the AppMaster To loadBalance the charge between them and in case 1 is down the second take the relay.

I mean by "Gluster node doesn't take over" that when I switch off a node the second doesn't replace it like when u have LoadBalancing if u switch 1 server the second keep taking all the charge.
Comment: You're still not describing your failure beyond stating that you have one. What do your logs read? They're in `/var/log/gluster/`, and in `dmesg`. Also, GlusterFS should not be behind a load balancer, so be sure you're not using load balancer VIPs for it. Gluster expects its IP addresses to not change or float.
Comment: Logs added, and seems the problem was resolved alone !
Answer: Obviously you forgot a parameter
you should add backupvolfile-server for mounts
example:
gluster1:/glustervol1       /home/wordpress/  glusterfs   defaults,_netdev,backupvolfile-server=gluster2  0  0


Arquivo php que cria html, como faço pra informação contida vir do banco de dados?

Question: Como faço para o html criado por esse php ao inves de conter o texto entre as aspa, ele contenha uma informação que vem do meu banco de dados.
<?php
# Nome do arquivo html
$pagename = "pastatest/paginahtml.html";

# Texto a ser salvo no arquivo
$texto = "
texto que vai conter no html
";

#Criar o arquivo
$fp = fopen($pagename , "w");
$fw = fwrite($fp, $texto);

#Verificar se o arquivo foi salvo.
if($fw == strlen($texto)) {
   echo 'Arquivo criado com sucesso!!';
}else{
   echo 'falha ao criar arquivo';
}
?>

Comment: @cadeira13 Se possível [edite](http://pt.stackoverflow.com/posts/153302/edit) a pergunta e coloque o código que faz a conexão, e também o `select ..` que você quer salvar no arquivo. Veja também o **[tour]**!.
Comment: Já fez a conexão com o banco de dados? essa é a parte que tem dúvida??
Comment: não eu ja tenho a conexão com banco de dados, meu problema é com select from, só que como pode ver a variavel $texto só mando pro aquivo criado o texto que tiver entre as " " e quero que esse texto no caso venha do banco de dados
Answer: Faça um SELECT
<?php
# Nome do arquivo html
$pagename = "pastatest/paginahtml.html";

# Pega texto no Banco de dados

$query = $conn->prepare("SELECT * FROM sua_tabela WHERE id='1'"); //Em id vc coloca qual registro do banco de dados você quer pegar.
$query->execute();

$row = $query->fetch(PDO::FETCH_ASSOC);

# Texto a ser salvo no arquivo
$texto = "
".$row['texto']."
";

#Criar o arquivo
$fp = fopen($pagename , "w");
$fw = fwrite($fp, $texto);

#Verificar se o arquivo foi salvo.
if($fw == strlen($texto)) {
   echo 'Arquivo criado com sucesso!!';
}else{
   echo 'falha ao criar arquivo';
}
?>

O SELECT eu fiz com base em uma conexão PDO. Faça uma query de acordo com sua conexão com o Banco de dados (MySQL, MySQLi, PDO, etc.)
Comment: gente eu fiz alguma coisa errada ta dando esse erro >> Fatal error: Call to a member function prepare() on a non-object in C:\AppServ\www\test\criar.php on line 21
Comment: @cadeira13 você primeiro tem que criar uma conexão PDO e atribui-lá a variavel $conn
Comment: sim eu ja consegui rsrs criei aqui a conexão pdo, deu tudo certo obgd
Answer: O arquivo usando mysql, ficará assim:
<?php
# Nome do arquivo html
$pagename = "pastatest/paginahtml.html";

# Texto a ser salvo no arquivo
$selecionar = "SELECT * FROM tabela";
$conectar = mysql_query($selecionar);
$array = mysql_fetch_array($conectar);
$texto = $array['texto'];

#Criar o arquivo
$fp = fopen($pagename , "w");
$fw = fwrite($fp, $texto);

#Verificar se o arquivo foi salvo.
if($fw == strlen($texto)) {
   echo 'Arquivo criado com sucesso!!';
}else{
   echo 'falha ao criar arquivo';
}
?>

Nota: mysql é obsoleto. PDO ou mysqli são mais recomendados.
Comment: gente obrigado pela resposta, fiquei satisfeito obgd
Comment: se puderem me enviar conexão com a db estou usando essa em PDO `$host = "localhost";
$db   = "devmedia";
$user = "root";
$pass = "88319076";
// conecta ao banco de dados
$con = mysql_pconnect($host, $user, $pass) or trigger_error(mysql_error(),E_USER_ERROR);
// seleciona a base de dados em que vamos trabalhar
mysql_select_db($db, $con);`


Calculating probability

Question: If $f(x,y)=2x , 0\leq x\leq 1 ,0\leq y\leq 1 $, find $ P(Y < e^{-X} \cap X > Y)$ Given X and Y have joint distribution.
Here is my approach:
$$ P(Y < e^{-X} \cap X > Y) =  1-  P(Y > e^{-X} \cap X > Y)$$
= $1- P(X > Y > e^{-X})$ = $P(e^{-X} \leq Y \leq X )$
=$ \int_0^1\int_{e^{-x}}^x2x dydx $
=  $2e^{-1} - \frac{1}{3}$
Is my solution for this problem correct?
Thanks!
Comment: (1) Presumably $f$ is a bivariate probability density function. (2) The question asks for a probability, which (by definition) is a *number.* The answer you propose depends on some undefined variable "$x$": this makes no sense. (3) The answer is fairly nasty: it will help to write it in terms of the number $x$ satisfying $x = \exp(-x)$. If this is a probability homework problem, it seems to miss the pedagogical mark by requiring the evaluation of such an integral. Are you sure you copied it correctly?
Comment: It is still unclear what "$x$" is: in "$P(Y\lt e^{-x}\ldots)$" is it a typo for "$X$" or is $x$ some constant independent of the random variables $X$ and $Y$?
Comment: That was implied by introducing $f$, assuming it is the PDF of the joint distribution.
Comment: This would seem to fall under [self-study](http://stats.stackexchange.com/tags/self-study/info). Please review the tag wiki info and add the tag (or if it doesn't apply, would you mind explaining how the question arises, please). There's no difficulty though - you seem to be following what it asks for in any case.
Comment: @whuber I missed to mention that X & Y are jointly distributed, which I corrected in the question now.
Comment: @whuber I think what I missed in my solution is that I need to double integrate it wrt to x and y. But I am not understanding why I need to do it, is it because it is bivariate.
Comment: @whuber & Glen_b I have updated the question and also my solution.
Answer: An event for a bivariate random variable $(X,Y)$ is any set of possible outcomes to which a probability can meaningfully be assigned.  Examples are the set of outcomes $(x,y)$ such that $y\lt e^{-x},$ the set for which $x\gt y,$ and their intersection (about which the question is concerned).
The probability of any event is the volume under the graph of $f$ subtending that event.  We can draw a picture of this probability:

The open (dark yellow) chamber is bounded at the bottom by $y=0$, on the right by $x=1$, on the upper right by $y=e^{-x}$, on the upper left by $y=x$, and above by the graph of $f$.  The rest of the graph of $f$ is shown in dark blue with a mesh.
The calculation of this volume can be carried out in two parts: first, the integral over $x=0$ to $x=x_0$ where $(x_0, x_0) = (x_0, e^{-x_0})$ is the point at which the two graphs $y=x$ and $y=e^{-x}$ intersect.  ($x_0\approx 0.567$.)

Second, the integral from $x=x_0$ to $x=1$.

The probability is
$$\int_0^{x_0} \int_0^x 2x\ dy dx + \int_{x_0}^1\int_0^{e^{-x}} 2x\ dy dx$$
$$= 2\frac{x_0^3}{3} + 2\left(\frac{2}{e} + x_0 + x_0^2\right)$$
$$\approx 0.427687.$$
Notice this differs from $2/e - 1/3\approx 0.402426.$

With problems like this it can be helpful (and often insightful) to double-check one's answer with a simulation.  This requires us to write code to draw values of $(X,Y)$ from the specified distribution.  In this case, notice that $Y$ has a uniform distribution independent of $X$ and that the distribution function of $X$ (for $0\le x \le 1)$
$$F_X(x) = \int_{0}^x\int_{0}^{1} f(t,y)\ dy dt = x^2.$$
Therefore, since the inverse of $F_X$ is the square root (restricted to arguments between $0$ and $1$), $X$ is distributed as the square root of a uniform distribution.
The following R code generates ten million independent realizations of $(X,Y)$.  It estimates the desired probability as the fraction of realizations in which the event occurs.  It also computes its standard error:
n<- 10^7                  # Number of realizations
set.seed(17)              # Allows this calculation to be reproduced
x <- sqrt(runif(n))       # The X values
y <- runif(n)             # The Y values
i <- y < exp(-x) & x > y  # Indicator of the event
mean(i)                   # Estimated probability
sd(i) / sqrt(length(i))   # Standard error of the estimate

After $1.7$ seconds of computation, this simulation yields a probability estimate of $0.42769$ with a standard error of $0.00016$.
(This simulation could be made several times faster, but it does the job in reasonable time and has the merit of being such a direct translation of the original question that it evidently is correct code.)
Doing this simulation would have cast strong doubt on the validity of $0.4024$ as an answer, because that is $160$ standard errors too low (and more than three SEs would be suspicious).  Indeed, even $0.4291$ is suspicious because it is $9$ SEs higher than the estimate.  In contrast, the answer developed here ($0.427687$) differs from the estimate by only $0.03$ standard errors: it is bang on.
Comment: Significantly better than the answer I was just working on.
Comment: @whuber Thanks for the beautiful explanation. I just finished the problem and saw the answer posted by you. I took the similar approach by drawing it in 2 dimensional plane and looking for regions for range of x and y. I am now able to see that earlier solution was wrong as I missed the fact that the region involves two curves. My answer, with correct approach, is 0.4291 (which is close to yours).

Calculating probability


Como usar Google Chart radar?

Question: Tenho um gráfico e gostaria de faze-lo ficar como na imagem. (duas ou mais linhas)

Já tenho o seguinte código:

http://jsfiddle.net/05g2nw0r/
Answer: Pra adicionar mais linhas basta ir adicionando valores a cada item do data provider. Por exemplo:
<code>"dataProvider": [ {
    "name": "Item 1",
    "value": 5,,
    "novoNome": "Novo Item 1",
    "novoValor": 2
}
</code>
E onde você define o "graph", adiciona mais um item no array:
<code>"graphs": [ {
        "balloonText": "[[name]] : [[value]]",
        "bullet": "round",
        "valueField": "value"
      } ,
      {
        "balloonText": "[[novoNome]] : [[novoValor]]",
        "bullet": "round",
        "valueField": "novoValor"
       } ],
</code>
Aqui tem um fiddle de exemplo funcionando.
Comment: consegue colocar legenda?
Comment: Dá uma olhada na documentação deles, lá tem tudo o que você está precisando fazer: http://docs.amcharts.com/3/javascriptcharts/AmLegend
Comment: blz, só que esse chart não é do google... ele teria algo do tipo?
Comment: Ainda não cheguei a usar o do Google (quando precisei usar, o projeto em que eu estava trabalhando ja tinha uma implementação com uma API de terceiros), mas pelo fiddle que você colocou pareceu que estava usando o amcharts.
Comment: sim, eu estava usando o amcharts, mas gostaria de usar o Google Charts... Já olhei na documentação, mas não consegui implementar nada.

Como usar Google Chart radar?


How to open the Watch Window in Visual Studio 2019

Question: I search on Google about "Visual Studio 2019 Watch Window". It tells me that open the Watch Window by the menu sequence Debug > Windows > Watch. However there is no an Watch item in the Windows menu. Can anybody tell me how to open the Watch window?
Comment: Run it. Then `CTRL+ALT+W + 1,2,3,4`. Or open the Menu. Or pin it.
Answer: button becomes visible when in debug mode, debug> window> watch
Answer: Add a breakpoint in your code, and then click "start debugging(F5)". Then Select DEBUG -> Windows -> Watch
Have you already started debugging? The watch window option is only visible under DEBUG -> Windows during debugging (debugger must be running or in break mode).


ActiveMQ cannot receive my message

Question: Hi i've added this WebListener class to my webproject
<code>@WebListener
public class SelfSend implements ServletContextListener {

    private MessageProducer producer;
    private Connection sendconnection;
    private Connection receiveconnection;
    private Session sendsession;
    private Session receivesession;
    private MessageConsumer receiver;

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        try {
            InitialContext initCtx = new InitialContext();
            ConnectionFactory connectionFactory = (ConnectionFactory) initCtx.lookup("java:comp/env/jms/ConnectionFactory");
            sendconnection = connectionFactory.createConnection();
            receiveconnection = connectionFactory.createConnection();
            sendsession = sendconnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            receivesession = receiveconnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            producer = sendsession.createProducer((Destination) initCtx.lookup("java:comp/env/jms/queue/MyQueue"));
            receiver = receivesession.createConsumer((Destination) initCtx.lookup("java:comp/env/jms/queue/MyQueue"));
            receiver.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    System.out.println("MESSAGE RECEIVED");

                }
            });
            TextMessage testMessage = sendsession.createTextMessage();
            testMessage.setStringProperty("from", "ki");
            producer.send(testMessage);
            System.out.println("MESSAGE SENT");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

    }

}
</code>
But the message is never received.
When i put the reciver in a @WebServlet like this
<code>@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    try {
        InitialContext initCtx = new InitialContext();
        ConnectionFactory connectionFactory = (ConnectionFactory) initCtx.lookup("java:comp/env/jms/ConnectionFactory");
        connection = connectionFactory.createConnection();
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        receiver = session.createConsumer((Destination) initCtx.lookup("java:comp/env/jms/queue/MyQueue"));
        receiver.setMessageListener(this);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    mud = new MongoUserdata();
}
</code>
i recive the message, when i put it in both i receive only every second message with the Servlet-Receiver, the other messasge seems to be lost.
Can anyone explain theis odd behaviour to me?
Answer: In your first example class you don't appear to be starting the receiver connection which would mean it will not dispatch any messages that are received.  It will however hold onto incoming messages in the consumer prefetch buffer leading to the every other message receive that you are experiencing.

ActiveMQ cannot receive my message


Defining a Complex Sort (by stripping out a pre-defined set of words) with Views

Question: I'd like to do a more complex sorting on my Drupal 7 View. Specifically, I'd like to sort by a particular field alphabetically (easy - that's the default). However, before the View sorts the field I want it to strip out (a predefined) set of words at the beginning of the field (if they exist) such as the word 'the' or 'a' and sort based on the words that follow.
Does anyone know if this is possible?
My workaround will be to just create a 'sort by' field in the content type.
Comment: +1 Good question. It can be done in MySQL using temporary column at query time: [MySQL Sort Alphabetically but Ignore "The"](http://stackoverflow.com/questions/9087603/mysql-sort-alphabetically-but-ignore-the). Interesting to see if there will be a good answer to this.
Comment: Thanks for the suggestion - it's a good idea. I'll try the given answer first and if that doesn't meet our needs this is a good workaround.
Answer: Have you tried Views Natural Sort -module?

Provides a views filter that sorts node titles by a more natural manner by ignoring articles like "The" and "A."

Not sure if it matches your needs because of "sorts node titles" and in your question you talk about particular field. But maybe you should try it?
At least you can get base for custom module if you need to build one.
Comment: +1 This post explains how to enable natural sort for fields: [How to use Views Natural Sort 2.0](http://generalredneck.com/blog/how-use-views-natural-sort-20)
Comment: Love this - looks like it will almost perfectly meet our needs.


Animation with CSS selector not working

Question: My HTML:

        <input type='email' name='email' class='input animate' value='' placeholder='E-mail'>
        <input type='submit' id='submit' class='submit animate' value='>'>

My CSS:
.animate { -webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; }

html body div.body-container form div#composite-field {
            position: relative; float: left;
            width: 80%; height: 100px; margin: 0 10%; padding: 0;
        }

        html body div.body-container form div#composite-field input[type=email] {
            float: left;
            width: 90%; height: 100px; margin: 0; padding: 0 6% 0 4%;

            border: 0; outline: none;
            -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px;
            background-color: #eab94e; color: rgba(26, 60, 88, 0.9);

            z-index: 10;
        }

        html body div.body-container form div#composite-field input[type=submit] {
            position: absolute; float: none; clear: both; top: 0; right: 5%;
            min-width: 80px; width: auto; height: 100px; margin: 0; padding: 0;

            border: 0; border-radius: 0; outline: none; -webkit-appearance: none;
            background-color: #2e4856; color: #eab94e;
            z-index: 11;
        }

        html body div.body-container form div#composite-field input[type=email],
        html body div.body-container form div#composite-field input[type=submit] { font-family: "Fjalla One", sans-serif; font-weight: 400; font-size: 40px; letter-spacing: normal; }

        html body div.body-container form div#composite-field input[type=email]:focus {
            box-shadow: inset 0 0 0 5px rgba(26, 60, 88, 0.9);
        }

        html body div.body-container form div#composite-field input[type=submit]:hover { opacity: 0.5; }

Now problem is here, the width of 20% doesn't get animated. It worked before. And I can't seem to figure out why it's not now...
html body div.body-container form div#composite-field input[type=email]:focus ~ input[type=submit] { width: 20%; }

Do I have an error with my css somewhere?
Thanks.
Comment: Do you have the initial width defined?
Answer: The issue is that your submit button had a width of "auto", that was transitioning to 80% (the width was only set with min-width). If you set a width on it, the transition will work. Here's a fiddle:
http://jsfiddle.net/znm63rky/15/
html body div.body-container form div#composite-field input[type=submit] {
    width: 80px;
}

Animation with CSS selector not working


Let Q be a random point in the unit circle. Let Z=distance from Q to (-1,0) and T the distance from (1,0). What is Cov(Z,T)?

Question: The question hints that we need to use angles since there is no joint denstity, i.e.:
Let $T=h(\theta)$ and $Z=g(\theta)$
I know in general that:
$$ Cov(X,Y)= E[XY]-E[X]E[Y]$$
But I'm not sure how to use the information they gave me for this question.
Comment: The coordinate of $Q$ is $(\cos\Theta, \sin\Theta)$ and hence you can express $T, Z$ as a function of $\Theta$.The distribution of $\Theta$ maybe assumed as uniform on $[0, 2\pi]$, I guess as it is not specified in the question.
Comment: You should update your question to include that.
Comment: Is this ON or IN the unit circle?  Does it include the points having radius < 1?
Comment: @FelixCastor on the unit circle
Comment: If IN the unit circle, the answer involves elliptic integrals.
Comment: Related: http://math.stackexchange.com/questions/1181357/can-the-following-triple-integral-be-computed-via-elementary-calculus-methods
Answer: Let $L=(-1,0),R=(1,0)$, $O=(0,0)$, the center, and  $M$ the random point on the circle. WLOG assume $M$ is on the upper semicircle. Note the picking the point uniformly is equivalent to sampling  $\theta =\angle ROM$ uniformly over $[0,\pi]$.
Write $X$ for the length of $LM$ and $Y$ for the length of $RM$.

Observation:  $\angle LMR$ is a right angle. Indeed, let $\alpha = \angle RLM$ and $\beta = \angle LRM$. Since the triangles $MOL$ and $MOR$ are each an isosceles, it follows that $\angle LMR=\alpha+\beta$.  But then
$$180^{\circ} =
\angle RLM+\angle LRM+ \angle LMR=\alpha +\beta + (\alpha+\beta) = 2 (\alpha+\beta).$$
Corollary: $XY$ is twice the area of the triangle $LMR$.
Twice area of $LMR$ is also given by the length of its base $LR$ times its height. This is easy to compute. Base is $LR$ and has length $2$, and the  height is equal to $\sin \theta$. Thus,
$$ E[XY ] =2 E[ \sin \theta ] =2 \frac{1}{\pi} \int_0^{\pi}\sin (\theta)d \theta =  \frac{4}{\pi}.$$
Next find $E[X]$ and $E[Y]$. Because of symmetry, $E[X]=E[Y]$. By looking at the triangle $MOR$, we see that $Y= 2 \sin (\theta/2)$. Therefore,
$$ E [ Y ] = \frac{2}{\pi} \int_0^\pi \sin (\theta /2) d \theta = \frac{4}{\pi}\int_0^{\pi/2}\sin (t) dt = \frac 4 \pi. $$
Final calculation:

$$ \mbox{Cov} (X,Y) = E [XY] - E[X] E[Y] = \frac{4}{\pi} (1- \frac{4}{\pi}).$$


Como alterar o atributo de um objeto recebido por parâmetro em um método?

Question: Estou tentando implementar um exemplo bem simplório de utilização de classes na linguagem C++. Bem, resumindo, existem dois objetos (cliente1 e cliente2), que representam duas contas bancárias. Dentro da classe Conta, há um método transferir(), responsável, claro, por realizar a transferência entre essas duas contas.
Bem, o problema é que eu não consigo atualizar o valor do saldo da conta que recebe a transferência.
No exemplo do código, a conta 'Pedro Gonçalves' deveria possuir o saldo final de 1000, no entanto, o saldo permanece inalterado (450), mesmo após a transferência. O objeto é passado como parâmetro no método transferir.
Eu tentei alterar o atributo saldo desta conta através do setter que eu defini, mas não funciona.
Alguém pode indicar os meus erros?
<code>#include <iostream>
#include <iomanip>

using namespace std;

class Conta{
    private:
        string nome, cpf, rg;
        float saldo;
    public:
        void setDados(string a, string b, string c, float s){
            nome = a;
            cpf = b;
            rg = c;
            saldo = s;
        }
        void setSaldo(float s){
            saldo = s;
        }
        string getNome(){
            return nome;
        }
        string getCpf(){
            return cpf;
        }
        string getRg(){
            return rg;
        }
        float getSaldo(){
            return saldo;
        }

        void transferir(Conta dest, float valor){
            if(saldo >= valor){
                //O saldo da conta atual possui valor de transferência subtraído.
                saldo -= valor;

                float saldo_destino = dest.getSaldo();
                //O saldo da conta destino é incrementado com o valor da transferência.
                saldo_destino += valor;

                dest.setSaldo(saldo_destino);

                cout << "Transferência realizada com sucesso." << endl;
            }
            else
                cout << "Saldo insuficiente para realizar a operação" << endl;
        }
};

int main(void){
    Conta cliente1, cliente2;

    cliente1.setDados("Pedro Gonçalves", "123456", "1", 450.00);
    cliente2.setDados("João Santos", "654321", "2", 1550.00);

    cliente2.transferir(cliente1, 550);

    cout << fixed << setprecision(2);
    cout << cliente1.getNome() << " possui saldo de R$" << cliente1.getSaldo() << endl;
    cout << cliente2.getNome() << " possui saldo de R$" << cliente2.getSaldo() << endl;
}
</code>
Comment: Tem diversos problemas nesse código, mesmo resolvendo essa questão ainda terá um código ruim em mãos.
Comment: Ajudou bastante. Obrigado!
Answer: O que você quer é passar o objeto para o método por referência, isto é passando o endereço na memória para o objeto, em vez de passá-lo por valor como está escrito no seu código, onde o método copia o valor do objeto em outro objeto e as alterações nos dados no novo objeto criado pelo método não surtirão efeito no objeto que foi passado na chamada da função.
Para resolver isso você pode utilizar apontadores.
Seu método reescrito ficaria assim:
<code>        void transferir(Conta* dest, float valor){
            if(saldo >= valor){
                //O saldo da conta atual possui valor de transferência subtraído.
                saldo -= valor;

                float saldo_destino = dest->getSaldo();
                //O saldo da conta destino é incrementado com o valor da transferência.
                saldo_destino += valor;

                dest->setSaldo(saldo_destino);

                cout << "Transferência realizada com sucesso." << endl;
            }
            else
                cout << "Saldo insuficiente para realizar a operação" << endl;
        }
</code>
E na chamada para a função, tendo em vista que o objeto cliente1 não é um apontador, você passaria o endereço na memória dele, dessa forma:
<code>cliente2.transferir(&cliente1, 550);
</code>
Comment: Era exatamente isso que eu precisava, Raphael! Eu, na verdade, tinha feito isso com a utilização de ponteiros, mas recebi alguns problemas no momento da compilação. Foram resolvidos. Grato!


How do I expand Project Explorer to the bottom of my eclipse screen?

Question: I recently had to delete all my projects in eclipse and re-import them, and it messed up the view organization I had (I had never realized I could save a view until now). I want to use the Team Synchronizing Perspective in Eclipse, but I want the Project Explorer section to go to the bottom of the screen.
for example, in the Java perspective,

The package explorer goes to the bottom of the screen. but on the Team Sync Perspective, that I want to stay on, I can't get the Project explorer view to go to the bottom of the screen (and I know one is the package and one is the project explorer, I tried adding package explorer to the sync perspective and it also doesn't show up how I want).
Team Sync Perspective:

Does anyone know how to do what I'm asking? I've googled plenty and can't find the answer. I'm assuming it's simple and I just can't find the steps...
Answer: See this animated gif to rearrange views in a perspective. Left click on view's title bar and drag and drop the view wherever you need it.

Refer this help guide
Comment: you're amazing, thank you! I knew you could re-arrange them, but didn't realize it was kind of like a puzzle of re-arranging the bottom section off to the side so that the project explorer on the left could expand down.


How can I use HTTPS with *.domain.com AND domain.com?

Question:
Possible Duplicate:
How to have a certificate which works with both example.com and subdomain.example.com in IIS?

I've been looking for a solution to the following problem for a few days now.
I have domain.com for which I have bought and installed a wildcard certificate so now I can provide secure access to www.domain.com or whatever.domain.com. This works.
However, even though the application thar runs on these subdomains makes sure no one gets to visit an URL that doesn't contain at least www as the subdomain, you can still delete the www part.
Once you do that no serverside redirects will help if you are on https because the browser will not fulfil the request because the wildcard ssl certificate will not cover the naked domain (domain.com)
So my question is this:

Can I get a wildcard ssl from a provider that will also cover the naked domain? Is that even possible?
If no for 1 above, if I purchase a basic SSL cert for domain.com will I be able to install it (Apache) on the same server and same IP as the wildcard one is installed on?
If answer is No for both and 1 and 2 what are my options? I find it really annoying that securing a domain AND it's subdomains is that complicated :)

[EDIT]: Forgot to mention that of course I would prefer and option with no costs involved, but if that's not possible, then I guess I would prefer number 2 because the costs for a basic SSL cert are lower then for a new Wildcard one.
Thank you.
Answer: Yes, you can have more than one domain name covered by a certificate. It can be done with the "Subject Alternative Name" x509v3 extension:
<code>X509v3 Subject Alternative Name:
     DNS:*.mydomain.example, DNS:mydomain.example
</code>
Certificates issued by StartSSL do that automatically (with them, the difficult thing is not to have the top-level included)


Por que o Google Chrome acusa que está faltando jquery.min.map?

Question: Baixei a versão do jQuery 1.10.1 minimizado e o Google Chrome está alertando nas ferramentas para desenvolvedor, aba Network, que jquery.min.map não foi encontrado: erro 404
Observação: O jQuery funciona corretamente.
Esse jquery.min.map é uma nova dependência para usar jQuery?
Comment: Isso só acontece no Google Chrome?
Answer: O arquivo minificado perde informações que podem ser úteis no momento de exibir detalhes de um erro, como o backtrace. O JQuery vem com um arquivo .map que dá essa informação adicional ao navegador, de forma que você pode usar a biblioteca minificada e, ao mesmo tempo, não ver mensagens incompreensíveis de erro.
Se você está em um ambiente de produção, o arquivo .map não é necessário, afinal, é esperado que nenhum erro ocorra. Use apenas durante o desenvolvimento.
jquery-1.10.1.min.map
Comment: No caso do *Google Chrome* você pode abrir as *Ferramentas do Desenvolvedor* (F12), abrir as configurações (ícone no cando inferior direito) e desmarcar "Enable JS source maps". O arquivo será usado apenas para exibir informações nesse painel e não apresenta nenhum efeito na página para o usuário final.
Comment: Mas este arquivo só é requisitado quando ocorrem erros?
Answer: Um arquivo .map permite mapear um arquivo javascript minimizado (minified) para o arquivo original. Então podemos depurar uma página web sem precisar alterar o sistema no servidor, ou seja:

Sem mais gambiarras para colocar o jQuery original em modo "desenvolvimento" e o jQuery min em modo produção
O código executado no navegador continua sendo o minified, mas você consegue ver o trecho orignal equivalente de forma que pode entender o que está acontecendo

Existem outros detalhes, vantagens e aplicações que podem ser lidos no artigo Introduction to JavaScript Source Maps.
Quanto ao Chrome, ele tenta baixar o mapa sempre que encontra uma referência no arquivo javascript. Exemplo:
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery-1.10.2.min.map
*/

Para evitar os erros, remova o trecho do arquivo Javascript ou desabilite este recurso do navegador através da opção Enable Source Maps, conforme a imagem abaixo (extraído do artigo citado):