How to do one-class text classification?

Question: I have to deal with a text classification problem. A web crawler crawls webpages of a certain domain and for each webpage I want to find out whether it belongs to only one specific class or not. That is, if I call this class Positive, each crawled webpage belongs either to class Positive or to class Non-Positive.
I already have a large training set of webpages for class Positive. But how to create a training set for class Non-Positive which is as representative as possible? I mean, I could basically use each and everything for that class. Can I just collect some arbitrary pages that definitely do not belong to class Positive? I'm sure the performance of a text classification algorithm (I prefer to make use of a Naive Bayes algorithm) highly depends on which webpages I choose for class Non-Positive.
So what shall I do? Can somebody please give me an advice? Thank you very much!
Comment: This is in fact two class clustering since you have two classes. For one class you would have only one class and would be interested in assessing how well does your observations fit the data (i.e. detecting outliers).
Comment: This learning problem has a name - PU learning. This is naturally to be used if positive examples are easy or natural to get but negatives are basically everything rest (difficult to get). In principle you want to learn a standard two class classifier but with a different criteria - optimize the area under PR curve. This software package allows you to train such a classifier https://code.google.com/p/sofia-ml/
Answer: The Spy EM algorithm solves exactly this problem.

S-EM is a text learning or classification system that learns from a set of positive and unlabeled examples (no negative examples). It is based on a "spy" technique, naive Bayes and EM algorithm.

The basic idea is to combine your positive set with a whole bunch of randomly crawled documents.  You initially treat all the crawled documents as the negative class, and learn a naive bayes classifier on that set.  Now some of those crawled documents will actually be positive, and you can conservatively relabel any documents that are scored higher than the lowest scoring true positive document.  Then you iterate this process until it stablizes.
Comment: Thanks a lot, that sounds quite promising. I'll take a look into it.
Answer: Here is a good thesis about one-class classification:

Tax, D. M.: One-class classification - Concept-learning in the absence of counter-examples, PhD thesis, Technische Universiteit Delft, 2001. (pdf)

This thesis introduces the method of Support Vector Data Description (SVDD), a one-class support vector machine that finds a minimal hypersphere around the data rather than a hyperplane that separates the data.
The thesis also reviews other one-class classifiers.
Comment: Welcome to the site, @nub. We hope to build a permanent repository of statistical information, as such, we worry about the possibility of linkrot. Would you mind giving a summary of the info in that thesis in case the link goes dead?
Comment: Thank you for summarizing. Please register & merge your accounts (you can find out how in the **My Account** section of our [help]), then you will be able to edit & comment on your own posts.
Comment: @gung Thanks for the welcome.  I'm thrilled to have received "Yearling" badge on StackOverflow itself, so now I can comment everywhere.
Comment: @JosiahYoder, if you are the OP here, please merge your accounts. You can find out how in the **My Account** section of our [help].
Comment: I'm not the OP. Just a random SO user who happened across this question.
Answer: Good training requires data that provides good estimates of the individual class probabilities.  Every classification problem involves at least two classes.  In your case the second class is anyone that is not in the positive class.  To form a good decision boundary using Bayes or any other good method is best done with as much training data randomly selected from the class.  If you do non random selection you might get a sample that doesn't truly represent the shape of the class conditional densities/distributions and could lead to a poor choice of the decision boundary.
Comment: You are right, this is exactly what bothers me. How to select a sample of _non-positive_ samples that leads to a good decision boundary? Is doing a random selection the best I can do?
Answer: I agree with Michael.
Regarding your question about random selection; yes:  you have to select randomly from the complementary set of your 'positives'.  If there is any confusion that it is possible that your 'positives' are not fully defined as 'pure positive', if I may use that phrase, then you can also try at the least some kind of matched definition for positives so that you will control on those variables that are generating potentially some contamination on the definition of 'positive'.  In this case you have to correspondingly match on the same variables on the 'non-positive' side also.
Answer: An article that may be of interest is:

"Extended nearest shrunken centroid classification: A new method for
  open-set authorship attribution of texts of varying sizes", Schaalje,
  Fields, Roper, and Snow.  Literary and Linguistic Computing, vol. 26,
  No. 1, 2011.

Which takes a method for attributing a text to a set of authors and extends it to use the possibility that the true author is not in the candidate set.  Even if you don't use the NSC method, the ideas in the paper may be useful in thinking about how to proceed.


Forcing user in both directions using bindfs

Question: I have a specific OS user called 'app' which runs Dropbox. The app is deployed (in the same server) for multiple sites. But the Dropbox of the 'app' user has info about all sites.
The dropobox has a directory like /home/app/Dropbox/Sites/siteXXX/folder one for each site. All Dropbox folder is automatically created with the OS user 'app'.
However, each installation of the app uses an internal folder of the dropbox. For example:  /app/sites/siteXXX/siteData/shared/folder. Each instance of the app runs with a particular OS user, for example 'siteXXX'. The problem is that I want all /app/sites/siteXXX/siteData/shared/folder to be 700 and with ownership siteXXX. The app can create or edit new files. In addition, Dropbox user 'app' should continue to be able to sync....
So...to solve this I installed bindfs and added this to the fstab:
/home/app/Dropbox/Sites/siteXXX/folder /app/sites/siteXXX/siteData/shared/folder fuse.bindfs force-user=siteXXX,force-group=siteXXX,perms=0700 0 0
This gives me what I want in /app/sites/siteXXX/siteData/shared/folder: 700 and ownership of siteXXX.
The problem is now that if I create a file from the app it will be created with the user 'siteXXX'. Dropbox will likely be able to read it (because most files get read others by default). But it won't be likely to update it if there are newer versions since the file could have been created with 644 and Dropbox is running with 'app' OS user.
Sorry if the explanation is a bit messy. Is there some workaround for this?
Is there a way I can keep the original /home/app/Dropbox/Sites/siteXXX/folder with the 'app' user no matter what?
Thanks in advance,
Answer: If I understood the question correctly, you should check out the --create-for-user and --create-with-perms options.
Comment: Thank you very much, that was exactly what I was looking for!! That worked perfectly. Just as a reference, the final fstab line is this: `/home/app/Dropbox/Sites/siteXXX/folder /app/sites/siteXXX/siteData/shared/folder fuse.bindfs force-user=siteXXX,force-group=siteXXX,perms=0600:u+X,create-for-user=app,create-for-group=app 0 0
`. That way, everything in `/app/sites/siteXXX/siteData/shared/folder` is 700 and 600 and owned by 'siteXXX'. However, newly or modified files/directories by the user 'siteXXX' in that directly, are seen in the dropbox folder with default permission and owned by 'app'


How to validate whole request is an array in Laravel?

Question: I need to validate the JSON body of a request, and it must be an array.
I know I can validate individual fields as an array like so:
$request->validate([
    'name' => ['required', 'array'],
]);

but how can I validate that the whole request is an array instead of, say, an object?
Comment: Why do you want to validate that everything is an array? simply when you send a request to a server you have to give a name to what you are sending. for example `name=John` `firstname.lastname@example.com` if you want to send everything in an array it has to be `array[]=value1` `array[]=value2` and then in the backend `$request->array` and there validate that the `array parameter` is an `array`
Answer: You can use Middleware to check raw request body.
request()->all() will always return array.
Comment: Do you mean to check if `$request->all()` returns an array? Because that `all()` will always return an array even if the request is an object.


Jackson 2.11.4: Set Default Value For Missing JSON field

Question: I have the below JSON
"Choices": [
        {
        "choiceId": "1"

    },
    {
        "choiceId": "2",
        "choiceType": null
    }
    ]

below is the POJO and I need to have both the constructors because if there is no choiceType in json I need to default it to Yes, if  choiceType in json exists with null value then it should not default to Yes
@Getter
@ToString
@Setter
@NoArgsConstructor
public class Choices {
    @JsonProperty("choiceId")
    @NonNull
    private String choiceId;

    @JsonProperty("choiceType")
    private String choiceType;

    @JsonCreator
    @JsonIgnoreProperties(ignoreUnknown = true)
    public Choices(@JsonProperty("choiceId") String choiceId) {
        this.choiceType = choiceType !=null ? choiceType : "Yes";
        this.choiceId = choiceId;
    }

    public Choices(@JsonProperty("choiceId") String choiceId, @JsonProperty("choiceType") String choiceType) {
        this.choiceType = choiceType;
        this.choiceId = choiceId;
    }
}

And my goal is to have a list of choices when the above Json is deserialized and I have below test case
@Test
    public void testChoices(){
        ObjectMapper objectMapper = new ObjectMapper();
        String json = "[ { \"choiceId\": \"1\" }, { \"choiceId\": \"2\", \"choiceType\": null } ]";

        List<Choices> choices = objectMapper.convertValue(json, new TypeReference<List<Choices>>() {
        });
        assertTrue(choices.get(0).getChoiceId().equals("1"));
        assertTrue(choices.get(0).getChoiceType().equals("Yes"));
        assertTrue(choices.get(1).getChoiceType().equals("2"));
        assertNull(choices.get(1).getChoiceType());
    }

When I try to deserialize the below json. I have tried many solutions but still no luck, can someone please help me witht this?
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Invalid definition for property `choiceType` (of type `com.onetrust.ds.request.dto.rest.Choices`): Could not find creator property with name 'choiceType' (known Creator properties: [choiceId])
 at [Source: UNKNOWN; line: -1, column: -1]

Comment: Try without Lombok.
Comment: @Nemanja tried without Lombok but no luck
Answer: You could just get rid of the args constructor and default the value to "Yes". If value is explicitly set to null or to a value it will be assigned. In case of missing value it will be defaulted.
@Getter
@ToString
@Setter
@NoArgsConstructor
public class Choices {
    @JsonProperty("choiceId")
    @NonNull
    private String choiceId;

    @JsonProperty("choiceType")
    private String choiceType = "Yes";

}

Reference - Jackson: What happens if a property is missing?
Answer: Looks like your problem is you should mark both constructors with @JsonCreator. And you need only one of them, Jackson will fill not set values to null by default (no need to create separate constructor for that).
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import lombok.Getter;

public static void main(String[] args) throws IOException {
    String json = "[ { \"choiceId\": \"1\" }, { \"choiceId\": \"2\", \"choiceType\": null } ]";
    ObjectMapper mapper = new ObjectMapper();
    ObjectReader reader = mapper.readerFor(Choices.class);
    List<Choices> choices = reader.<Choices>readValues(json).readAll();
}

@Getter
public static class Choices {

    private String choiceId;
    private String choiceType;

    @JsonCreator
    public Choices(@JsonProperty("choiceId") String choiceId,
                   @JsonProperty("choiceType") String choiceType) {
        this.choiceId = choiceId;
        this.choiceType = choiceType == null ? "Yes" : choiceType;
    }

}

I have found this example here
Comment: Thanks for your answer. I need to have both the constructors because if there is no `choiceType` in json I need to default it to `Yes`
Comment: Expected behavior is, if the `choiceTyoe` doesnt exist in the json then only I need to set the value as `Yes` if the `choiceTyoe`  exists with the value `null` then it should not be set to "Yes". You can double check my test case. With your code I get `choiceTyoe`  as `Yes` for both of the above cases


dnsmasq - Multiple forwarding servers for domain entries?

Question: I was wondering if it was possible to configure dnsmasq to send "server=" entries to multiple upstream servers?
so like this:
server=/facebook.com/126.96.36.199
server=/facebook.com/184.108.40.206

and have it pick which one based on it being available or not, as with resolv.conf? According to the man page, it looks like only one is allowed, but I wondered if there was a way to ask it to behave this way.
Answer: Well in your example you're only pointing out facebook, but I guess you would have the same need for every hostname you might visit
dnsmasq provides the option --all-servers

--all-servers
By  default,  when  dnsmasq has more than one upstream server available, it will send queries to just one server. Setting
  this flag forces dnsmasq to send all queries to all available servers.
                The reply from the server which answers first will be returned to the original requestor.

Set a several DNS servers
server=OpenDNS.IP.Addr.ess

server=GoogleDNS.IP.Addr.ess

server=...

And the fastest response will be considered
Answer: Sure just add multiple lines.
server=/facebook.com/18.104.22.168
server=/facebook.com/22.214.171.124

Man dnsmasq
   -S, --server=[/[<domain>]/[domain/]] ...
          ...  More than one -S  flag  is  allowed,  with
          repeated domain or ipaddr parts as required.

Comment: yes, if one the first server is unavailable, dnsmasq will then send the request to the second server (unless the --all-servers options is used, that will force dnsmasq to use all the servers in parallel and take the first reply)
Comment: huh.... but is the behavior as per resolv.conf?


Property of presheaves morphism

Question: I am trying to prove that whenever there is an injective morphism of presheaves $\mathcal{F} \rightarrow \mathcal{G}$, the morphism induced on the sheafifications is still injective; it's basically exercise in Hartshorne. Here is my attempted solution and I'd like someone to check that it makes sense and there are no obvious mistakes. I am especially unsure about bold statements.
Note that a morphism of presheaves $f$ that is injective on open sets $U \subseteq X$ induces an injective morphism on the stalks $f_x:\mathcal{F}_x \rightarrow \mathcal{G}_x$. We know $f$ induces $f_x$ by [omissis]. To prove injectivity, assume we are given two elements of $\mathcal{F}_x$ with the same image in $\mathcal{G}_x$; we can choose for them two representatives $s, t$ of $\mathcal{F}$ on some open neighbourhood of $x$ and without loss of generality we can take the same neighbourhood $U$ for both. Their images are sections of $\mathcal{G}$ that have the same image in $\mathcal{G}_x$, which means that we can find an open subset $V \subseteq U$ such that $f(s) = f(t)$ in $\mathcal{G}(V)$. But then by the injectivity of $f$, $s = t$ in $\mathcal{F}(V)$. Now I claim that $\mathcal{F}_x \cong \mathcal{F}^+_x$. Define a map $\Phi:\mathcal{F}_x\to\mathcal{F}^+_x$ in the following way: for an element $s_x\in\mathcal{F}_x$, we choose a representative $(s,U)$ where $s\in\mathcal{F}(U)$, send it to the family $(s_p)_{p\in U}\in\mathcal{F}^+(U)$ and take the equivalence class of $(s_p)_{p\in U}$ in $\mathcal{F}^+_x$. I claim that this map is a bijection. [omissis]
As a consequence of this fact, we can define an injective morphism $f^+_x:\mathcal{F}^+_x \rightarrow  \mathcal{G}^+_x$ as  $\Phi^{-1} \circ f_x$. Note that this is the map induced on the stalks by the unique morphism $f^+:\mathcal{F}^+ \rightarrow \mathcal{G}^+$ arising from the universal property of sheafification. All that's left to prove is that it implies the injectivity $f^{+}:\mathcal{F} \rightarrow \mathcal{G}$. Let $s \in \mathcal{F}^+(U)$ and suppose $f^+(U)(s) = 0$. Then clearly $f_x(s_x)=0$, where $s_x=[(U,s)] \in \mathcal{F}^+_x$, $x$ arbitrary. Since $f^+_x$ is injective, there exists an open set $V_x \subset U$ such that $s|_{V_x} = 0$. $\{V_x \}_{x \in U}$ is clearly an open cover of $U$ and since $\mathcal{F^+}$ is a sheaf we can conclude $s = 0$, hence $f^+(U)$ is injective for every $U$.
Answer: Your strategy seems to be the following:
1) If $f : F \to G$ is an injective morphism of presheaves, then $f_x$ is injective for every $x \in X$.
Your proof seems to be fine to me.
2) The morphism $\Phi^F : F \to F^+$ is such that $(\Phi^F)_x$ is bijective for every $x \in X$. Here you denoted $(\Phi^F)_x$ just by $\Phi$, but it is important to notice that this is actually the morphism induced on stalks by a presheaf morphism, which I called $\Phi^F$.
This is the reason why your statement in bold makes sense. (In general, an arbitrary family of maps $F_x \to G_x$ doesn't come from a morphism of presheaves $F \to G$).
The proof of bijectivity of $\Phi^F_x$ is written here.
3) We have a commutative diagram
$$\require{AMScd} \begin{CD}
F @>{f}>> G\\ @V{\Phi^F}VV @VV{\Phi^G}V\\
F^+ @>>{f^+}> G^+
\end{CD}$$
From 1) and 2), we see that $f^+_x$ is injective for all $x \in X$. By exercise III.1.2b) in Hartshorne, this implies that the sheaf morphism $f^+$ is injective. You actually proved this at the end of your question, which is great ! :-)
You should just replace the "$x$ arbitrary" by $x \in U$, but this is not a major issue.
Moreover, writing $f^+_x(s_x)=0$ only makes sense if you have presheaves of abelian groups. For presheaves of sets, you need to write somthing like $f^+_x(s_x) = f^+_x(t_x)$, where $t \in F^+(U)$.
Comment: Thanks for your reply, will read carefully later

Property of presheaves morphism


Error 500 (Internal Server Error) After Clearing Cache

Question: I truncated cache_block and cache_bootstrap tables in Drupal database (I don't know if its okay to truncate cache tables) and after that my site went down.
I am getting HTTP Error 500 that says

The website encountered an error
  while retrieving www.drupalwebsite.com. It may be down for maintenance
  or configured incorrectly.

Before truncating those tables, my site was working fine. Is there any way to get it back to working??

UPDATE -

I cleared all other cache tables too...
WEBSERVER LOGS -

[Thu Dec 27 02:51:24 2012] [warn] [client *IP_Address*] mod_fcgid: stderr: PHP Fatal error: Call to undefined function ctools_include() in /var/www/vhosts/*my_site_name*/drupal/sites/all/modules/views/views.module on line 62
Comment: You need to read your webserver logs to find out what is causing the error.
Comment: Try truncating other cache tables too.
Comment: Can you check your PHP error log, Drupal dblog (if you have drush) and report back with what you see.
Comment: Is your Ctools module folder exist?
Comment: @kalabro yes it does, but the module is disabled
Answer: Somehow your site has entered a broken state since the Views module depends on ctools but it's not enabled.
What you need to do to fix it is to:

Enable the ctools module in the database, by running the following SQL UPDATE system SET status = 1 WHERE name = 'ctools';
Truncate all the cache tables in your database.
(Might not be needed) run $ drush rr, requires drush and the registry rebuild extension.
Run $ drush cc all requires drush.

Going through the above list should fix your site. Messing with your sites cache table can be a bit dangerous if you don't know what you are doing since drupal caches what modules it needs to load for performance.
You can read more about and download drush and registry rebuild on drupal.org.
Comment: Thanks so much.. I followed the first two steps and site is running now.. I know now I dont have to, but am just a little curious, how and where do I run - $ drush rr. Sorry but I am new to Drupal
Comment: Drush is a shell extension for drupal, that allows you to be able to do stuff on your Drupal site from the shell.
Comment: @see http://drupal.org/project/drush
Answer: I found this tool extremely useful in resoling similar problems. Just on your server, wget boomshadow.net/tools-utils/fixperms.sh
Then, sh ./fixperms.sh -a USER-NAME


Como verificar se os arquivos "DLL" foi registrado com sucesso

Question: Preciso verificar se o processo foi executado com sucesso, no caso as extensões que ele vai tentar registrar são:

.DLL
.OCX

O Código que estou usando pra registrar é este:
string pathcli = copiar + nomedofonte;

if (!nomedofonte.Contains(".exe") ||!nomedofonte.Contains(".EXE"))
{
    Process proc = new Process
    {
        StartInfo =
        {
            FileName = Registrador,
            Arguments = "/s"+pathcli,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true
         }
     };

    proc.Start();
    Application.DoEvents();
}

Como que irei verificar se os arquivos daquela extensão foram registrado com sucesso?
Comment: Só de curiosidade, pra que alguém precisa de DLL registrada nos OSes modernos, em vez de simplesmente carregar? Outra coisa. e se a extensão for uma das variantes como `.Exe`, ou `.eXe`, por eXEmplo? Não seria o caso de comparar _case insensitive_?
Comment: Não, Pois é um sistema interno da empresa, onde precisa justamente registrar as DLL pra outro sistema poder entender e rodar, o .EXE eu usei a verificação pra ignorar essas extensão
Answer: Você pode inspecionar o registro do Windows para ver se a DLL ou OCX está registrado. O node CLSID tem as chaves registradas:
HKEY_CLASSES_ROOT\CLSID\{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
Porém para isso você precisa saber o Guid, e provavelmente você não sabe. Então a solução é ler as sub-chaves do CLSID e procurar pelo nome da DLL ou OCX, como no exemplo abaixo:
bool VerificarRegistro(string nomeDLL)
{
    bool achou = false;
    RegistryKey clsid = Registry.ClassesRoot.OpenSubKey("CLSID");
    string[] ClsIDs = clsid.GetSubKeyNames();
    string subkey = "";
    for (int i = 0; i < ClsIDs.Length; i++)
    {
        subkey = ClsIDs[i];
        if (subkey.Substring(0, 1) != "{") continue;
        RegistryKey cls = Registry.ClassesRoot.OpenSubKey("CLSID\\" + subkey + "\\InprocServer32");
        if (cls == null) continue;
        string x = cls.GetValue("", "").ToString();
        if (x.IndexOf(nomeDLL) >= 0)
        {
            achou = true;
            break;
        }
    }
    return achou;
}

Comment: Esta quase la, mas me deu uma luz, muito obrigado.


Commerce Number Pattern

Question: My system environment:

OS - Windows 10 64-bit
Local Server Stack - WampServer
Drupal 8.9.8
Theme Droopler
Module Commerce - installed using Composer and enabled by Drush

The Status Report (screen capture as below):

The setting for Commerce Number Pattern:

Despite clearing the cache after updating the default number setting, Drupal still reports an error as shown above.
Any assistance is greatly valued.
Thank you.
Comment: I think I had that too, goto `/update.php` and run the update.
Comment: I did that many times but to no avail.
Comment: I conjecture that the module (commerce_number_pattern) is used by commerce cart. I have googled and find no resources directly applicable to the issue. Commerce 2.x also is not very helpful for a newbie like me. Still trying to decipher the issue and come up with a solution. I even tried to create a yaml (yml) file. The status remains the same. Will try another attempt after a cool-down. Thanks for those reading and keeping the discussions alive:-)
Comment: `drush entity-updates` is the solution according to [this issue](https://www.drupal.org/project/drupal/issues/2601762). If you don't have Drush run [#24 code](https://www.drupal.org/project/drupal/issues/2601762#comment-10835098) once by placing it in a preprocess or a hook temporarily.
Comment: Thanks. I will try it and update the result:-)
Comment: No luck. I think the issue is still about how to configure the module commerce_number_pattern. Anyway, I appreciate your effort@NoSssweat
Comment: It's not about configuration at all. Drupal is detecting that you have commerce_number_pattern installed, but the entity type definition that ships with that module has not been created. It usually means that module installation failed for some reason, and now you need some Drush magic to resolve it (if update.php didn't work).
Comment: @BojanZivanovic. update.php didn't work. That's what I am looking for. Until now, I cannot find the answer. Any tip will be helpful. Thanks!
Answer: Please install Devel module.
Link to Devel module

enable devel module.

click on reinstall module.

check module "Commerce Number Pattern".

click on reinstall.

Hope this helps you.

Commerce Number Pattern


trouble echoing a sql query in the order i want

Question: im new in php sql and stuff, and I've been trying to think in a way to show in order a SELECT.
Let me explain this better, this is the query I have:
$resultAraucania = mysql_query("SELECT nombre.idNombre,
                                       nombre.nombre AS nombreNombre,
                                       comuna.nombre AS nombreComuna,
                                       giro.nombre AS nombreGiro,
                                       provincia.nombre AS nombreProvincia,
                                       region.nombre AS nombreRegion
                                  FROM nombre
                            INNER JOIN comuna ON nombre.Comuna_idComuna = comuna.idComuna
                            INNER JOIN giro ON nombre.Giro_idGiro = giro.idGiro
                            INNER JOIN provincia ON comuna.Provincia_idProvincia = provincia.idProvincia
                            INNER JOIN region ON provincia.Region_idRegion = region.idRegion
                                 WHERE provincia.Region_idRegion = 9
                              ORDER BY nombreProvincia, nombreComuna, nombreGiro, nombreNombre");

See at the end, I ordered by nombreProvincia, nombreComuna, nombreGiro, nombreNombre.
How can I echo it in a way that I get first all the results for nombreProvincia, inside all the result for nombreComuna, and so on so I get something like this:
nombreProvincia1
nombreComuna1
  nombreGiro1
     nombreNombre1, nombreNombre2, nombreNombre3...

  nombreGiro2
     nombreNombre4, nombreNombre5, nombreNombre6...

  nombreGiron...
    nombreNombren...

nombreComunan..

nombreProvincia2
nombreComuna21...
  nombreGiro...
    nombreNombre....

Hope I explain this well enough, I thought doing something like this:
<?php
  while($row = mysql_fetch_assoc($resultAraucania)) {
    echo $row['nombreProvicia']."
";

    while($row = mysql_fetch_assoc($resultAraucania)) {
      echo " ".$row['nombreComuna']."
";

      while($row = mysql_fetch_assoc($resultAraucania)) {
        echo " ".$row['nombreGiro']."
";

        while($row = mysql_fetch_assoc($resultAraucania)) {
          echo " ".$row['nombreNombre']."
";
        }
      }
    }
  } ?>

but it didn't work, hope somebody can help me in this. thank you.
Answer: You could try something like that. It's not optimal, but you should understand how it works.
$nombreProvincia = "";
$nombreComuna = "";
$nombreGiro = "";
$nombreNombre = array();

while ($row = mysql_fetch_assoc($resultAraucania)) {
    if ($nombreProvincia == $row['nombreProvincia']) {
        if ($nombreComuna == $row['nombreComuna']) {
            if ($nombreGiro == $row['nombreGiro']) {
                $nombreNombre[] = $row['nombreNombre'];
            }
            else { //nombreGiro
                echo '  ' . implode(', ', $nombreNombre);
                $nombreGiro = $row['nombreGiro'];
                echo '
 '.$nombreGiro;
                $nombreNombre = array($row['nombreNombre']);
            }
        }
        else { // nombreComuna
            echo '  ' . implode(', ', $nombreNombre);
            $nombreComuna = $row['nombreComuna'];
            echo '
'.nombreComuna;
            $nombreGiro = $row['nombreGiro'];
            echo '
 '.$nombreGiro;
            $nombreNombre = array($row['nombreNombre']);
        }
    }
    else { // nombreProvincia
        if (!empty($nombreNombre)) {
            echo '  ' . implode(', ', $nombreNombre);
        }
        $nombreProvincia = $row['nombreProvincia'];
        echo '
'.$nombreProvincia.'
'."\n";
        $nombreComuna = $row['nombreComuna'];
        echo '
'.nombreComuna;
        $nombreGiro = $row['nombreGiro'];
        echo '
 '.$nombreGiro;
        $nombreNombre = array($row['nombreNombre']);
    }
}
echo '  ' . implode(', ', $nombreNombre);

Comment: wow, thank you so much!, it works perfectly!, also i thought in doing a query with group by, do you think that you make everything easier??
Comment: No. GROUP BY is when you want to do some aggregation functions on queries, like SUM or MAX...


Limit of matrix powers

Question: Suppose to consider a matrix $P$ whose entries $p_{ij} \in [0,1)$.
Can we always say that
$$\lim_{k \rightarrow \infty} P^k = 0$$ ?
Thanks for your help!
Answer: I don't think that is true.  Consider a $2 \times 2$ matrix $A$ with all the entries $\frac{1}{2}$, i.e.
$$A=\begin{pmatrix}
\frac{1}{2} & \frac{1}{2} \\
\frac{1}{2} & \frac{1}{2}
\end{pmatrix}$$
 Then every power of that matrix is the original matrix itself, i.e.
$$A^n=A \quad \forall n \in \mathbb{N}^+$$
Answer: If $P$ is a squared matrix and $\rho(P)$ its spectral radius, then
$$\lim_{k\to \infty} P^k = 0 \qquad \iff \qquad \rho(P)<1$$
Now, note that for a nonnegative matrix $P$, by the Collatz-Wielandt principle, we have
$$ \max_{\substack{x\geq 0\\ x\neq 0}}\min_{x_i\neq 0}\frac{(Px)_i}{x_i}\leq \rho(P)\leq \min_{x> 0}\max_{i}\frac{(Px)_i}{x_i},$$
where the inequalities $x\geq 0$ and $x>0$ have to be understood component-wise.
Combining these facts is useful for at least two reasons:
1) It allows you to relatively easily check if $\rho(P)<1$.
Example: If $P=\dfrac{1}{6}\begin{pmatrix}2 & 3 \\ 2 & 2 \end{pmatrix}$ and $x=\begin{pmatrix}1\\ 1 \end{pmatrix}$, then
$$ \rho(P) \leq \max_{i=1,2}\frac{(Px)_i}{x_i} = \frac{2+3}{6}<1 \qquad \implies \quad \lim_{k\to \infty} P^k =0.$$
2) It allows you to easily build counter-examples for your claim.
Example: If $P=\dfrac{1}{4}\begin{pmatrix}2 & 3 \\ 3 & 3 \end{pmatrix}$ and $x=\begin{pmatrix}1\\ 1 \end{pmatrix}$, then
$$ \rho(P) \geq \min_{i=1,2}\frac{(Px)_i}{x_i} = \frac{2+3}{4}>1 \qquad \implies \quad \lim_{k\to \infty} P^k \neq 0.$$
Answer: If the spectral radius is less than unity the sequence will converge.
Look at the largest singular value.
This post shows what happens as a matrix is raised to a sequence of powers.
What is the mechanism of Eigenvector?
Consider the matrix
$$
 \mathbf{A} =
\left[
\begin{array}{rr}
 1 & -1 \\
 0 & 1 \\
\end{array}
\right].
$$
which has singular values
$$
\sigma = \left( \sqrt{\frac{1}{2} \left(\sqrt{5}+3\right)},\sqrt{\frac{1}{2} \left(3-\sqrt{5}\right)}\right) \approx (1.61803, 0.618034)
$$
The map of a matrix onto a unit circle (left) creates an ellipse (right).

This next image overlays the column vectors from the SV decomposition matrix $\mathbf{V}$, scaled by the singular values. The matrix grows in directions where the singular value exceeds unity.

Limit of matrix powers


Issue with negative lookbehind in R

Question: I have this set of sentences:
w <- c("so i said er well it would n't surprise me if it could bloody talk",  # quote marker
        "we got fifteen, well thirteen minutes",
        "well she brought a pie and she brought some er punch round",
        "so your dad said well have n't i been soft ?",                       # quote marker
        "And he went [pause] well I can't feel any. ",                        # quote marker
        "I goes well they'll improve the grant to start off with",            # quote marker
        "so with the chips as well this is about one sixty .",
        "well we 're not all the same are we , but")

All strings contain the word well. I'm interested in those strings where well acts as a quote marker, as indicated by the occurrence of said, goes, and went. Using positive lookbehind I can match these sentences:
grep("(?<=said|goes|went).*well", w, value = T, perl = T)
[1] "so i said er well it would n't surprise me if it could bloody talk"
[2] "so your dad said well have n't i been soft ?"
[3] "And he went [pause] well I can't feel any. "
[4] "I goes well they'll improve the grant to start off with"

The issue I have is that negative lookbehind to match those string in which 'well' is not a quote marker does not work. For example, this matches everything:
grep("(?<!said|goes|went).*well", w, value = T, perl = T)
[1] "so i said er well it would n't surprise me if it could bloody talk" # not match
[2] "we got fifteen, well thirteen minutes"                              # match
[3] "well she brought a pie and she brought some er punch round"         # match
[4] "so your dad said well have n't i been soft ?"                       # not match
[5] "And he went [pause] well I can't feel any. "                        # not match
[6] "I goes well they'll improve the grant to start off with"            # not match
[7] "so with the chips as well this is about one sixty ."                # match
[8] "well we 're not all the same are we , but"                          # match

Why doesn't it match correctly and how would it have to be changed to match correctly?
Thanks in advance!
Comment: don't you just want to invert your matches in the positive look-behind? `grep(..., invert = TRUE)`
Comment: I'm familiar with that option but in the post I was specifically intererested in digging a little deeper into negative lookbehind. But thanks anyway.
Answer: That happens because (?<!said|goes|went) matches a location in the string that is not immediately preceded with the strings defined in the lookbehind. .* then matches any 0+ chars other than line break chars as many as possible and then well is matched. There are a lot of such valid positions.
The easiest is to match those strings where said, goes or went occur before well and skip them, then match well in all other contexts:
\b(?:said|goes|went)\b.*\bwell\b(*SKIP)(*F)|\bwell\b

See the regex demo.
Caution: If you use a solution like ^(?!.*\b(?:said|goes|went)\b).*\bwell\b, you may get false negatives when said, goes or went appear after well.
Pattern details

\b(?:said|goes|went)\b.*\bwell\b(*SKIP)(*F) - a whole word: said, goes or went and then any 0 or more chars as many as possible and then a whole word well, after this match is found, it is dropped and the regex engine starts looking for a match at the current failed position
| - or
\bwell\b - a whole word well.

See an R demo:
grep("\\b(?:said|goes|went)\\b.*\\bwell\\b(*SKIP)(*F)|\\bwell\\b", w, value = TRUE, perl = TRUE)
# [1] "we got fifteen, well thirteen minutes"
# [2] "well she brought a pie and she brought some er punch round"
# [3] "so with the chips as well this is about one sixty ."
# [4] "well we 're not all the same are we , but"

Issue with negative lookbehind in R


Question about this version of L'hopital Rule

Question: I saw below L'hopital Rule in a book somewhere.
After I saw that, I was curious that the rule's proof is strictly correct!
for example, To be the strictly proof $f\left(x\right)$, $g\left(x\right)$ must continuous differentiable?
Sorry for bad english! T^T I'm foreigner
Theorem and Proof is written in Other language Originally.
So I translated them to English!

L'hopital's Theorem when $\dfrac{0}{0}$ form
Let $f\left(x\right)$, $g\left(x\right)$ be differentiable in interval
  $\left(a,b\right)$ that includes a point $c$ and
  $f\left(c\right)=g\left(c\right)=0$ and $g'\left(x\right)\neq0$ in
  $\left(a,b\right)$ that doesn't include a point $c$.
If ${\displaystyle \lim_{x\rightarrow c}\dfrac{f'\left(x\right)}{g'\left(x\right)}}$ exists, then
  ${\displaystyle \lim_{x\rightarrow c}\dfrac{f\left(x\right)}{g\left(x\right)}=\lim_{x\rightarrow c}\dfrac{f'\left(x\right)}{g'\left(x\right)}}$

p.f)
At first, for $c<x<b$, $g'\left(x\right)\neq0$. Also $f\left(x\right)$, $g\left(x\right)$ are continuous in $\left[c,b\right]$ and differentiable in $\left(c,b\right)$ and $g'\left(x\right)\neq0$ for all $x$ in that open interval, so Cauchy's mean value theorem can be applied.
there exists $c$ that makes $\dfrac{f\left(x\right)-f\left(c\right)}{g\left(x\right)-g\left(c\right)}=\dfrac{f'\left(c\right)}{g'\left(c\right)}$ in $\left(c,b\right)$ at least one.
By condition, $\dfrac{f\left(x\right)}{g\left(x\right)}=\dfrac{f'\left(c\right)}{g'\left(c\right)}$
thus $c<d<b$ when $x\rightarrow c+$, $d\rightarrow c+$
so ${\displaystyle \lim_{x\rightarrow c+}\dfrac{f\left(x\right)}{g\left(x\right)}=\lim_{d\rightarrow c+}\dfrac{f'\left(d\right)}{g'\left(d\right)}=\lim_{x\rightarrow c+}\dfrac{f'\left(x\right)}{g'\left(x\right)}}$
Alike above, thus $a<d<c$ when $x\rightarrow c-$, $d\rightarrow c-$
So ${\displaystyle \lim_{x\rightarrow c-}\dfrac{f\left(x\right)}{g\left(x\right)}=\lim_{d\rightarrow c-}\dfrac{f'\left(d\right)}{g'\left(d\right)}=\lim_{x\rightarrow c-}\dfrac{f'\left(x\right)}{g'\left(x\right)}}$
By above, ${\displaystyle \lim_{x\rightarrow c}\dfrac{f\left(x\right)}{g\left(x\right)}}$ equals ${\displaystyle \lim_{x\rightarrow c}\dfrac{f'\left(x\right)}{g'\left(x\right)}}$ if ${\displaystyle \lim_{x\rightarrow c}\dfrac{f'\left(x\right)}{g'\left(x\right)}}$ exists.
Comment: Please don't vandalize your posts.
Answer: You are more or less on the right track but do not use $c$ (the fixed point for the limit) as the intermediate point from MVT.
If $\lim_{x \to c}f'(x)/g'(x) = L$, then applying the mean value theorem there exists $\xi$ between $x$ and $c$ such that for $x \neq c$
$$\left|\frac{f(x)}{g(x)}- L \right|= \left|\frac{f'(\xi)}{g'(\xi)}- L \right| \to 0, $$
 as $x \to c$.  This follows because $\xi \to c$ as $x \to c.$
You only need $f$ and $g$ to be differentiable, not necessarily continuously differentiable.


Evaluating Math Function through Simplification

Question: I am going through a computer science text book and it is simplifying an equation but I don't understand how it gets the answer. How does 5n get multiplied out? If you multiply both sides by 2 to get rid of the denominator wouldn't 5*(n/2) just be 5n not (5n + 5n)?
Question runthrough screenshot
Comment: Um, no.  5*(n/2) would be neither of those.  It'd be 5n/2.
Comment: Could you explain why
Comment: Explain why 5*(n/2) = 5n/2?  Seriously?  Because.... well associativity of multiplication and notation of fractions as multiplicative inverses, I guess if you are algebraicly inclined.  Or as fractions defined as division (the inverse of multiplication) because "5 times (n divided by 2) = 5 times ((n times 1) divided by 2) = (5 times times n) times (1 divided by 2) = (5 times n) divided by 2".
Comment: I agree with the proposer. There is an error in the third equation of Ch.11.
Answer: Going on the sheet:
$T(n) = 2T(\frac n 2) + 5n$
So $T(\frac n 2) = 2T(\frac n 4) + \frac {5n} 2$
Plugging the second back into the first:
$T(n) = 2[ 2T(\frac n 4) + \frac {5n} 2 ] + 5n$
$= [2\times2T(\frac n 4) + 2\times \frac{5n} 2] + 5n$
$ = 2\times2T(\frac n 4) + 5n + 5n$.
Comment: I see, would have been much easier to follow if the textbook said plug back in, thanks a lot!


geofire android to store and retrive locations and display it on map

Question: I am developing an taxi application in android. I need to store retrieve and update location of my cabs and show it on maps using geofire. I have used firebase for authentication.
Need a complete tutorial for android geofire but can't find any
I have also seen SFVehicle example but didn't understand much
Any help would be appreciated!!!
Answer: first of all currently there are no complete tutorials on geofire so all you have in your disposal is the official documentation of Geofire go for java and js.And here is a small but maybe helpful stuff--
https://firebase.googleblog.com/2013/09/geofire-location-queries-for-fun-and.html,
https://medium.com/google-cloud/firebase-is-cool-geofire-is-just-awesome-b7f2be5e0f0f#.x78gjws28,
I hope that these could be of some help to you.
Answer: I have created a library for Android, which provides geo-based firestore data to find the list of data within a given radius in KM / MILES.
It also gives the faster response in a single query read with the classification of the ADDED and REMOVED data in and from the query with real-time updates.
You can refer Geo-Firestore
It has well-documentation so you can easily develop the same.
Answer: here are a few more links
https://firebase.googleblog.com/2014/08/geofire-goes-mobile.html
https://firebase.googleblog.com/2014/06/geofire-20.html
How to save GeoFire coordinates along with other items in Firebase database?
Answer: Here is an example code for having a current location of driver
public class MainActivity extends AppCompatActivity implements
    OnMapReadyCallback, PermissionsListener {
// Variables needed to initialize a map
private MapboxMap mapboxMap;
private MapView mapView;
// Variables needed to handle location permissions
private PermissionsManager permissionsManager;
// Variables needed to add the location engine
private LocationEngine locationEngine;
private long DEFAULT_INTERVAL_IN_MILLISECONDS = 1000L;
private long DEFAULT_MAX_WAIT_TIME = DEFAULT_INTERVAL_IN_MILLISECONDS *1;
// Variables needed to listen to location updates
private MainActivityLocationCallback callback = new MainActivityLocationCallback(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Mapbox access token is configured here. This needs to be called either in your application
    // object or in the same activity which contains the mapview.
    Mapbox.getInstance(this, "");

    // This contains the MapView in XML and needs to be called after the access token is configured.
    setContentView(R.layout.activity_main);

    mapView = findViewById(R.id.mapView);
    mapView.onCreate(savedInstanceState);
    mapView.getMapAsync(this);
}

@Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
    this.mapboxMap = mapboxMap;

    mapboxMap.setStyle(Style.TRAFFIC_NIGHT,
            new Style.OnStyleLoaded() {
                @Override
                public void onStyleLoaded(@NonNull Style style) {
                    enableLocationComponent(style);
                }
            });
}

/**
 * Initialize the Maps SDK's LocationComponent
 */
@SuppressWarnings( {"MissingPermission"})
private void enableLocationComponent(@NonNull Style loadedMapStyle) {
    // Check if permissions are enabled and if not request
    if (PermissionsManager.areLocationPermissionsGranted(this)) {

        // Get an instance of the component
        LocationComponent locationComponent = mapboxMap.getLocationComponent();

        // Set the LocationComponent activation options
        LocationComponentActivationOptions locationComponentActivationOptions =
                LocationComponentActivationOptions.builder(this, loadedMapStyle)
                        .useDefaultLocationEngine(false)
                        .build();

        // Activate with the LocationComponentActivationOptions object
        locationComponent.activateLocationComponent(locationComponentActivationOptions);

        // Enable to make component visible
        locationComponent.setLocationComponentEnabled(true);

        // Set the component's camera mode
        locationComponent.setCameraMode(CameraMode.TRACKING);

        // Set the component's render mode
        locationComponent.setRenderMode(RenderMode.COMPASS);

        initLocationEngine();
    } else {
        permissionsManager = new PermissionsManager(this);
        permissionsManager.requestLocationPermissions(this);
    }
}

/**
 * Set up the LocationEngine and the parameters for querying the device's location
 */
@SuppressLint("MissingPermission")
private void initLocationEngine() {
    locationEngine = LocationEngineProvider.getBestLocationEngine(this);

    LocationEngineRequest request = new LocationEngineRequest.Builder(DEFAULT_INTERVAL_IN_MILLISECONDS)
            .setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY)
            .setMaxWaitTime(DEFAULT_MAX_WAIT_TIME).build();

    locationEngine.requestLocationUpdates(request, callback, getMainLooper());
    locationEngine.getLastLocation(callback);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

@Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
    Toast.makeText(this, "Enable Location", Toast.LENGTH_LONG).show();
}

@Override
public void onPermissionResult(boolean granted) {
    if (granted) {
        if (mapboxMap.getStyle() != null) {
            enableLocationComponent(mapboxMap.getStyle());
        }
    } else {
        Toast.makeText(this, "Permission Not Granted", Toast.LENGTH_LONG).show();
        finish();
    }
}

private static class MainActivityLocationCallback
        implements LocationEngineCallback<LocationEngineResult> {

    private final WeakReference<MainActivity> activityWeakReference;

    MainActivityLocationCallback(MainActivity activity) {
        this.activityWeakReference = new WeakReference<>(activity);
    }

    /**
     * The LocationEngineCallback interface's method which fires when the device's location has changed.
     *
     * @param result the LocationEngineResult object which has the last known location within it.
     */
    @Override
    public void onSuccess(LocationEngineResult result) {
        MainActivity activity = activityWeakReference.get();

        if (activity != null) {
            Location location = result.getLastLocation();

            if (location == null) {
                return;
            }
            FirebaseDatabase database = FirebaseDatabase.getInstance();
            String somi_id2 = "emp_samad";
            DatabaseReference myRef3 = database.getReference("current");
            GeoFire geoFire = new GeoFire(myRef3);
            geoFire.setLocation(somi_id2,new GeoLocation(location.getLatitude(),location.getLongitude()));

            Toast.makeText(activity,String.valueOf(location.getLatitude()+"\n"+String.valueOf(location.getLongitude())),Toast.LENGTH_SHORT).show();

            // Pass the new location to the Maps SDK's LocationComponent
            if (activity.mapboxMap != null && result.getLastLocation() != null) {
                activity.mapboxMap.getLocationComponent().forceLocationUpdate(result.getLastLocation());
            }
        }
    }

    /**
     * The LocationEngineCallback interface's method which fires when the device's location can not be captured
     *
     * @param exception the exception message
     */
    @Override
    public void onFailure(@NonNull Exception exception) {
        Log.d("LocationChangeActivity", exception.getLocalizedMessage());
        MainActivity activity = activityWeakReference.get();
        if (activity != null) {
            Toast.makeText(activity, exception.getLocalizedMessage(),
                    Toast.LENGTH_SHORT).show();
        }
    }
}

@Override
protected void onStart() {
    super.onStart();
    mapView.onStart();
}

@Override
protected void onResume() {
    super.onResume();
    mapView.onResume();
}

@Override
protected void onPause() {
    super.onPause();
    mapView.onPause();
}

@Override
protected void onStop() {
    super.onStop();
    mapView.onStop();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    mapView.onSaveInstanceState(outState);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    // Prevent leaks
    if (locationEngine != null) {
        locationEngine.removeLocationUpdates(callback);
    }
    mapView.onDestroy();
}

@Override
public void onLowMemory() {
    super.onLowMemory();
    mapView.onLowMemory();
}
}

Now here is the code for showing him on map for realtime
    public class MainActivity extends AppCompatActivity
      implements
        OnMapReadyCallback, PermissionsListener{

    private MapView mapView;
    private PermissionsManager permissionsManager;
    private MapboxMap mapboxMap;
    private GeoJsonSource geoJsonSource;
    private ValueAnimator animator;
    public static double pre_lat,pre_long;
    public static Marker marker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Mapbox.getInstance(this, "*YOUR_KEY*");
        setContentView(R.layout.activity_main);

        Mapbox.getInstance(this, "");

        mapView = findViewById(R.id.mapView);
        //fetchData process = new fetchData();
        // process.execute();
        mapView.onCreate(savedInstanceState);
        mapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(@NonNull final MapboxMap mapboxMap) {
                MainActivity.this.mapboxMap = mapboxMap;
                mapboxMap.setCameraPosition(new CameraPosition.Builder()
                        .zoom(19)
                        .target(new
       LatLng(24.987029999999997,67.056585))
                        .build());
                mapboxMap.setStyle(Style.DARK,
                        new Style.OnStyleLoaded() {
                            @Override
                            public void onStyleLoaded(@NonNull Style style) {
                               // enableLocationComponent(style);
                                // Create an Icon object for the marker to use

                                FirebaseDatabase database = FirebaseDatabase.getInstance();
                                String somi_id2 = "emp_samad";
                                DatabaseReference myRef3 = database.getReference("current");
                                GeoFire geoFire = new GeoFire(myRef3);
                                GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(24.987043333333336, 67.05663333333334), 10);
                                geoFire.getLocation("emp_samad", new LocationCallback() {
                                    @Override
                                    public void onLocationResult(String key, GeoLocation location) {
                                        if (location != null) {
                                            pre_lat = location.latitude;
                                            pre_long = location.longitude;
//                                            Location prevLoc = new Location(location.latitude,location.longitude);
//                                            Location newLoc =  ;
//                                            float bearing = prevLoc.bearingTo(newLoc) ;
                                            marker = mapboxMap.addMarker(new MarkerOptions()
                                                    .position(new LatLng(pre_lat,pre_long))
                                                    .icon(IconFactory.getInstance(MainActivity.this).fromResource(R.drawable.marker)));
                                            System.out.println(String.format("The location for key %s is [%f,%f]", key, location.latitude, location.longitude));
                                        } else {
                                            System.out.println(String.format("There is no location for key %s in GeoFire", key));
                                        }
                                    }

                                    @Override
                                    public void onCancelled(DatabaseError databaseError) {

                                    }
                                });
                                geoQuery.addGeoQueryDataEventListener(new GeoQueryDataEventListener() {
                                    @Override
                                    public void onDataEntered(DataSnapshot dataSnapshot, GeoLocation location) {
                                        System.out.println(String.format("The location is [%f,%f]", location.latitude, location.longitude));
                                    }

                                    @Override
                                    public void onDataExited(DataSnapshot dataSnapshot) {

                                    }

                                    @Override
                                    public void onDataMoved(DataSnapshot dataSnapshot, GeoLocation location) {

                                    }

                                    @Override
                                    public void onDataChanged(DataSnapshot dataSnapshot, GeoLocation location) {
                                        double lat = pre_lat;
                                        double lon = pre_long;

                                        LatLng pre_latlng = new LatLng(lat,lon);
                                        LatLng washington = new LatLng(location.latitude,location.longitude);

                                        ValueAnimator markerAnimator = ValueAnimator.ofObject(new TypeEvaluator<LatLng>() {

                                            @Override
                                            public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) {
                                                return new LatLng(startValue.getLatitude() + (endValue.getLatitude() - startValue.getLatitude()) * fraction, startValue.getLongitude() + (endValue.getLongitude() - startValue.getLongitude()) * fraction);
                                            }

                                        }, new LatLng[]{pre_latlng, washington});

                                        markerAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                            @Override
                                            public void onAnimationUpdate(ValueAnimator animation) {
                                                if (marker != null) {
                                                    marker.setPosition((LatLng) animation.getAnimatedValue());
                                                }
                                            }
                                        });

                                        markerAnimator.setDuration(7500);
                                        //markerAnimator.setRepeatCount(ValueAnimator.INFINITE);
                                        //markerAnimator.setRepeatMode(ValueAnimator.REVERSE);
                                        markerAnimator.setInterpolator(new AccelerateDecelerateInterpolator());

                                        markerAnimator.start();

                                       /* if(marker!=null)
                                        {
                                            //marker.remove();
                                            //marker.setPosition(new LatLng(location.latitude,location.longitude));
                                        }
                                        System.out.println(String.format("The location is [%f,%f]", location.latitude, location.longitude));
*/

                                       }

                                    @Override
                                    public void onGeoQueryReady() {

                                    }

                                    @Override
                                    public void onGeoQueryError(DatabaseError error) {

                                    }
                                });
                            }
                        });
            }
        });
    }

    @SuppressWarnings( {"MissingPermission"})
    private void enableLocationComponent(@NonNull Style loadedMapStyle) {
// Check if permissions are enabled and if not request
        if (PermissionsManager.areLocationPermissionsGranted(this)) {

// Get an instance of the component
            LocationComponent locationComponent = mapboxMap.getLocationComponent();

// Activate with options
            locationComponent.activateLocationComponent(
                    LocationComponentActivationOptions.builder(this, loadedMapStyle).build());

// Enable to make component visible
            locationComponent.setLocationComponentEnabled(true);

// Set the component's camera mode
            locationComponent.setCameraMode(CameraMode.TRACKING);

// Set the component's render mode
            locationComponent.setRenderMode(RenderMode.COMPASS);
        } else {
            permissionsManager = new PermissionsManager(this);
            permissionsManager.requestLocationPermissions(this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onExplanationNeeded(List<String> permissionsToExplain) {
        Toast.makeText(this, "Enable Location", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onPermissionResult(boolean granted) {
        if (granted) {
            mapboxMap.getStyle(new Style.OnStyleLoaded() {
                @Override
                public void onStyleLoaded(@NonNull Style style) {
                   // enableLocationComponent(style);
                }
            });
        } else {
            Toast.makeText(this, "Permission Not Granted", Toast.LENGTH_LONG).show();
            // finish();
        }
    }

    @Override
    @SuppressWarnings( {"MissingPermission"})
    public void onStart() {
        super.onStart();
        mapView.onStart();

    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        mapView.onStop();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onMapReady(@NonNull MapboxMap mapboxMap)
    {

    }

    }

what you have to use for this is to implement a geofire library
Geofire implementation
implementation 'com.firebase:geofire-android:3.0.0'

I hope that this will help you alot


Add a class retrieved from a sibling field to responsive image

Question: I have a Profile paragraph type that has the following fields:

Profile Image [Responsive Image Field format]
Profile Headline [Plain Text]
Profile Description [Plain Text]
Rounded Profile Image [Boolean]

What I'm trying to do is that when the field_rounded_profile_image boolean is selected, that it will add the rounded-circle class to the image attributes of the field_profile_image field.
Currently, this is what the code for the image looks like when it is printed:

  <picture>
    <source srcset="/sites/default/files/styles/profile_large/public/paragraphs/image/profile/image1.jpg?h=74e1741d&itok=WLlku9ED 1x, /sites/default/files/styles/profile_large/public/paragraphs/image/profile/image1.jpg?h=74e1741d&itok=WLlku9ED 2x" media="all and (min-width: 992px)" type="image/jpeg">
    <source srcset="/sites/default/files/styles/profile_small/public/paragraphs/image/profile/image1.jpg?h=74e1741d&itok=p2VQAa0P 1x, /sites/default/files/styles/profile_small/public/paragraphs/image/profile/image1.jpg?h=74e1741d&itok=p2VQAa0P 2x" media="all and (min-width: 768px)" type="image/jpeg">

  </picture>

I'm trying to write a preprocess hook to do this but this part of my Drupal game is lacking so I was wondering if anyone could help me out.
I've tried something along the lines of the following to no avail:
// Note that me adding the __profile_card below does work due to another hook I have running to allow me to specify which paragraph type to target
function MYTHEME_preprocess_paragraph__profile_card(&$variables) {
  if ($variables['content']['field_rounded_profile_image'][0]['#markup'] == "On") {
    $variables['content']['field_profile_image']['attributes']['class'][] = "rounded-circle";
  }
}

Any help on this would be great and I can provide any follow-up details if needed.
Answer: What I'd recommend is to simply preprocess the paragraph, get the "round image" Boolean, and use it to add a class to the paragraph. This should be just enough to style the responsive image accordingly.
/**
 * Implements template_preprocess_paragraph__PARAGRAPH_TYPE.
 */
function MYTHEME_preprocess_paragraph__profile_card(&$variables) {

  // Get paragraph.
  $paragraph = $variables['paragraph'];

  if (!$paragraph->get('field_rounded_profile_image')->isEmpty()) {

    // Get Boolean.
    $rounded = $paragraph-> field_rounded_profile_image->first()->getValue();

    if ($rounded['value'] == '1') {
      $variables['attributes']['class'][] = 'rounded-image';
    }
  }
}

And then via CSS (Sass) you'd do:
.paragraph-profile-card {
  &.rounded-image {
    .field-profile-image {
      // rounded image styles
      // ...
    }
  }
}

Comment: Thanks for this. It definitely works. The reason I wanted to just add the class to the image was due to the fact that I already have that modifier class available globally and figured it'd be one less style to add. But again, this works too, so thanks again!


How do I get .NET Feature Management to use config in User Secrets?

Question: I've got an ASPNET Core web app (.NET 6). I have User Secrets enabled and Feature Management enabled.
I would like to override some flags in my user secrets. However, by default, Feature Management reads from the FeatureManagement section of config, but doesn't read from user secrets.
How do I get FeatureManagement to read from user secrets as well as other config sources?
Answer: Assuming you have set up your project for User Secrets, you simply have to call AddUserSecrets when building your configuration.
This is automatically done for you when using WebHost.CreateDefaultBuilder, but isn't if you manually initialise the builder (several hours could be lost if you forget this important fact - ask me how I know...)


Find values in numpy array space-efficiently

Question: I am trying to create a copy of my numpy array that contains only certain values. This is the code I was using:
A = np.array([[1,2,3],[4,5,6],[7,8,9]])
query_val = 5
B = (A == query_val) * np.array(query_val, dtype=np.uint16)

... which does exactly what I want.
Now, I'd like query_val to be more than just one value. The answer here:  Numpy where function multiple conditions suggests using a logical and operation, but that's very space inefficient because you use == several times, creating multiple intermediate results.
In my case, that means I don't have enough RAM to do it. Is there a way to do this properly in native numpy with minimal space overhead?
Comment: Could there be duplicates in `A`?
Comment: Yes, there will be duplicates.
Answer: Here's one approach using np.searchsorted -
def mask_in(a, b):
    idx = np.searchsorted(b,a)
    idx[idx==b.size] = 0
    return np.where(b[idx]==a, a,0)

Sample run -
In [356]: a
Out[356]:
array([[5, 1, 4],
       [4, 5, 6],
       [2, 4, 9]])

In [357]: b
Out[357]: array([2, 4, 5])

In [358]: mask_in(a,b)
Out[358]:
array([[5, 0, 4],
       [4, 5, 0],
       [2, 4, 0]])

Comment: Thanks. Though, if I see this right, this needs to allocate many times the space of the full-size array (1. a, 2. idx, 3. idx==b.size, 4. b[idx], 5. b[idx]==a, 6. np.where(...)) while my code needs 2 full-size allocations.
Comment: @fns  We can easily write back to the results to the input array with the mask `b[idx]==a` if you don't want a copy as output. So, do you want a copy or write back?
Comment: @fns Other than that, we have have memory occupancy for `idx` and `b[idx]`. Since, we have duplicates in `a`, there won't be an easy solution to it. If memory is super critical for you, I think you should stick to a loopy solution.


Recover deleted mailbox and user- no AD recycle bin

Question: I deleted a users mailbox in the ECP- AD user was of course also deleted. The recycle bin is not enabled.
Is the only way to recover the user and mailbox with an authoritative restore?
Answer:
You can't restore the mailbox by restoring the user account. If you don't have a backup of the mailbox then see this link:

https://technet.microsoft.com/en-us/library/jj863438(v=exchg.150).aspx

You can restore the deleted user account with the ADResore utility from Sysinternals:

https://technet.microsoft.com/en-us/sysinternals/bb963906.aspx
Comment: The ADRestore has been last updated in 2006.
Although the article includes support for Windows 2008 R2, I would consider it's usage as a bit risky and double-check if it will work properly in your environment.
Comment: ADRestore isn't doing anything that you can't do yourself with NTDSUTIL (which isn't deprecated). ADRestore is just simplifying the process.
Answer: As far as I am aware apart from pulling the data from a backup you will have to use Authoritative Restore. Definitely interested in seeing i there is an alternative myself.


How can this buying logic be achieved using drupal commerce and/or ubercart?

Question: I think the following scheme describes best what I am trying to achieve:

I am trying to make a ticket booking "shop" if you will.

There are different events
For each event you can buy tickets, like the graphic above shows
There are different ticket types, like normal, vip and special vip (for instance)
Each ticket type can vary in its price depending on the date
The visitor should be able book several tickets for that event at once
Optional: beneath the table is a summary of the selected tickets/ total price
The visitor can checkout and pay, gets a summary (different story)

My attempts so far
On an existing drupal project I installed the commerce module.
I installed commerce booking since it pretty much claims to do what I am looking for. Unfortunately there has been a bug in this module for several months making it unusable, there is no fix there yet (https://www.drupal.org/node/2134449 for instance). What a bummer.
So I installed drupal commerce kickstarter and tried around a little bit in here.
I came up with a product type/ variation "Event", two taxonomy vocabs "Ticket Type" and "Date" and added taxonomy reference fields to the event/ product type.
The cool thing is I can now add a new event "Jam session at Alex's" and add many product variations in it.
For instance I can add a variation which's price is 1 €, pick a term for a date like "Date 01" and pick a term for the type of ticket like "Ticket Normal". With these fields I can add x numbers of product variations to actually depict the variety of tickets as shown in the graphic. So far so good.
However, I cant manage to create an output like shown in the graphic, how would you do that with views? How could you implement an ajax quantity indicator (it actually should work like the add to cart form, but with AJAX) and adding a payment process right after? Help would be greatly appreciated.
I havent tried to use ubercart yet, would it be far more easy to do it with uc, maybe?
Comment: got most of the above scheme working, using add to cart extra quantity field, taxonomies and views matrix fyi.
Answer: This isn't going to be easy to do with either Drupal Commerce or Ubercart. What you're proposing is a very specific, custom bulk Add to Cart form. You're going to have to code it yourself in a site-specific module. The closest you can get would be Commerce Cart Extras, but you'd still have to reformat it to look like your proposed grid and also to have a live updating order total in the footer.


Importing joptimizer as external JAR file fails in eclipse

Question: I'm trying to use the JOptimizer library (http://www.joptimizer.com/). I've downloaded the .jar file and added it to the project by using the Project->Properties->Java Build Path->Libraries->Add External JARs.
I've then imported the relevant library, and Eclipse recognized the import:
<code>import src.main.java.com.joptimizer.optimizers.*;
</code>
However, in project explorer, all the packages in the jar are showed as empty, and I'm not able to use any of the classes listed in the package's documentation: http://www.joptimizer.com/apidocs/index.html  When I try to organize imports (ctrl-shift-o), the import disappears.
What could be wrong here?
Answer: There are actually 3 downloads available - one is XXX-sources.jar (the default), and XXX.jar, and XXX-dependencies.jar.zip are the other two. I had the same problem as you and fixed it by downloading the latter two files, unzipping the zip, and pointing to the contents of the zip and optimizer jar, NOT the sources jar.


C++ fstream and printing to terminal

Question: I've got a bit of code that I am trying to get to work. Basically I want to open a file and print the contents to the terminal. Right now I've just got a list (1-10) in a .txt file in the same folder as my .cpp file.
<code>int main() {
  ifstream inFile;
  inFile.open("numbers.txt");

  if( inFile.fail()) {
    cout<<"Error opening file "<< endl;
    return 0;
  }

  while(!(inFile.fail())) {
    int x;
    inFile >> x;
    cout<<x<< endl;
  }
}
</code>
This is what I have so far and it works to open the file and print to the console. Only issue is, that it prints the last line of the file twice ( so it print 1-10 fine but prints 10 twice) I've stumped myself trying to figure this out. Any ideas?
Thanks for helping me edit this!
Answer: Try below code
<code>#include <iostream>
#include <fstream>
using namespace std;
int main() {
  ifstream inFile;
  inFile.open("a.txt");

  if( inFile.fail()) {
    cout<<"Error opening file "<< endl;
    return 0;
  }

  int x;
  while(inFile >> x) {
    cout<<x<< endl;
  }
}
</code>
Comment: This reminds me that scanf() and the likes return a value.
Comment: Thank you, I had no idea you could use that line as a boolean expression

C++ fstream and printing to terminal


Shannon's Entropy, manual vs. analytic results differ

Question: Let's say that I have information string A, B, C, D, E.
All letters are equally probable (1/5). So Shannon's formula would give us.
<code># Original Formula
sum(p * log(1/p,2))

# Which can be simplified in this case as
0.2*log(5,2)*5 = 2.321928
</code>
However, if I manually try to count the number of bits that have to asked, I come up with 2.4.
<code>             ABCDE
           /      \
        ABC        DE
       /   \      /  \
     AB     C    D    E
    /   \
   A     B
</code>
2 letters require 3 questions and 3 letters require 2 questions. This means that the average number of questions should be (3+3+2+2+2)/5 = 2.4
Can anyone explain where I am going wrong?
Comment: I am assuming it is because in my manual breakdown theu are not true 50-50 probability splits?
Answer: Shannon entropy gives you a limit on what you could achieve by lossless compressing the data. You can't do better than that, but it's not easy (and maybe not guaranteed) to achieve that limit as well. Your way of doing the compression resembles very much Huffman Coding, which is optimal in the sense that each symbol is associated with a bit string. However, you could have tried to code pairs of symbols, i.e. $AA,AB,...$ and achieve a different bit length; or you may continue to do so as well by considering triples, quadruples etc. The algorithm to converge Shannon entropy may not reveal itself at all. Your coding will reach Shannon entropy limit if the alphabet size is $2^k$, with equiprobable symbols; which is in line with your comment that your splits are not true 50-50 splits.


How to transition from rough vocals to clean vocals?

Question: I am a lead singer on a band, I spent a lot of time learning rough vocals, like in this example:

Now i want to learn clean vocals, there's some practical way to carry my previous learning to this new style?
Comment: I've never faced a similar situation, so I won't venture into a formal answer, but (assuming you normally don't "throat speak") I would suggest that you practice speaking (e.g. reciting poems) and work your vocal resonance and timber in that mode and then little by little (i.e. starting with very simple melodies) transition into singing mode. A lot of information in this stack and elsewhere (e.g. this question https://music.stackexchange.com/questions/46620/what-exactly-is-singing-with-your-head-voice/46635#46635) may help find a balanced vocal resonance.
Comment: This information can be really helpful, It's a really good starting point for improving general technique. I will que the question up for more specific answers.
Answer: José directed me to you because we are having a complementary problem. I am the opposite of you, i'm trying to re-achieve unclean vocals/rough vocals as i used to be able to do, in the most healthy way possible. As I'm in a popular music course in university I have increased my knowledge on technique in clean singing. If you want, we could skype one day and could give you some tips of clean singing as it's easier to explain by speaking to the person directly and giving vocal examples than by written, I know it sounds weird but if it's a problem, I can try my best and explain by written here. But I must admit I do struggle to find sometimes the right way/ words to explain my point ! Have a nice day/evening
Comment: Thanks for taking up my challenge Lydia, however in alignment with the purpose of stack exchange it would be better if you shared some of your experience in writing here, both for the OP's benefit as well as the rest of the community. I'm afraid that, as it is, your answer may not be considered a good one, despite your good will.
Comment: +1 for the initiative,  I kinda want to wait if someone can bring an answer to be shared with the community (following the Stack Exchange alignment), but in the lack of anwers I would be very grateful for the opportunity :)
Comment: Great! Ok no worries! I will do it next week or whenever I have time, I'll share my personal experience!


Como mover elementos no HTML

Question: Estou desenvolvendo uma aplicação e não tenho muito conhecimento sobre HTML. Peguei um template direto no site do bootstrap e estou fazendo algumas alterações para ficar da forma que eu quero, porém estou com o seguinte problema:

Gostaria de saber como mover e alinhar os campos em que estão escondidos, tenho um template base e outro para cada "página", conforme os códigos abaixo:
Template 'novo projeto':
{% extends 'base.html' %}

{% block title %}

    Novo Projeto - {{ block.super }}

{% endblock title %}

{% block body %}

Novo Projeto

    <form action="." method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Simular</button>
    </form>

{% endblock body %}

Template 'base':

<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
        <title>{% block title %} Projeto 2 {% endblock title %}</title>

          <link href="{% static 'css/menu.css' %}" rel="stylesheet">

            Teste
                <button class="navbar-toggler position-absolute d-md-none collapsed" type="button" data-toggle="collapse" data-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation">

                </button>
                <input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">

                    Sair

                    Novo Projeto (current)

                    Meus Projetos

                    Perfil

                Sobre a aplicação

                    Informações

        {% block body %}

        {% endblock body %}

Caso seja necessário segue o link oficial do template no bootstrap:
https://getbootstrap.com/docs/4.5/examples/dashboard/
Comment: você pode mudar a propriedade `margin` ou `margin-left` no css pra resolver isso
Comment: tente verificar as documentações de espaçamento do bootstrap [Espaçamento Bootstrap](https://getbootstrap.com.br/docs/4.1/utilities/spacing/)
Answer: Use o CSS para posicionar os elementos na sua  tela:
item {
  clear: both;
}

Se não for:
item: {
  position: relative;
  left: 35%;
}

Comment: Obrigado, mas desse jeito não deu certo. Consegui de outra forma, vou postar como resposta!!
Answer: Coloquei um div container envolvendo o form no html e modifiquei deixando da forma que eu queria mexendo no css.
O css ficou da seguinte maneira:
#containerForm{
  float: right;
  width: 1050px;
}

Estou incluindo um print para mais detalhes:
Answer:

Comment: Considere adicionar uma breve explicação da sua solução.

Como mover elementos no HTML


tensorflow cannot import name container_types

Question: I've just compiled tensorflow from source code with GPU support on OSX.
This was with a few hick-ups and hacks along the way:

based on this issue I've checkout commit 49dcb6c769d60206eb845eb249fa3ef6bc333457 from the 24th of August  2017 (to get past the XLA namespace related error)
I've also manually taken out the -lgomp flag as well

Finally I've compiled the .whl file and installed in a virtual environment, however, when I try to import tensorflow, I get these errors:
import tensorflow
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Volumes/GP_2T/tensorflow_tutorials/tf_src/venv/lib/python2.7/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/Volumes/GP_2T/tensorflow_tutorials/tf_src/venv/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 63, in <module>
    from tensorflow.python.framework.framework_lib import *
  File "/Volumes/GP_2T/tensorflow_tutorials/tf_src/venv/lib/python2.7/site-packages/tensorflow/python/framework/framework_lib.py", line 102, in <module>
    from tensorflow.python.framework.importer import import_graph_def
  File "/Volumes/GP_2T/tensorflow_tutorials/tf_src/venv/lib/python2.7/site-packages/tensorflow/python/framework/importer.py", line 30, in <module>
    from tensorflow.python.framework import function
  File "/Volumes/GP_2T/tensorflow_tutorials/tf_src/venv/lib/python2.7/site-packages/tensorflow/python/framework/function.py", line 33, in <module>
    from tensorflow.python.ops import resource_variable_ops
  File "/Volumes/GP_2T/tensorflow_tutorials/tf_src/venv/lib/python2.7/site-packages/tensorflow/python/ops/resource_variable_ops.py", line 25, in <module>
    from tensorflow.python.eager import custom_gradient
  File "/Volumes/GP_2T/tensorflow_tutorials/tf_src/venv/lib/python2.7/site-packages/tensorflow/python/eager/custom_gradient.py", line 23, in <module>
    from tensorflow.python.eager import tape
  File "/Volumes/GP_2T/tensorflow_tutorials/tf_src/venv/lib/python2.7/site-packages/tensorflow/python/eager/tape.py", line 23, in <module>
    from autograd import container_types
ImportError: cannot import name container_types

My setup is OSX 10.11.5 with bazel 0.5.4, CUDA 8.0, cudnn 5.1 and XCode 7.0
Has anyone else bumped into this issue ?
Any clues on how I could get myself unstuck / what should I double check ?
Comment: install older version of `autograd ¯\_(ツ)_/¯` also I've found that they [moved](https://github.com/HIPS/autograd/commit/7e382b441f81f645568cacfba8591cc70a9c9bd3) `container_types` so this might be the case
Comment: @Aiven Thanks for the tip. I'll follow the container_types thread to see if I can hack my way through it
Answer: Eventually solved the issue by pulling the latest version from the repo (currently 1.6.0-rc0) and using a few super helpful github comments on Eigen and Protobuf errors.
More details in this answer


Getting property from c# anonymous object

Question: On a server, I get JSON objects. I use JsonConvert to deserialize them into anonymous objects. I then want to access the members, but I can't do something like:
object a = jsonObj.something.something.else;

So I created the following, with the intention of being able to access a member using an array of selector strings. However, getProperty() here always returns null. Any ideas?
private object recGetProperty(object currentNode, string[] selectors, int index) {
    try {
        Type nodeType = currentNode.GetType();
        object nextNode = nodeType.GetProperty(selectors[index]);
        if (index == (selectors.Length - 1)) {
            return nextNode;
        }
        else {
            return recGetProperty(nextNode, selectors, index + 1);
        }
    }
    catch (Exception e) {
        return null;
    }
}

private object getProperty(object root, string[] selectors) {
    return recGetProperty(root, selectors, 0);
}

Comment: `but you can't do something like:...` Why? have you tried to use *dynamic* keyword?
Comment: you can with dynamics.  Look at [this post](http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object)
Comment: I'm new to c#. I haven't heard of this yet. I'll look into it.
Comment: dynamic allows for the "." notation access, but can this be used to access using a series of strings? String indexing doesn't work on a dynamic type object, it seems.
Answer: JsonConvert.DeserializeObject does not deserialize to anonymous object (I guess, you don't use JsonConvert.DeserializeAnonymousType). Depending on json it returns either JObject or JArray.
1. Since JObject implements IDictionary<string, JToken> you can use it this way
string json = @"{prop1:{prop2:""abc""}}";

JObject jsonObj = JsonConvert.DeserializeObject(json) as JObject;
Console.WriteLine(jsonObj["prop1"]["prop2"]);

or
string str = (string)jsonObj.SelectToken("prop1.prop2");

2. If you want to use the dynamic keyword, then
dynamic jsonObj = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonObj.prop1.prop2);

Both ways will print abc
Answer: my code
Dictionary<string, object> dictionaryObject = new Dictionary<string, object>();
        if (anonymousObject is string)
        {
            dictionaryObject = JsonConvert.DeserializeObject<Dictionary<string,object>>((string)anonymousObject);
        }
        if (!dictionaryObject.ContainsKey(propertyName))
        {
            throw new Exception($"property name '{propertyName}' not found");
        }
        object value = dictionaryObject[propertyName];


Como fazer para o programa reconhecer ' x ' como multiplicação?

Question: Tem como tratar x como *, pois o usuário vai digitar x para multiplicar num número, teria como o programa reconhecer x como multiplicação via a código?
exemplo double b = 5 x 5;
Comment: Quando você diz "usuário" quer dizer a pessoa que usa o sistema que você criou em Java ou você mesmo programando em Java? Não ficou claro se vc pretende trocar o `*` por `x` na hora de programar (isto é, no código) ou fazer a avaliação da expressão matemática digitada pelo usuário em uma UI. Se for o segundo caso, dé uma olhada nesta outra pergunta: http://pt.stackoverflow.com/questions/51324/como-calcular-express%C3%A3o-matematicas-numa-string
Comment: No código Java em si, não. Mas na entrada de dados dele, claro que tem, depende de como você está cuidando disto. Edite a pergunta postando seu código.
Comment: mesmo o usuário mais leigo utiliza o *, não faz sentido pensar que ele irá digitar X...
Answer: Não. O operador de multiplicação no Java é o *. Porém, você pode fazer isso para o usuário final.
Por exemplo, ele até pode digitar 5 x 5 como uma multiplicação, daí o programa recebe a string e substitui o x por * e avaliar matematicamente a expressão resultante da substituição.
Por que é assim?
Vamos supor as seguintes instruções matemáticas num código Java:
int x = 10;
int a = 10 * x; //Compila corretamente, com a recebendo o valor 100;
int b = 10 x x; //Como deve ser entendido cada x? Um é multiplicação e outro é identificador?
                //Duas multiplicações?
                //Dois identificadores?

A linguagem deve ser uniforme e precisa. Caso contrário, imprevisibilidades ocorrem e ninguém sabe por que diabos o código não faz o que deveria ser feito.
Como solucionar esse problema?
Quando você recebe a entrada do usuário, você pode alterá-la sem o conhecimento dele e mostrar o resultado correto com uma expressão diferente da dele, desde que a expressão usada para calcular seja equivalente à que o usuário deu ao programa.
Exemplo: Calculadora com interface gráfica
Vamos supor uma calculadora tradicional, com números de 0 a 9 e apenas o operador de multiplicação (para simplificar).
Cada número coloca o valor dele no visor e o botão de multiplicação coloca a letra x. O que o botão de = deveria fazer?
O algoritmo seria:

Recuperar a string que o usuário criou e atribuir a uma variável;
Substituir todos os x da variável por *. Facilmente feito com replaceAll, e note que não é necessário que essa String nova seja mostrada ao usuário;
Fazer o parsing dos números que cada * circunda e multiplicar;
Substituir na string com o resultado;
String só tem números? Mostrar ao usuário;
Caso contrário, volte ao passo 3.
Answer: Pela tag da pergunta, vou presumir que você está implementando em Java.
Existem várias maneiras de fazer isso, a que vou sugerir é apenas uma delas, não necessariamente a melhor ou mais simples:

Fazer o parsing da expressão e converter os símbolos que o usuário entende para o símbolos que a linguagem entende. Ex.: de "b = 5 x 5" para "b = 5 * 5".
Passar a string processada para uma biblioteca que faça isso para você, como por exemplo, o BeanShell

Um exemplo hipotético usando BeanShell seria:
Interpreter interp = new Interpreter();
interp.eval("b = 5 * 5");
System.out.println("resultado: b="+interpreter.get("b"));


A simple example of an incomplete probability space?

Question: A probability space is complete if every subset of a set of measure zero is measurable. The probability space is incomplete if otherwise.
But is there a simple example of an incomplete probability space?
Answer: Take the space $\{a,b,c\}$ with measurable sets $\{a,b\},\{c\},\{a,b,c\},\{\}$ where the measure of $\{a,b\}$ is 0 and the measure of $\{c\}$ 1. Then we have an incomplete measure space as $\{a\}$ (and $\{b\}$) are unmeasurable subsets of the null set $\{a,b\}$.


logback loading all appenders

Question: I have a logback.xml file with 3 appender in : 1 ConsoleAppender and 2 FileAppender
<?xml version="1.0" encoding="UTF-8"?>

<configuration>
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <Target>System.out</Target>
        <encoder>
            <pattern>[%d{yyyy-MM-dd HH:mm:ss}] %msg%m%n%ex</pattern>
        </encoder>
    </appender>

    <appender name="bAppender" class="ch.qos.logback.core.FileAppender">
        <file>logs/b.txt</file>
        <append>true</append>
        <encoder>
            <pattern>[%d{yyyy-MM-dd HH:mm:ss}] -[%t] %-4r %-5p %c : %n%m%n</pattern>
        </encoder>
    </appender>

    <appender name="aAppender" class="ch.qos.logback.core.FileAppender">
        <file>logs/a.txt</file>
        <append>false</append>
        <encoder>
            <pattern>[%d{dd/MM/yyyy : HH:mm:ss}  %level - %logger] %m%n</pattern>
        </encoder>
    </appender>

    <logger name="aLogger" additivity="false">
        <level value="DEBUG" />
        <appender-ref ref="aAppender" />
    </logger>

    <root level="info">
        <appender-ref ref="stdout"/>
    </root>
</configuration>

The problem is when i launch the program associated with aLogger(Logger LOGGER = LoggerFactory.getLogger("aLogger");. It add the bAppend as well ( and so create a empty b.txt file ....)
It's like logback call and execute all appender when a logger is called regardless attached appender.
How to avoid this behaviour ?
Thank you very much
Answer: Maybe late to answer, but I do need same result as you @ulquiorra
So based on my search I did come across this solution: use SiftingAppender
example :
<appender name="bAppender" class="ch.qos.logback.classic.sift.SiftingAppender">
    <discriminator>
        <key>logFileName</key>
        <defaultValue>b</defaultValue>
    </discriminator>
    <sift>
        <appender name="${logFileName}" class="ch.qos.logback.core.FileAppender">
            <file>logs/${logFileName}.txt</file>

            <encoder>
                <pattern>[%d{dd/MM/yyyy : HH:mm:ss}  %level - %logger] %m%n</pattern>
            </encoder>
        </appender>
    </sift>
</appender>

From LogBack Jira: https://jira.qos.ch/browse/LOGBACK-202

If you wrap a FileAppender with a SiftingAppender, then the
  FileAppender will be created on the first log event, and thus the log
  file will be created in a lazy manner.

Take a look also on documentation https://logback.qos.ch/manual/appenders.html#SiftingAppender
Another example on https://www.mkyong.com/logging/logback-xml-example/
Answer: In short, I think the answer is 'no', there isn't a way to prevent b.txt from being created. Looking at the source for FileAppender, it appears that the output file (and the corresponding parent folder hierarchy) is created when the appender is started (which happens when logback is initialized). This design is deliberate, since this approach will save considerable time during logging.
Comment: Thank you very much . Damn i thought that the appender start when the corresponding logger is called. I can't afford the creation of a empty file when i run an other program. Maybe the creation of another separated logback file could resolve this ?

logback loading all appenders


Why does the eMail in my Rules Component use a theme that differs from page-theme?

Question: I use the Rules module to send follow-up emails, which works fine.
In the past I used a different theme for my site, and somehow this theme (call it "old-theme" for now) is applied when a follow-up email is sent (Mime Mail).
How do I apply the current site-theme to my Rules Component?
Answer: You may want to check the result you get if you do NOT tell Mime Mail to use the site's stylesheet. And combine this with creating a file in your theme that is named mail.css. If you do that, then Mime Mail should automatically use that when sending emails. For more details on that, refer to its README.txt, i.e.:

Email messages are formatted using the mimemail-message.tpl.php template.
  This includes a CSS style sheet and uses an HTML version of the text.
  The included CSS is either:

the mail.css file found anywhere in your theme folder or
the combined CSS style sheets of your theme if enabled.

Also make sure your theme is set as "Theme to render the emails" within admin/config/system/mailsystem. Without that, the stylesheets used by emails sent via cron (for example) may not look like you want them to look.


Base table missing in database?

Question: I just emptied the cache in my Drupal database via MySQL, and all of a sudden I'm getting this error on my home page? Help! How can I fix this? It almost seems like a table was deleted by accident?
Original

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'databasename.entity_test_type' doesn't exist:
  SELECT et.* FROM {entity_test_type} et; Array ( ) in
  entity_test_entity_info() (line 73 of
  /var/www/drupal/true-001/sites/all/modules/contrib/entity/tests/entity_test.module).

Additional

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'databasename.locales_source' doesn't exist:
  SELECT lid, location FROM {locales_source} WHERE source = :source AND
  context = :context AND textgroup = 'default'; Array (
  [:source] => An AJAX HTTP error occurred. [:context] => ) in
  _locale_parse_js_file() (line 1563 of /var/www/drupal/true-001/docroot/includes/locale.inc).
Answer: Yes that is correct, the errors are saying entity_test_type and locales_source do not exists. Try searching for them with PHPMyAdmin or any other DB viewer and you will very likely not find them. So yes, somehow those tables got deleted or possibly renamed?

Help! How can I fix this?

If they got deleted, you have the following options:
A) Disable and uninstall those modules, then enable them again and they should create the missing tables.
B) Revert back to a DB backup where those tables exist, then export the 2 tables only. Now revert back to your latest DB backup where they are missing and just import those 2 tables.
C) Manually re-create those tables with the proper column names
Comment: I agree with your answer, but I also find it suspecious to see those "*databasename*" occurences in both error messages. Maybe that rings other bells? BTW, for "b)", how about first creating a new backup "now", so that in the 2nd phrase of this bulet you revert to the now-backup?

Base table missing in database?


Write the system of equations describing the populations in this system...

Question: In a closed ecosystem, we have that Frogs,represented by $F(t)$, eat fleas, represented by $f(t)$, and the fleas eat fungus, represented by $g(t)$.
Assuming that fungus grows at rate A, fleas eat the fungus at rate B, frogs eat the fleas at rate C, and frogs die at rate D, write the system of equations describing the populations in this system:

My attempt:
Fungus grows at rate A, which means $dg/dt = A$
Frog = $dF/dt = C-D$ as frogs thrive on eating fleas and dying at rate D
Fleas = $df/dt = -C $ as frogs are eating fleas at rate C
Why is this wrong?
Answer: The rates aren't fixed; they are proportional to the size of the population. For the fungus, for example, you might have $\frac{dg}{dt}=Ag(t)-Bf(t)$, rather than $\frac{dg}{dt}=A-B$. This should make sense if you think about it for a second. If the flea population was zero, would they be able to eat the fungus? If the fungus population was zero, how would they reproduce?
It is also generally assumed that a population grows in a way proportional to both the current population, and the available food. So the flea equation would be $\frac{df}{dt}=Bf(t)-CF(t)$, rather than $\frac{df}{dt}=-CF(t)$.