How to strip all array keys appended with :protected?

Question: I'm trying to replicate entity->export() using Entity Metadata Wrappers. When I call value() on entity_metadata_wrapped entities (in this case a field collection), I get everything entity->export() give me, plus a bunch of entity_key:protected fields. I'd like to strip these out, as everything not protected gives me identical values to that provided in export.
Example wrapper->value() result:
Object
(
    [fieldInfo:protected] =>
    [hostEntity:protected] =>
    [hostEntityId:protected] =>
    [hostEntityRevisionId:protected] =>
    [hostEntityType:protected] =>
    [langcode:protected] => und
    [item_id] => 9
    [revision_id] => 9
    [field_name] => field_treatment_categories
    [default_revision] => 1
    [archived] => 0
    [entityType:protected] => field_collection_item
    [entityInfo:protected] => Array
        (
            [label] => Field collection item
            [label callback] => entity_class_label
            [uri callback] => entity_class_uri
            [entity class] => FieldCollectionItemEntity
            [controller class] => EntityAPIController
            [base table] => field_collection_item
            [revision table] => field_collection_item_revision
            [fieldable] => 1
            [redirect] =>
            [entity keys] => Array
                (
                    [id] => item_id
                    [revision] => revision_id
                    [bundle] => field_name
                    [uuid] => uuid
                )

            [module] => field_collection
            [view modes] => Array
                (
                    [full] => Array
                        (
                            [label] => Full content
                            [custom settings] =>
                        )

                    [token] => Array
                        (
                            [label] => Tokens
                            [custom settings] =>
                        )

                )

            [access callback] => field_collection_item_access
            [metadata controller class] => FieldCollectionItemMetadataController
            [bundles] => Array
                (
                    [field_treatment_categories] => Array
                        (
                            [label] => Field collection field_treatment_categories
                            [admin] => Array
                                (
                                    [path] => admin/structure/field-collections/%field_collection_field_name
                                    [real path] => admin/structure/field-collections/field-treatment-categories
                                    [bundle argument] => 3
                                    [access arguments] => Array
                                        (
                                            [0] => administer field collections
                                        )

                                )

                            [rdf_mapping] => Array
                                (
                                )

                        )

                    [field_treatments] => Array
                        (
                            [label] => Field collection field_treatments
                            [admin] => Array
                                (
                                    [path] => admin/structure/field-collections/%field_collection_field_name
                                    [real path] => admin/structure/field-collections/field-treatments
                                    [bundle argument] => 3
                                    [access arguments] => Array
                                        (
                                            [0] => administer field collections
                                        )

                                )

                            [rdf_mapping] => Array
                                (
                                )

                        )

                )

            [static cache] => 1
            [field cache] => 1
            [load hook] => field_collection_item_load
            [translation] => Array
                (
                )

            [schema_fields_sql] => Array
                (
                    [base table] => Array
                        (
                            [0] => item_id
                            [1] => revision_id
                            [2] => field_name
                            [3] => archived
                            [4] => uuid
                        )

                    [revision table] => Array
                        (
                            [0] => revision_id
                            [1] => item_id
                        )

                )

            [token type] => field_collection_item
            [apachesolr] => Array
                (
                    [indexable] =>
                    [status callback] =>
                    [document callback] =>
                    [reindex callback] =>
                    [bundles changed callback] =>
                )

            [configuration] =>
            [uuid] => 1
        )

    [idKey:protected] => item_id
    [nameKey:protected] => item_id
    [statusKey:protected] => status
    [defaultLabel:protected] =>
    [uuid] => c1d3982f-31c8-4640-89b4-2f54334e4803
    [field_tc_short_description] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => short desc 2
                            [format] =>
                            [safe_value] => short desc 2
                        )

                )

        )

    [field_tc_short_title] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => Short title 2
                            [format] =>
                            [safe_value] => Short title 2
                        )

                )

        )

    [field_tc_title] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => Treatment Category 2
                            [format] =>
                            [safe_value] => Treatment Category 2
                        )

                )

        )

    [field_treatments] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => 10
                            [revision_id] => 10
                        )

                    [1] => Array
                        (
                            [value] => 11
                            [revision_id] => 11
                        )

                )

        )

    [rdf_mapping] => Array
        (
        )

    [entity_view_prepared] => 1
)

The [fieldInfo:protected] fields I'd like to remove, but I haven't found an options/methods to do so. Any thoughts?
Answer: use array_walk and scan the entity array to see if the key has the substring :protected in it. If yes, then unset() the array key.
Comment: While I am hoping for existing functionality, that's a good alternative. Cheers.
Comment: Because these were object properties, looping would not work to strip them out. You could use this method and construct a second array containing only the values foreach or array_walk can touch, providing a similar result.
Answer: For anyone looking to do this, the answer is pretty simple.
entity_metadata_wrapper->value() returns an object, complete with protected properties. To get only the values from the result, you can use php's get_object_vars() function.
This returns data equivalent to a normal entity->export() call in terms of data, although I believe export returns JSON instead of the array you get here.
So:
// Wrap an existing entity.
$wrapper = entity_metadata_wrapper('entity_type', $entity);

// Get the object representation of that entity.
$entity_data = $wrapper->value();

// Strip all properties (including :protected),
// and get an array representation of that data.
// This is the same data you get from entity->export(),
// but in array form.
$final_data = get_object_vars($entity_data);

Hope this helps someone.
Answer: You can't, because what you're seeing it's not an array, but an object, so you can't simply unset protected properties, because they're protected for the reason.

Members declared protected can be accessed only within the class itself and by inherited classes.

This is how PHP OOP visibility works. So you should find appropriate getter/setter method to change that member of class or extend that class and define one.


How to ask for user confirmation when submitting a form using FAPI

Question: What I want is suppose a user enters same data twice in two rows then I want to show her an error/warning and now if she chooses to press submit again then I'd process and accept the form.
How to do it?
Answer: use the confirm_form function. See Here and Here for examples

This function returns a complete form array for confirming an action.
  The form contains a confirm button as well as a cancellation link that
  allows a user to abort the action.
Comment: In the second comment link there is a _submit handler in the bottom of the code: mymodule_form_submit. What I'm confused is after confirming it, again the else part of _submit handler is executed but how do I get the first form's form_state values? As all those I need them to save it in the database


DNS server is not working - timed out

Question: I have 2 child controllers. But one of the controller can resolve names and the other doesn't. I can't find out the cause. Any suggestions to troubleshoot this?
Edit: It seems like AD_child_02 cannot resolve example.com but it can resolve testserver1.example.com.
AD_child_01 can resolve example.com and it can also resolve testserver1.example.com
AD_child_01 (10.10.10.10) - test1.example.com
AD_child_02 (10.10.10.20) - test1.example.com
When testing with AD_child_01 :
nslookup test_server 10.10.10.10
Server:  AD_child_01
Address:  10.10.10.10

Non-authoritative answer:
Name:    test_server
Addresses:  10.10.10.30

When testing with AD_child_02 :
nslookup test_server 10.10.10.20
Server:  AD_child_02
Address:  10.10.10.20

DNS request timed out.
    timeout was 2 seconds.
DNS request timed out.
    timeout was 2 seconds.
DNS request timed out.
    timeout was 2 seconds.
DNS request timed out.
    timeout was 2 seconds.
*** Request to AD_child_02  timed-out0

Comment: DNS Server service on AD_child_02 started? Local nslookup on AD_child_02 works? Netstat on AD_child_02 shows listening port 53? Firewall on AD_child_02 set up correctly for TCP/UDP 53?
Comment: Updated the question. It can resolve x.example.com but it cannot resolve example.com. anything with xx.example.com is the entries that are in AD_child_02. But it should be forwarding or something like to resolve the other address. I'm not sure what's wrong. AD_child_01 works btw. There is no firewall issue or port issue. Everything is open.
Answer: Found out the issue. AD_child_02 forwarder was pointing to old (non existence) domain controller. I updated forwarder  to point to AD_Parent_01 and now it can resolve example.com

DNS server is not working - timed out


How to write loop to optimize the given number

Question: I have some amount (value) say x= 7180.7 ,need to divide this amount to five variables say A=1225.00,B=355.25,C=6775.00 ,D=253.85,E=235.00 such that the  remainder value of x should be as low as possible.
Ex: From x=7180.7 I can have 3*A (3*1225=3675), 3*B (3*355.25 ), 4*D (4*253.85) , 4*E (4*235.00) .
3*A + 3*B + 0*C + 4*D + 4*E= 6696.15   Difference=7180.7-6696.15=484.55
like this I can get different combination of A,B,C,D ,but I want the best possible of A,B,C,D which minimises the difference .
I have tried the below code :
RemAmt=c(As,Bs,Cs,Ds,Es)
sumrem=AmtArem+AmtBrem+AmtCrem+AmtDrem+AmtErem

Comment: Can you proof read your question _very_ carefully and make edits as necessary?  In your example, why is there 2A, 3B, **no C**, 4D, and then **4**E?  And also, when in the parenthesis of your example do you say things like **2A (3*...)**?  Also, why is there a **D*E**?
Comment: This is actually an interesting problem (if I understand), but it is not well explained. Using multiples of a set of five numbers what is the combination that gets closest to some target value without exceeding it. The question then is what is an efficient approach to systematically arrive at the result.
Comment: This is an integer programming/optimizing problem. I think for the given values you can try all combinations with coefficients for A lower than 6, cB lower than 20, ...
Comment: Also please include any attempt from your side at finding a computational solution. Otherwise this sounds too much like a "gimme teh codez" question. I agree with @AaronHayman in that this may be an interesting code challenge. Even more so you should try for yourself first.
Answer: Here is a solution of the problem:
x <- 7180.7
Parts <- c(A=1225.00, B=355.25, C=6775.00, D=253.85, E=235.00)
maxCoef <- x %/% Parts
prod(maxCoef+1) ### number of combinations
Comb <- expand.grid(A=0:maxCoef["A"], B=0:maxCoef["B"], C=0:maxCoef["C"],
            D=0:maxCoef["D"], E=0:maxCoef["E"])
Comb$residuum <- x - as.matrix(Comb) %*% Parts
Comb$residuum <- ifelse(Comb$residuum<0, 9999, Comb$residuum)
i <- which.min(Comb$residuum)
Comb[i, ]
# > Comb[i, ]
#        A B C  D  E residuum
# 112903 0 1 0 13 15      0.4

The call to expand.grid() can be shorten to
expand.grid(lapply(maxCoef, ':', 0))

Comment: Thanks a lot jog,It works now.
Comment: @PraveenChougale **Please close this question by setting the green check mark next to the answer.** This also applies to *all* of your other questions for which you have gotten an answer.


Pegando nome de usuário (windows)

Question: Olá
Estou tentando pegar o nome do usuário logado no windows, algo que obtive sucesso com o
Environment.UserName

porém, quando eu publico a aplicação, o nome que me retorna é "DotNetCore", que é um usuário criado pelo SKD.
Tem alguma forma que pego do usuário mesmo?
Answer: Tente capturar o nome do usuário logado na máquina
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
Comment: Não deu certo.. agora voltou como resultado isso:
"IIS APPPOOL\DotNetCore"
Answer: Você precisa que a sua aplicação esteja configurada para fazer autenticação integrada no windows
Segue exemplo de configação
No caso, esse dotnetcore ou coisa do tipo é pq a autenticação está habilitada para anonymous.

Pegando nome de usuário (windows)


Quotients and continuous maps

Question: Suppose $f:\mathbb R\times \mathbb R\to \mathbb R/\mathbb Z\times \mathbb R/\mathbb Z$ where the domain is given the usual topology and the latter the quotient topology. Why then is the restriction $f|_S:S\to f(S)$, where $S=\{(x,\sqrt{5} x): x\in \mathbb R\}$ not continuous with continuous inverse?
If I am not wrong, the quotient topology is comprised of sets whose preimages are open.
I can prove that $f|_S^{-1}$ is well-defined by showing that $f|_S$ is bijective, but I don't know why they are not continuous.
Comment: are you asking for a proof or for intuition?
Comment: the intuition is that $f|_S$ maps distant points in $S$ to nearby points in the codomain so that the $f|_S^{-1}$ would have to tear those nearby points away from each other.
Answer: Let $\alpha=\frac12\sqrt2$, and let $p_n=\left\langle n\alpha,n\alpha\sqrt5\right\rangle\in S$ for $n\in\Bbb N$; then $\{f(p_n):n\in\Bbb N\}$ is dense in $\left(\Bbb R/\Bbb Z\right)^2$. Thus, there is a strictly increasing sequence $\langle n(k):k\in\Bbb N\rangle$ in $\Bbb N$ such that $$\left\langle f(p_{n(k)}):k\in\Bbb N\right\rangle\to p_0$$ in $\left(\Bbb R/\Bbb Z\right)^2$. Let $g=f\upharpoonright S$, and let $h=g^{-1}$. If $h$ were continuous, we'd have $$\left\langle p_{n(k)}:k\in\Bbb N\right\rangle=\left\langle h\left(f(p_{n(k)})\right):k\in\Bbb N\right\rangle\to h(p_0)=\langle 0,0\rangle\;,$$ which is absurd.
The density of $\{f(p_n):n\in\Bbb N\}$ in $\left(\Bbb R/\Bbb Z\right)^2$ follows from the fact that $1,\alpha$, and $\alpha\sqrt5$ are pairwise incommensurate: none of them is a rational multiple of another.

Quotients and continuous maps


TypeScript - Representar o resto dos parâmetros de um componente em uma Interface

Question: Tenho um componente de Input que utiliza o TextInput do React Native. Este componente deve aceitar a propriedade append, e qualquer outra propriedade que lhe for passada será atribuída ao componente TextInput:
interface InputProps {
  append: string;
}

const Input: React.FC<InputProps> = ({append, ...props}) => {
  return (
    <>
      <Append>{append}</Append>

      <TextInput {...props} />
    </>
  )
}

Utilização:
const Home: React.FC = () => {
  return (
    <View>
      <Input append="R$" placeholder="0,00" />
    </View>
  )
}

Neste caso, a propriedade placeholder é destacada como inválida por que ela não existe na interface que define as propriedades aceitas pelo componente Input.

Property 'placeholder' does not exists on type 'InstrinsicAttributes & InputProps & {children?: ReactNode;} TS(2322)

Já segui algumas sugestões como utilizar o React.HTMLAttributes<HTMLElement>, mas sem sucesso.
Answer: Amigo tente passe as demais propriedades que não quer declarar no interface por fora da estruturação, assim:
interface InputProps {
  append: string;
}

const Input: React.FC<InputProps> = ({append}: InputProps, ...props) => {
  return (
    <>
      <Append>{append}</Append>

      <TextInput {...props} />
    </>
  )
}


Mixed effects models for nested study design and time-series

Question: The bird auditory surveys consist of >100 roadside survey routes across Ontario. Bird call count was conducted at 10-20 stations along each survey routes for >10 years. For each station, there is data on the amount of forest harvested within the last 5 years.  An objective is to assess how bird abundance is affected by forest harvesting.
My problem is to how to deal with spatial and temporal autocorrelation and the violation of independence of data. That is, the response variable (abundance of birds) is likely to be spatially and temporally autocorrelated. And, the bird abundance at each station is likely correlated with that at other stations within a route. My approach is to incorporate routes and year as random effects in generalized mixed effects models as shown below (using lme4 package). But, I am not sure how well autocorrelation is modeled adequately in this way.
glmer(Abundance ~ Area_harvested + (1 | route) + (1 | Year),
      data = mydata, family = poisson)

Although I specified Poisson above, negative binomial or zero-inflated models (because there are many zeros; abundance = 0) may be more appropriate.
Could anyone please suggest a proper way to analyze my data? Also, could you please suggest better or proper way to specify random effects given my data?
Answer: This is a pretty broad question, but ...

you should definitely check for overdispersion (roughly speaking, the deviance() of the model should be approximately equal to its df.residual(); you can check here for a function to test this
many zeros doesn't necessarily mean zero-inflated; zero-inflation means more zeros than expected, and a Poisson with a small mean or a negative binomial with a small mean and a lot of overdispersion can easily generate lots of zeros
your random effect structure is certainly reasonable, and it's what I would do as a first pass

Making sure you are dealing appropriately with any residual spatial/temporal autocorrelation is harder.

the first thing to do is to see if you can rule out spatial/temporal autocorrelation.
try a spatial plot of the residuals (e.g. x,y coordinates; circles in red or blue depending on whether residuals are positive or negative, with size proportional to the absolute value) and see if there are obvious patterns.
try plotting the residuals one at a time vs your x/y coordinates to see if you need a spatial trend term in your model
if you take the residuals from your model and feed them to nlme::gls with a trivial model (i.e. something like dd <- broom::augment(fitted_model); g <- gls(.resid~1,data=dd)), you can get it to compute and plot temporal autocorrelations (something like plot(ACF(g,form=~Year|route))), or fit a spatial autocorrelation model (again using gls) to the residuals and hope that there's not much happening
if you do need to fit a GLMM with spatial/temporal autocorrelation, take a look at INLA, or use MASS::glmmPQL (the former is more complicated to get working but will almost definitely work better if you can make it go)

PS: make sure you plot your data, and the predictions of your model, and look at the standard diagnostic plots (e.g. see ?plot.merMod, ?ranef.merMod, http://bbolker.github.io/mixedmodels-misc/ecostats_chap.html ...)
Comment: Your answer will certainly get me started and guide me to proper analysis of my data. One question: Could you please explain what ".resid" notation means in gls(.resid~1,data=dd)?
Comment: the `augment()` function generates an "augmented" version of the data (saved as `dd` here) that also contains columns for predicted values, residual values, etc.; `.resid` is the name given to the residual-value column


Accessing large app files using Elastic Beanstalk and Flask?

Question: I'm deploying a flask app through AWS Elastic Beanstalk, and when I try and push my app for deployment, i get an error that the contents are too big. Apparently, there is a hard maximum upload of 512 mb. However, I have some pickle files and a whoosh index that take up more than 1gb of space.
How should I go about giving my flask app access to those large files?
As i understand it, if i were to scp them into the ec2 instance of the elastic beanstalk, it could be lost at any time if the instance is unmounted and replaced.
Thanks in advance for any answers!
Answer: I had the same problem and talked to AWS Technical support. They recommended using S3 for storing large files. Once it's done, you can use ebextensions to mention your files in the "files" section. You must copy into a temporary directory and then use a container command to copy into your application if you need that.
See:
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html#linux-files
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html#linux-container-commands


Query custom node by user Entity Reference

Question: I am trying to build a query that finds all nodes of a custom type where one of the fields is a user Entity Reference.  I am trying to use EntityFieldQuery but just as open to db_select().  The following is just an example of one of the queries I have tried.
$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'custom_node', '=')
  ->fieldCondition('field_marketer', 'value', $user->uid, '=');

$entities = $query->execute();

Thanks in advance for any help.
Comment: Wouldn't that be 'field_user_entity_reference'?
Comment: The actual field name is 'field_marketer'.
Answer: The column name for an entity reference field is target_id, so your code should be:
$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'custom_node', '=')
  ->fieldCondition('field_marketer', 'target_id', $user->uid, '=');

$entities = $query->execute();

Comment: That's it! Thank you again Clive! This was my first attempt at using EntityFieldQuery.


ASP.Net MVC 3 - instantiate data context class in BaseController

Question: When adding a controller in ASP.Net MVC 3 using "Controller with Read/Write actions and views, using EntityFramework" as template, it generates a class as follows:
namespace Project.Controllers
{
    public class Default1Controller : Controller
    {
        private ProjectEntities db = new ProjectEntities();

        ...
    }
}

Now, I would like to know if it would be a good practice to change this so that my Controller would inherit a custom base controller that would instantiate ProjectEntities. It would look as follows:
BaseController:
namespace MatchesHorsConcours.Controllers
{
    public class BaseController : Controller
    {
        protected MatchesEntities db = new MatchesEntities();
        ...
    }
}

Other controllers:
namespace Project.Controllers
{
    public class Default1Controller : BaseController
    {
    ...
    }
}

Comment: It's better practice to use Dependency Injection. There are a number of libraries out there to do this. To name a few, Ninject, Castle Windsor or Autofac
Answer: This technique is useful when you need logic in your master page (for example, to dynamically render menu options). Read about this here: http://www.asp.net/mvc/tutorials/passing-data-to-view-master-pages-cs
However, in general this is not a good technique. I would recommend using dependency injection (Ninject works well with MVC and is easy to implement)
Answer: No absolutely not. It makes totally untestable. Please use repository pattern and constructor injection if possible: Repository Pattern vs DAL


Knockout css binding

Question: I have a button that I want to toggle the class when clicked.
This is what I currently have.

it almost works. When green it works as expected but only has whitishBtn class when white.
Answer: figured it out
selected() ? 'greenishBtn button_small':'whitishBtn button_small'"

Knockout css binding


Erro Cannot use object of type PDOStatement as array

Question: Não estou conseguindo fazer o header location redirecionar para um campo da tabela.
Nesse campo, tem o link de um documento PDF.
Vejam o código:
case 'mostra-id':

$link = Connection::select("SELECT link FROM `arquivos` where id =" . App::$key);

$sql = "update `arquivos` set `acessos`= acessos + 1 where id=" . App::$key;
$dados = Connection::exec($sql);

header('Location: ' . $link['link']);
break;

O link na tabela está gravado dessa forma: sistema/public/arquivos/pdf/01.pdf
O update normalmente está correto, mas não abre o link quando redireciono. Dando o seguinte erro:

Fatal error: Cannot use object of type PDOStatement as array in
Comment: Fiquei meio na dúvida, o link só não aparece pelo header location, mas quando você bota o link direto pelo navegador ele funciona, correto?
Comment: Faça `print_r($link);` e coloque o resultado aqui comnetários.
Comment: PDOStatement Object ( [queryString] => SELECT link FROM `arquivos` where id =10 )
Comment: Não tens de executar o `$link` para obteres o resultado da BD?
Comment: Sim, funcionou dessa forma: header('Location: ' . $link->fetchColumn(0));
Answer:
Cannot use object of type PDOStatement as array in

O erro sugere que o retorno do select não é um array mas provavelmente um objeto, então mude a notação de:
header('Location: ' . $link['link']);

Para:
header('Location: ' . $link->link);

Comment: Deu o mesmo erro.
Answer: $link não é um array para ser manuseado da maneira que você fez, é um objeto PDOStatement então precisa manusear de jeito diferente.
Tente $link->fetchColumn(0), esta é a documentação dele, esse comando irá buscar a primeira coluna da próxima linha do result set.
Comment: Funcionou certinho cara. Muito obrigado.


How can I use pandas.melt to unpivot my dataframe?

Question: I have data as such
        time  close
date
6/1/20 00:00 4375.5
6/1/20 00:15 4374.0
6/1/20 00:30 4376.5
...

I used df.pivot(columns='time', values='close') to output this (which worked as I wanted)
        00:00  00:15  00:30
date
6/1/20 4375.5 4374.0  4376.5
...

I ran the pct change across timeframes df.pct_change(axis=1)
        00:00  00:15  00:30
date
6/1/20   NaN  .00312 .00123  #these are just not real calcs, just putting in nums for example
...

Now I want to melt the df, but I'm having trouble doing so. I want the dataframe to go back to the original layout
        time  pct_change
date
6/1/20 00:00  NaN
6/1/20 00:15 .00312
6/1/20 00:30 .00123
...

The reason I want to do this is because plotly.express.density_heatmap() cannot read the data as in the non-melted form. I'm using streamlit and wanted to insert a chart with plotly but ultimatly the chart just needs to look the same as df.style.background_gradient(cmap='green')
from plotly.express as px

#this code doesnt work, but this is how ideally want to input it.
fig = px.density_heatmap(df, x='time', y='date', z='pct_change')

Thank you to anyone who provides guidance!
Comment: Does this answer your question? [Doing the opposite of pivot in pandas Python](https://stackoverflow.com/questions/48135994/doing-the-opposite-of-pivot-in-pandas-python)
Answer: you are missing a date, you can try this way
df2=df.pivot(index='date', columns=['time'], values='close').pct_change(axis=1)
df2

time    00:00   00:15   00:30
date
6/1/20  NaN     -0.000343   0.000572

df2.unstack().reset_index()

    time    date    0
0   00:00   6/1/20  NaN
1   00:15   6/1/20  -0.000343
2   00:30   6/1/20  0.000572

Answer: This is all going to be much easier if you just have a proper datetime index:
df.reset_index(inplace=True)
df['datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df = df.set_index('datetime').drop(['date', 'time'], axis=1)
print(df.pct_change())

Output:
                        close
datetime
2020-06-01 00:00:00       NaN
2020-06-01 00:15:00 -0.000343
2020-06-01 00:30:00  0.000572


Priors that do not become irrelevant with large sample sizes

Question: This may be a weird question. My colleagues and I are working on a medical estimation problem, where relevant prior knowledge regarding plausible values of some physiological parameters exists. In addition, these parameters can be estimated using time series data, which often have some tens of thousands of samples. What often happens is that, due to model imperfections, MAP estimation converges towards implausible solutions (e.g., very small parameter values). The priors are essentially ignored because they become irrelevant given the large amount of available (and informative) measurements.
Now I am well aware that one way (probably the preferred one) to solve this problem is to improve the time series model and try to fix its imperfections. This is proving to be really hard, however, for a number of reasons.
Another (partial) remedy might be to somehow "fix" the influence of the prior such that it does not become irrelevant. This could be done, e.g., by choosing the prior's covariance as a function of the sample size or simply assigning the prior and the likelihood fixed weights when determining final parameter estimates. That got me wondering: is this "a thing"? Is there a name for doing something like this, i.e., a "fixed-influence prior"? Surely much more knowledgeable people than me have thought about this problem.
Comment: I agree with Dave that it is a feature. When your MAP nevertheless produces "implausible" solutions, I would advocate considering the likelihood rather than the prior as the culprit. Think local maxima etc. If you still want to tweak the prior, the fictitious sample interpretation of conjugate priors might be a starting point, see e.g. https://stats.stackexchange.com/questions/155059/justification-for-conjugate-prior/155116#155116
Comment: A prior which sets the probabilities or densities of impossible parameter values to zero will lead to a posterior distribution with those values remaining zero.  If those parameter values are merely improbable and the evidence points towards them then you start to move into the realms of Cromwell or Sherlock Holmes.
Comment: Note also that MAP inference is only debatably Bayesian.
Comment: But I think this is a great question; for example sklearn Lasso function automatically multiplies the provided regularization coefficient by the sample size, somewhat like what you describe.
Comment: Wouldn't this amount to taking the outputs of the model and basically just pushing them into the region of measurements that are considered plausible? If I know that human body temperature is always between 13 °C and 47 °C, and I have a model that says that the patient's temperature is almost certainly approximately 200 °C, then applying a really strong prior that forces the estimate down to 47 °C isn't necessarily going to give me reasonable results.
Comment: A prior that gives a non-negligible probability fo impossible values is just wrong and needs to be replaced.
Comment: A couple thoughts, since I don't think your question really has an answer because it's not defined well enough: 1) heavy tails and skews are a classic case of when more data can hurt a bad prior (e.g. don't use mean, gaussian distribution, use median, cauchy distribution) 2) you can use variational inference or MCMC to better estimate your distribution
Comment: Thought-experiment:  You're measuring a temperature that you think is probably about 50-degC.  You're using a thermometer that you suspect to have some bias plus errors in its readings.  How do you update your estimate of the temperature after each reading?  (Observe that, even after infinitely many readings, you probably wouldn't completely trust the thermometer due to bias.)
Comment: Sounds like you're basically using a meta-model that combines two different models together: one based on your initial-guesses and one informed by observations.  And it sounds like you don't want your meta-model to completely ignore the initial-guesses sub-model.
Comment: Very interesting question and answers.
Answer: I dispute your main premise.
A prior distribution is your guess (hopefully a good guess, but still a guess).
Then you observe data and see what really happens.
When you have enough observations that contradict your original guess, it is reasonable to change your mind.
What you're observing strikes me as a feature, not a bug, of Bayesian inference.
Comment: I do not mean to be stubborn, but I would take the same stance in this case as in my comment above - if the model is well-specified, then bias should be smallish in large samples (which is where the prior is overruled). If bias is still large in large samples, this, to me, points to misspecification, think omitted variable bias, so that it may be more promising to reconsider the specification of the model rather than to tweak the prior.
Comment: (+1) I think part of the problem here is that the specified prior does not match OP's stated beliefs. If the beliefs are so strong that one is prepared to discount the posterior after an analysis involving tens of thousands of data points, then it implies that OP's actual prior beliefs are MUCH stronger than specified in the model prior.
Comment: @DikranMarsupial That is precisely correct. In particular, it is proving very challenging to find a sufficiently good noise model that captures all relevant ways in which the regression model is misspecified, leading to biased parameter estimates.
Comment: In principle, I agree - the problem only arises in the context of significant model mismatch, I believe? In that case, while not completely useless, an ML estimate may be significantly biased (as it is in our case), and I would like my prior knowledge to not be completely overruled by that bias.
Comment: If you think maximum likelihood/MAP/modes of posterior distributions are risky, then apply a suitable loss function - you may end up with the mean of the posterior distribution as a point value (though that has its own issues, as it may be impossible)
Comment: The usual complaint about Bayesian models is that the prior may be wrong, but in this case it sounds like the problem may lie with the likelihood (and it is overstating the amount of information that are in the data)?
Comment: @ChristophHanck Maybe we're having a clash of terminology here? What I mean by "significant model mismatch" is precisely that the model is _not_ well-specified. As I alluded to in my question, I am aware that the better solution would be to fix the misspecification, but that is proving really hard (we have been trying to do that for a long time already).
Comment: So then what's the problem with the data overwhelming your initial assumptions?
Comment: @Eike, yes, that is possible - while, as many have expressed by now, your idea may not be the cleanest one theoretically it may, in your practical situation given the complications, have some merit as a kind of "second best" solution.
Answer: The answer to this question centers on its false premise. If I can sum up your question, you are saying the posterior is really far from your prior, but rather than acknowledging that either your prior is wrong or that your likelihood is misspecified, you instead want to know how you can just use a stronger prior to enforce that the posterior is not "too far" from prior... at which point why even use data? Just start with your prior, flip a coin and roll some dice, move your prior by that amount in that direction, and then call it your posterior. From your question it sounds like if you had 2x or 10x the data you would just be asking how to make your prior 2x or 10x stronger to cancel out the data and get the posterior you want. Therefore please fix your model (or acknowledge that currently it is not possible to model this data well enough), but please do not just change your prior to get a predetermined outcome.
Answer: I do agree with the previous answers, but if you really want to "fix" the influence of the prior, here are some ideas.

If your prior is based on historical data, you can use a power prior [1] to control the relative influence of your prior on the posterior obtained with new data.

Alternatively, you can also consider weighing the likelihood (power scaling) so that the relative influence of your prior is increased. However, if, for example, you have a Gaussian model, this would be equivalent to increasing the standard deviation of the Gaussian. So in the end, maybe you do need to change your model.

You may also be interesting in reading [2] which uses power scaling as a way to diagnose prior sensitivity.
[1] Ibrahim, J. G., Chen, M. H., Gwon, Y., & Chen, F. (2015). The power prior: Theory and applications. Statistics in Medicine, 34(28), 3724–3749. https://doi.org/10.1002/sim.6728
[2] Kallioinen, N., Paananen, T., Bürkner, P.-C., & Vehtari, A. (2021). Detecting and diagnosing prior and likelihood sensitivity with power-scaling. https://arxiv.org/abs/2107.14054v1
Answer: Have you considered that your expectation is simply wrong, perhaps because of publication bias?
Alternatively, if you are so confident in your beliefs that you're willing to discount the posterior after an analysis of tens of thousands of data points, it seems to me that your specified prior does not truly reflect the strength of your belief. You should probably specify a much stronger prior - if it's strong enough, the posterior wouldn't be dominated by the data.


Cropping Image is not cropping correctly

Question: I have followed a YouTube Tutorial on how to create a cropping image application.
Goal:
My Goal is simply load a screenshot image into PictureBox1.
Then mark an area with a Red Rectangle to crop and display into PictureBox2.
Here is the code:
public partial class Form18 : Form
{
    Rectangle Rect;

    Point LocationXY;
    Point LocationX1Y1;

    bool IsMouseDown = false;

    public Form18()
    {
        InitializeComponent();
    }

    private void Form18_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        //Clipboard image
        pictureBox1.Image = Clipboard.GetImage();
    }

    private void picturebox1_MouseDown(object sender, MouseEventArgs e)
    {
        IsMouseDown = true;
        LocationXY = e.Location;
    }

    private void picturebox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (IsMouseDown == true)
        {
            LocationX1Y1 = e.Location;

            Refresh();
        }
    }

    private void picturebox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (IsMouseDown == true)
        {
            LocationX1Y1 = e.Location;

            IsMouseDown = false;

            if (Rect != null)
            {
                Bitmap bit = new Bitmap(pictureBox1.Image, pictureBox1.Width, pictureBox1.Height);

                Bitmap cropImg = new Bitmap(Rect.Width, Rect.Height);

                Graphics g = Graphics.FromImage(cropImg);
                g.DrawImage(bit, 0, 0, Rect, GraphicsUnit.Pixel);
                pictureBox2.Image = cropImg;
            }
        }
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        if (Rect != null)
        {
            e.Graphics.DrawRectangle(Pens.Red, GetRect());
        }
    }
    private Rectangle GetRect()
    {
        Rect = new Rectangle();

        Rect.X = Math.Min(LocationXY.X, LocationX1Y1.X);

        Rect.Y = Math.Min(LocationXY.Y, LocationX1Y1.Y);

        Rect.Width = Math.Abs(LocationXY.X - LocationX1Y1.X);

        Rect.Height = Math.Abs(LocationXY.Y - LocationX1Y1.Y);

        return Rect;
    }

}

Output:
And here is the output output:
On the left hand side - you can see the screenshot input and on the right hand side - you can see the cropped image.
I do not understand - the rectangle marked in Red does not crop the image correctly? - it shows different area of the screenshot image.
Where is the going wrong?
Comment: I have tried the code and it is working fine. Did you miss any code in the post?
Comment: No, definitely did not miss anything. That's strange - Could it be because of dual screen monitor?
Comment: I have tried with extended monitor and its working. What is the sizemode for the picturebox?
Comment: @AjithNair all normal - what is yours?
Comment: Try with StretchImage. I have included in the answer below.
Comment: @AjithNair the quality is horrible - but I see what is going on
Answer: Instead of flooding the memory with disposable Graphics and Bitmap objects in the MouseUp event of the PictureBox1, handle the Paint event of PictureBox2 and use the supported Graphics object to draw, and just use the e.Graphics.DrawImage overload to pass the source and destination rectangles.
//...
private Point LocationXY;
private Point LocationX1Y1;

private void button1_Click(object sender, EventArgs e)
{
    if (Clipboard.ContainsImage())
    {
        pictureBox1.Image?.Dispose();
        pictureBox1.Image = Clipboard.GetImage();
    }
}

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Left)
        LocationXY = e.Location;
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        LocationX1Y1 = e.Location;
        pictureBox1.Invalidate();
    }
}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Left)
    {
        LocationX1Y1 = e.Location;

        pictureBox1.Invalidate();
        pictureBox2.Invalidate();
    }
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if (MouseButtons == MouseButtons.Left)
        e.Graphics.DrawRectangle(Pens.Red, GetRect());
}

private void pictureBox2_Paint(object sender, PaintEventArgs e)
{
    var src = GetRect();

    if (src == Rectangle.Empty) return;

    var des = new Rectangle(0, 0, src.Width, src.Height);

    e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
    e.Graphics.CompositingQuality = CompositingQuality.HighQuality;

    e.Graphics.DrawImage(pictureBox1.Image,
        des, src, GraphicsUnit.Pixel);
}

private Rectangle GetRect()
{
    return new Rectangle(
        Math.Min(LocationXY.X, LocationX1Y1.X),
        Math.Min(LocationXY.Y, LocationX1Y1.Y),
        Math.Abs(LocationXY.X - LocationX1Y1.X),
        Math.Abs(LocationXY.Y - LocationX1Y1.Y)
        );
}
//...

Use the following to get the cropped image:
//...
private Bitmap GetCroppedImage()
{
    var src = GetRect();

    if (src == Rectangle.Empty) return null;

    var des = new Rectangle(0, 0, src.Width, src.Height);
    var b = new Bitmap(src.Width, src.Height);

    using (var g = Graphics.FromImage(b))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.CompositingQuality = CompositingQuality.HighQuality;

        g.DrawImage(pictureBox1.Image, des, src, GraphicsUnit.Pixel);
    }
    return b;
}
//...

Then you can save it like:
private void Save()
{
    using (var d = new SaveFileDialog())
    {
        d.Filter = "PNG|*.png|JPEG|*.jpeg;*.jpg|BMP|*.bmp";

        if (d.ShowDialog() != DialogResult.OK) return;

        using (var b = GetCroppedImage())
        {
            if (b == null) return;

            ImageFormat f;

            switch (d.FilterIndex)
            {
                case 2:
                    f = ImageFormat.Jpeg;
                    break;
                case 3:
                    f = ImageFormat.Bmp;
                    break;
                default:
                    f = ImageFormat.Png;
                    break;
            }

            b.Save(d.FileName, f);
        }
    }
}

Comment: @LV98 You got me. I'll add a method for that
Comment: @LV98 Of course buddy. Once it posted and accepted, it became your code. You own it now. :)
Comment: What variable would I then use to save it as .JPG?
Comment: the image also stretches sometimes - how can this be avoided?
Comment: I'll take a look now
Comment: Hey man, do you know how I can resize the new image in `pictureBox2` with current code by `* 0.8`? I am not sure where to look.
Comment: @LV98 Hey buddy! Welcome back. You need to ask a new question in this regard. Better to get many answers instead of one. Right? :)
Comment: Thanks man! - You provided me with a great answer and your attitude towards is great, thought I'd ask you again aha! Can I use your code to put in the new question?
Comment: I have just posted the question ;)
Answer: Setting the SizeMode to Normal may not crop the image with the following code
Bitmap bit = new Bitmap(pictureBox1.Image, pictureBox1.Width, pictureBox1.Height);
Bitmap cropImg = new Bitmap(Rect.Width, Rect.Height);

The cropping will be relative to the Picturebox width and height.
Change the new Bitmap line to the following
Bitmap bit = new Bitmap(pictureBox1.Image, pictureBox1.Image.Width, pictureBox1.Image.Height);
Bitmap cropImg = new Bitmap(Rect.Width, Rect.Height);

OR Set the SizeMode of the picturebox to StretchImage
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;


Maximizing combined log likelihood from different dataset using r

Question: I have observed data $y$. And I have a function that gives me estimated $\hat{y} = f(x,\hat{P})$ where P is the parameter I want to estimate. I was able to optim() command in R to get maximized log-likelihood estimate $\hat{P}$ using the residuals, assuming a normal distribution.
My question is: If I have multiple dataset and all of them should have the same $P$ but x is on a different scale for each dataset. Now I want to maximize the overall log-likelihood to find the overall $\hat{P}$ and its standard error. Can I just simply compute all the residuals from each data and assume they all have the same distribution so that I can use optim() to maximize the log-likelihood of that?
Answer: If they have all the same $P$, and the scale of the error term is the same for each, and they're independent across data sets, then you could just combine (stack) them all into a single set of (x,y) data.
(Which will then mean, yes, if you're using an optimizer (like optim in R) on residuals you should be able to combine the residuals into a single big set of residuals.)
(If you're less than certain they'll all be the same, other things can be done to address whether they might be different)


Configurar appender do Log4j para exibir no console log a partir de Error e salvar em arquivo logs a partir de Info

Question: Boa noite pessoal.
Preciso exibir no console apenas logs a partir de Error e gravar em arquivo logs a partir de Info.
Já tentei utilizar a propriedade additivity para false, mas ao utilizá-la o o appender para de funcionar e também tentei usar respostas do Stackoverflow, mas não funcionou.
Dependência utilizada:
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

log4j.properties:
log4j.rootLogger=ERROR, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.category.debugLogger=INFO, debugLog
log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=debug.log
log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

HelloWorld.java:
package com.vaannila.helloworld;

import org.apache.log4j.Logger;

public class HelloWorld {

private static final Logger logger = Logger.getLogger(HelloWorld.class);

    public static void main(String[] args) {
        logger.debug("Sample debug message");
        logger.info("Sample info message");
        logger.warn("Sample warn message");
        logger.error("Sample error message");
        logger.fatal("Sample fatal message");
    }
}

A única forma que consegui foi definindo o rootLogger como Info e um appender com um log acima, mas o que necessito é o contrário.
Há uma forma de fazer isso?
Answer: O problema está na configuração do log4j log4j.properties
Para configurá-lo corretamente recomendo definir em rootLogger sempre o level mais baixo (DEBUG) para todos os appenders que você vai utilizar, ai quando você for configurar cada appender utilizar o Threshold para especificar o nível que o appender irá aderir.
Acho que a configuração a seguir vai resolver seu problema:
#Cria os dois appender para o nível mais baixo de log
log4j.rootLogger=DEBUG, console, file

#Configura o console appender
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=ERROR
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

#Configura o fileAppender
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.Threshold=INFO
log4j.appender.file.File=debug.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n


Passing page arguments to custom block inside panel

Question: I have created a page(Page Manager) in drupal 8 with a path say /dashboard/{nodeid}. Inside that I have created a Panel and inside panel I have added a Custom Block ( which I created programmatically by extending BlockBase).
Now my problem is I want to use the {nodeid} inside my buildForm function.
Please suggest me.
My code is as follows.
ABCBlock.php
class ABCBlock extends BlockBase
{

    public function build() {

        return \Drupal::formBuilder()->getForm('Drupal\examples\Form\ABCForm');

    }

}

ABCForm.php
class ABCForm extends FormBase
{

    public function getFormId() {
      return 'example_ABCForm';
    }

    public function buildForm(array $form, FormStateInterface $form_state)    {

      drupal_set_message('Hello World.'); // displaying fine.
      $tmp = arg(0);//or arg(1) which i am assuming as url parameter value. But it FAILS.

      //load node object using $tmp

    }

}

Answer: While a very different question, the answer is the same as mine in https://drupal.stackexchange.com/a/188629/31.
In short, define a context on your block, make sure that the parameter in page manager is defined as type node and the rest should just work.
Comment: What if I just need to pass a string?


MVC3 Intranet Application / IIS Express Not Reading Site.css

Question: I first created an MVC3 Intranet web application in Visual Studio 2010 Professional.
It worked just fine.
I then right-clicked on the application and chose "Use IIS Express..."
I also edited the application properties and disabled Anonymous Authentication but enabled Windows Authentication.
Nothing more. This is a bare-bones, default skeleton of an application that I want to start from.
Now when I run, I first get a pop-up window to login with my username and password. This is just as I expect. However, when I log in, the "Home" and "About" pages are not formatted correctly. It looks like IIS Express isn't reading my Site.css file.
How do I fix this?
Thanks,
- Paul
Comment: is the login prompt looks like part of windows auth (dialog box) or part of the web app?  it sounds like you need to work out permissions that the iis express runs under and account's ability to the static content.  if you switch back to cassini, does it work ok?
Answer: The default links for the style sheets typically use the ../../ directory navigation. When you're on a real webserver, those links typically fail 'cause now you're in a different folder setup. An easy way to correct them is to use:
<code><link href="<%: Url.Content("~/Content/style.css") %>"
      rel="stylesheet" type="text/css" />
</code>
The url.content part will rebase the links to the current directory and will link up it's content correctly.
Hope this helps some, and good luck on your project.
Comment: Chris:Thanks. This was helpful


How do I do this limit?

Question: I have the following equation
$$ S = 3Nk\left[ ln \left( \frac{e^{\Theta/T}}{e^{\Theta/T}-1} \right) + \frac{\Theta/T}{e^{\Theta/T}-1} \right]$$
And I need to evaulate it in the limit as $T \rightarrow 0$.
I have used the approximation $e^{\Theta/T} \approx 1 + \frac{\Theta}{T}$ (Taylor Expansion to first order).
Using this and rearranging I get that $S \rightarrow 3Nk$ but this is incorrect.
The correct answer is:
$$S \rightarrow 3Nk\frac{\Theta}{T}e^{-\Theta/T} \rightarrow 0$$
Can you explain to me why? I must be missing something here.
EDIT: As one of you pointed out, my professor clearly meant:
$$S \sim 3Nk\frac{\Theta}{T}e^{-\Theta/T} \rightarrow 0$$
Comment: You are using the expansion of the exponential at 0 while you should be interested in the limit at +oo since Theta/T goes to +oo when T goes to 0.
Comment: Please show your work.
Comment: Furthermore, in the "correct answer" you cite, the intermediate step is absurd since it depends on T and a limit when T goes to 0 cannot depend on T.
Comment: @Did **INDEED!** This comes from my lecturer's notes. It made me wonder too; it is absurd.
Comment: Is the first $\to$ actually a $\sim$ sign?
Comment: Is $\Theta > 0$? what about $T$?
Comment: @Did Perhaps, although I can't seem to see how the intermidiate step is obtained still.
Comment: If $\to$ is $\sim$, the assertion holds.
Answer: Hints:

Let $x=\Theta/T$ with $\Theta\gt0$. When $T\to0^+$, $x\to+\infty$.
When $x\to+\infty$, $\mathrm e^x/(\mathrm e^x-1)\to1$ hence $\log(\mathrm e^x/(\mathrm e^x-1))\to0$.
When $x\to+\infty$, $x/(\mathrm e^x-1)\to0$.
Ergo?

How do I do this limit?


Oracle Synonym Error

Question: I am knew to programming against an Oracle DB and I am getting this error:
ORA-06550: line 2, column 9: PL/SQL: ORA-01775: looping chain of synonyms

Is this something wrong in my code or in my DB? The code is the same for pretty much the whole data access layer and I am only getting this error when I try to insert into one particular table.
BEGIN
UPDATE DEAL_NOTE
SET NOTE_TXT=:prmNOTE_TXT
WHERE DEAL_ID=:prmDEAL_ID;

IF SQL%NOTFOUND THEN
INSERT INTO DEAL_NOTE (NOTE_TXT, DEAL_ID) values (:prmNOTE_TXT, :prmDEAL_ID);
END IF;

END;

Comment: This is most likely an error in your SQL. Perhaps you could edit your post to include your SQL statement.
Answer: You have a problem in your database.
The ORA-01775 error indicates that you have one synonym A that references another synonym B.  Synonym B, in turn, references synonym A.  Something like
SQL> create synonym foo2 for foo1;

Synonym created.

SQL> create synonym foo1 for foo2;

Synonym created.

SQL> select * from foo2;
select * from foo2
              *
ERROR at line 1:
ORA-01775: looping chain of synonyms

The only way to correct this is to fix the synonyms in the database so that you don't have these sorts of circular dependencies.  You can run a query to identify these synonym loops (assuming you just have a one-level loop where A points to B and B points to A rather than more involved cycles) with a query like this
SQL> ed
Wrote file afiedt.buf

  1  select a.synonym_name, b.synonym_name
  2    from all_synonyms a,
  3         all_synonyms b
  4   where a.owner = b.table_owner
  5     and a.synonym_name = b.table_name
  6     and b.owner = a.table_owner
  7*    and b.synonym_name = a.table_name
SQL> /

SYNONYM_NAME                   SYNONYM_NAME
------------------------------ ------------------------------
FOO2                           FOO1
FOO1                           FOO2

Comment: When I run that query I do not get any results, does this mean that I have an even larger problem?
Comment: @esastincy - It likely means that you have more than a one-level cycle-- synonym A points to synonym B, B points to C, and C points to A.  It's probably easier just to manually walk through the dependency tree-- see what the synonym you're using references in `ALL_SYNONYMS`, see what that synonym references, etc. until you find the cycle.
Comment: You can also get this error if you create a synonym that references itself. This easily happens when you create a PUBLIC synonym for a particular schema's table/view, then drop/rename the table/view.
Comment: @DCookie - How do you get an ORA-01775 by dropping a table that a synonym references?  I can only get an ORA-00942: table or view does not exist error in that case.
Comment: @Justin: create a table me.x. create a PUBLIC SYNONYM x FOR me.x. Drop the TABLE me.x. SELECT * FROM x; results the error. You really don't need the CREATE/DROP the table steps, either, it just illustrates how I've usually seen it happen. Just create a PUBLIC SYNONYM x for me.x. SELECT * FROM x. Same error.
Comment: I get the ORA-00942 error in that case, not ORA-01775.
create public synonym enp2_syn for scott.emp2;
drop table emp2;
select * from emp2_syn;
ERROR at line 1:
ORA-00942: table or view does not exist
Comment: @JustinCave let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/1520/discussion-between-dcookie-and-justin-cave)
Answer: This is probably a code problem - probably something to do with what you have on line2 of your script.
Care to post it?
From this post How to debug ORA-01775: looping chain of synonyms?
http://ora-01775.ora-code.com/ suggests:
ORA-01775: looping chain of synonyms
Cause: Through a series of CREATE synonym statements, a synonym was defined that referred to itself. For example, the following definitions are circular:
CREATE SYNONYM s1 for s2 CREATE SYNONYM s2 for s3 CREATE SYNONYM s3 for s1

Action: Change one synonym definition so that it applies to a base table or view and retry the operation.
Comment: It's unlikely that the problem is related to the script.  Line 2 column 9 is undoubtedly where the reference to the synonym occurs.  The problem is the underlying definition of the synonym.
Answer: This is a problem in the DB -- probably the table you are touching is a synonym that indirectly references itself.

Oracle Synonym Error


Why is the partial derivative of two vectors equal to the vector not taking the derivative

Question: I am not sure how to prove this partial derivative. It seems to me that they are both vectors of integers. So when taking a derivative of the values we get 0 but then the total would be zero overall. Instead the value at one position seems to be 1 and it removes the transpose form the non derived value. I am not quite grasping this can anyone provide an explanation?
https://i.stack.imgur.com/fUTOt.jpg
\begin{equation}
\frac{\partial}{\partial Vc} = Uo^T Vc
\end{equation}
Thank you
Comment: Got it, sorry about that.
Answer: $u_0$ and $v_c$ are vectors of the same dimension. The expression $\frac{\partial}{\partial v_c}(u_0^\top v_c)$ is not really a partial derivative, but rather the gradient of the function $f(v_c) = u_0^\top v_c = \sum_i (u_0)_i (v_c)_i$. In other words, $\frac{\partial}{\partial v_c}(u_0^\top v_c)$ is a vector of the partial derivatives $\frac{\partial}{\partial (v_c)_i} (u_0^\top v_c)$ for each $i$. Noting that $\frac{\partial}{\partial (v_c)_i} (u_0^\top v_c) = (u_0)_i$ shows that the gradient is indeed the vector $u_0$.
Comment: Hello, thank you for your help! I fail to see how $\frac{\partial}{\partial (v_c)_i} (u_0^\top v_c) = (u_0)_i$ Why is the answer not transposed and how does $(V_c)$ go away leaving one element of $(u_0)$?
Comment: @JacobB Write $u_0^\top v_c$ as $\sum_i (u_0)_i (v_c)_i$ and take the partial derivative with respect to $(v_c)_i$. This is a simple calculus problem that does not involve vectors.
Comment: That part makes sense to a point, but to me it looks like it would always be 0? The values are constants in my mind.


Limit intranet to certain computers

Question: I've created a intranet website which I would like to limit to only certain computers spread throughout the city, my first thought was creating a vpn server on the web server and authorize the client computers with certificate and then limit the site only to lan. I used SoftEther VPN to setup the server, but a problem I immediately encountered was the slow bandwidth. Now to my actual question is it possible to enable the clients to browse the internet through their own connection and at the same time be able to access the website on the vpn?
Edit: I'm also open for other solutions that may be less introsive.
Comment: why the down vote?
Answer: Sure, enable split tunneling on the VPN.
Comment: on the server side or client side?
Comment: Well, split tunneling requires configuration on both.
Comment: would you mind elobrating, how would I know if the client is using the regular connection for other sites, since when I visit sites it gives me the ip of the vpn still
Comment: [My IP](https://duckduckgo.com/?q=my+ip).
Answer: Gather public IPv6 subnets each client is in, and allow them over the Internet. Encrypt with https and secure the web server as it is a public network.
This is not typical. It is more common to have a private network for an intranet, and a fully public network for public facing resources.

Limit intranet to certain computers


Guitars for small hands?

Question: I just started playing the guitar, I've had one for a while which is the 'Squier by Fender Stratocaster Bullet Guitar, a beginners guitar. When I started to try out the chords I realised that I have difficulty spreading my fingers through three frets, and I mean a LOT of difficulty. I play the piano and I have to stretch my hand out fully to reach an octave, I sometimes have to alternate a piano chord because I just can't reach it.
Are there any guitars with a thin neck along with smaller frets? My fingers are also quite thin. And an Electric guitar if possible.
Answer: Don't be discouraged by small hands.  I know many folks with extremely small hands who have become very accomplished guitarist.  In some cases you may need to adapt in the same way as on piano and find alternative voicings for some chords.
A smaller scale guitar will also help.  The biggest advantage is that the shorter the scale length, the closer the frets will be together.  Scale length is generally specified in inches.  Look for shorter.  A 3/4 scale guitar, will, as the name implies, be about three fourths as long as a full size guitar.  But even full size guitars come in varying scale lengths between different manufacturers.
Here is a company that specializes in smaller guitars.  Small Guitars . com
To make your full scale guitar a short scale guitar until you can buy a short scale guitar, try putting a capo on the first or second fret and then tune the guitar to standard tuning and leave the capo on.  This will shorten the scale of any guitar.  The best capo for this would be something similar to a Paige Capo (see picture below).

By the way, your fingers might be short, but you mentioned that your fingers are also thin.  For guitar, thin fingers are an advantage.  I have short and fat fingers and with fat fingers it's difficult to avoid touching the string next to the one I am fretting and inadvertently muting it.  Thin fingers allow for more precise fretting without accidentally touching nearby strings.
Good luck!
Comment: Thank you for the information! This was very useful, especially the website that you mentioned. I have also searched up short scaled guitars as you suggested and so far I'm happy with what I have found. I hope to be able to progress into a decent guitarist! Once again, thank you.
Comment: @Elixia I'm glad you found the information helpful.  Good luck on your journey.  The guitar is an instrument that will provide great enjoyment for the rest of your life - at any level of proficiency.
Answer: (Note although asking for a recommendation, I think this is a valid question here if we limit it to the available sizes of instruments.)
There are plenty of children's sized guitars which may be worth trying.  They have a shorter scale length. (They also have narrower necks.)
For "professional" or non-children's sized instruments, Rickenbacker used to do the 325 model (John Lennon used one!)
(For specific brands of children's guitars, Fender do the Squier Mini.  Ibanez do the Mikro.  But shop around for a "3/4 size guitar" or "Short scale guitar" for any more choices.)
Answer: In addition to the answers above, I would recommend trying Ibanez or Jackson guitars, then have thinner neck compared to Fender and you might find it easier to play.
I also have short fingers but frankly, I believe it is not an issue. I only realize I have short fingers when I watch Steve Vai playing.

Guitars for small hands?


how to implement pause and resume method in countdowntimer

Question: Hi i am working countdowntimer concept. Here when i click start button the countdown will start. as well as stop also its working fine but i need to implement pause and resume method in my countdown timer. the countdown will go to  pause state when i click pause button. the countdown will start from pause value  when i click start button. for ex: my countdown is 0 to 30, suppose if i click pause button the value will be pause ex: 25 or 15 something else. the countdown will start from 25 when i click start button. i hope you all understand my problem i tried but i am not getting any solution  could you please help me
<code>  public class MainActivity extends ActionBarActivity implements OnClickListener {

     private CountDownTimer countDownTimer;
     private boolean timerHasStarted = false;
     private Button startB;
     public TextView text;
     private final long startTime = 30 * 1000;
     private final long interval = 1 * 1000;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    startB = (Button) this.findViewById(R.id.button);
    startB.setOnClickListener((OnClickListener) this);
    text = (TextView) this.findViewById(R.id.timer);
    countDownTimer = new MyCountDownTimer(startTime, interval);
    text.setText(text.getText() + String.valueOf(startTime / 1000));
   }

    public void onClick(View v) {
     if (!timerHasStarted) {
      countDownTimer.start();
      timerHasStarted = true;
      startB.setText("STOP");
      } else {
        countDownTimer.cancel();
        timerHasStarted = false;
        startB.setText("RESTART");
    }
    }
 public class MyCountDownTimer extends CountDownTimer {
   public MyCountDownTimer(long startTime, long interval) {
                   super(startTime, interval);
  }

   @Override
    public void onFinish() {
     //text.setText("Time's up!");
      countDownTimer.start();
   }

     @Override
      public void onTick(long millisUntilFinished) {
      text.setText("" + millisUntilFinished / 1000);
         }
       }
    }

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rl" >

    <TextView
    android:id="@+id/timer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:paddingRight="10dip"
    android:textSize="50dp" />

    <Button
    android:id="@+id/button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:text="Start" />

</RelativeLayout>
</code>
Comment: Could you add your layout file ?
Comment: @ Gaëtan Maisse i updated my xml file check it
Answer: The only way I see is to cancel timer when you call pause and create a new one when you want to resume it, something like this :
<code>public class MainActivity extends ActionBarActivity implements OnClickListener {

 private MyCountDownTimer countDownTimer;
 private boolean timerHasStarted = false;
 private Button startB;
 public TextView text;
 private final long startTime = 30 * 1000;
 private final long interval = 1 * 1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    startB = (Button) this.findViewById(R.id.button);
    startB.setOnClickListener(this);

    text = (TextView) this.findViewById(R.id.timer);
    countDownTimer = new MyCountDownTimer(startTime, interval,text );
    // Set starting value
    text.setText(text.getText() + String.valueOf(startTime / 1000));
}

 public void onClick(View v) {
     if (!timerHasStarted) {
      // Start or resume counter
      countDownTimer = countDownTimer.resume();
      timerHasStarted = true;
      startB.setText("PAUSE");
      } else {
       // Pause counter
        countDownTimer.pause();
        timerHasStarted = false;
        startB.setText("RESTART");
      }
}

public class MyCountDownTimer extends CountDownTimer
{

    private long mRemainingTime = 0;
    private long mInterval = 0;
    private TextView mtvxToUpdate = null

    //  Use a textview reference to update text on each tick()
    public MyCountDownTimer(long startTime, long interval,TextView txv ) {
        super(startTime, interval);
        this.mInterval = interval;
        this.mRemainingTime = startTime;
        this.mtvxToUpdate = txv;
    }

    @Override
    public void onFinish() {
        mtvxToUpdate.setText("Time's up!");
    }

    @Override
    public void onTick(long millisUntilFinished) {
            mRemainingTime = millisUntilFinished;
            mtvxToUpdate.setText("" + millisUntilFinished / 1000);
    }

    public void pause(){
        // Stop current timer
        this.cancel();
    }

    public MyCountDownTimer resume(){
        // Create a counter with last saved data (just before pause)
        MyCountDownTimer newTimer = new MyCountDownTimer(mRemainingTime,mInterval,mtvxToUpdate);
        // Start this new timer that start where old one stop
        newTimer.start();
        // Return this new timer
        return newTimer;
    }
}
}
</code>
Comment: when i click pause button the number should stop, when i click start button the number should start from pause value    could you please explain me, exactly what i have to do and where i have to use your suggested code and tell me how to implement on click method also
Comment: @ Gaëtan Maisse if i use like this countDownTimer.resume(); as well as countDownTimer.pause(); i am getting this error  "The method resume(),pause() is undefined for the type CountDownTimer"   can i use ((MyCountDownTimer) countDownTimer).pause(); like this instead of countDownTimer.pause();
Comment: yes you can, or change : private CountDownTimer countDownTimer ot  private MyCountDownTimer countDownTimer;
Comment: @ Gaëtan Maisse now i have no error but still i am not getting correct output. countDownTimer.pause();
        timerHasStarted = false;
        startB.setText("RESTART"); this is pause function right? but  why it is restarting for me, i need pause when i click pause button sorry here startB.setText("pause"); instead of startB.setText("RESTART"); tell me what can i do?
Comment: @rizwan, don't know why it's restarting, I update my answer with a solution from a new point of view
Comment: your answer is almost get solution but pause is working fine when i click pause but once i click pause button start button should come  and when i click start count will start from paused value is it possible? if it is possible kindly edit my code please
Comment: You should get RESTART button after clicking on PAUSE, are you ?
Comment: @ Gaëtan Maisse i need to get start button after clicking on PAUSE. usually one countdown is there we need to give two provision start and pause when i click start button countdown will start ok now pause button visible ok if i click pause button the countdown should go to pause state now start button need to visible if i click start button countdown continue should not restart this is the concept i hope you understand my concept


Postgresql column from subselect does not exist

Question: I need to include subselect to the select statement which is common in Mysql but not work in Postgresql.
I get an error Undefined column: 7 ERROR:  column "count_receipts" does not exist
select "organizations".*, (
    SELECT count(*) AS count_receipts FROM companies
            JOIN receipts ON receipts.company_id = companies.id
            WHERE companies.organization_id = organizations.id
            GROUP BY companies.organization_id
) as count_receipts
from "organizations"
where count_receipts >= 10
AND count_receipts <= 20

If I remove the where clause everything works and count_receipts column is included in result. But with where it does not work.
What is wrong with this sql?
Answer: Instead of using the subquery as a column use it in a join :
SELECT o.*, count_receipts
FROM organizations o
JOIN (
  SELECT c.organization_id, count(*) AS count_receipts
  FROM companies c
  JOIN receipts r ON r.company_id = c.id
  GROUP BY c.organization_id
) AS s on s.organization_id = o.id
WHERE count_receipts >= 10
AND count_receipts <= 20;


Regular conditional Bayesian experiment

Question: In "Elements of Bayesian Statistics" (1990), Florens, Mouchart and Rolin describe two basic forms of reduction of a Bayesian experiment: Marginalization and Conditioning (Ch. 1). I don't understand the conditioning reduction. More precisely, i struggle with the definition of a regular conditional experiment. I would appreciate an explanation, if possible in measure-theoretic terms. Thanks
Comment: Florens et al.'s book has the distinction of being the first book to lay Bayesian statistics on rigorous, measure-theoretic foundations. There is only one other book on the market with the same rigorous approach to this subject, Schervish's Statistical Theory, but it is much less clear, imo, than Florens et al.'s, as implausibly as it may seem. Florens et al. is surely idiosyncratic, considering the fact that it's a break-through work, but i have seen it cited in published papers, so apparently some folks have managed to figure it out and i aspire to eventually count myself among them.
Comment: @Zen: [Here](https://docs.google.com/file/d/0BzbZQLKx1ZTReUFzUURaLWV6QXc/edit?usp=sharing)'s part of a letter i wrote to Prof. Florens requesting him for an explanation of the definition of 'regular conditional experiment'. I go there in greater detail into what it is exactly that i don't understand. [Here](https://docs.google.com/file/d/0BzbZQLKx1ZTRM2o3MkxMNkl0M00/edit?usp=sharing) are the relevant pages from the book. If you need further clarification, please let me know.
Comment: Regarding your question. It's a good one. The authors don't do as good a job explaining the conditioning reduction unambiguously as they do with the marginalization reduction. However, i feel pretty comfortable with the following interpretation of $\Pi^\mathcal{T}$.
Comment: Let $\mathcal{T}$ be a sub-$\sigma$-algebra of the sample space $\left(S,\mathcal{S}\right)$. Then $\Pi^\mathcal{T}$ is a regular version of the conditional probability of $\mathcal{A}\otimes\mathcal{S}$ conditional on $\mathcal{T}$ given $\Pi$.
Comment: In other words, $\Pi^\mathcal{T}$ is a transition from $\left(S,\mathcal{T}\right)$ to $\left(A\times S,\mathcal{A}\otimes\mathcal{S}\right)$, which satisfies the following condition. For every $D\in\mathcal{A}\otimes\mathcal{S}$ and every $E\in\mathcal{T}$, $\Pi\left(D\cap E\right)=\int_E\Pi^\mathcal{T}\left(t,D\right)\space P\left(dt\right)$, with $P$ being the predictive probability, defined in p. 27 as the restriction of $\Pi$ to the sample space.
Comment: P.S. By "transition" i meant what is elsewhere called a "[Markov kernel](http://en.wikipedia.org/w/index.php?title=Markov_kernel&oldid=491600480)". "Transition" is the terminology employed in the book (p. 17).
Comment: @Zen: P.S. #2 By "$\Pi\left(D\cap E\right)$" i meant "$\Pi\left(D\cap\left(A\times E\right)\right)$".
Comment: Evan: are you sure? Isn't $\mathcal{T}$ a sub-sigma-field of $\mathcal{A}\vee\mathcal{S}$?
Comment: @Zen: Yes, i'm sure. There's also a version $\mathcal{E}^\mathcal{M}$ where $\mathcal{M}$ is an arbitrary sub-$\sigma$-algebra of $\mathcal{A}\otimes\mathcal{S}$. If you can figure out the more general case, be my guest, but i think once the simpler case is cracked, the other case will be very similar.
Answer: Let us consider a more general case with arbitrary $\sigma$-fields $\mathcal{B}\subseteq\mathcal{A}$, $\mathcal{T}\subseteq\mathcal{S}$ and $\mathcal{M}\subseteq\mathcal{A}\otimes\mathcal{S}$ and a combined conditional/marginal experiment
$$
\mathcal{E}^\mathcal{M}_{\mathcal{B}\vee\mathcal{T}}=\left(A\times S,\mathcal{A}\otimes\mathcal{S},\Pi^\mathcal{M}_{\mathcal{B}\vee\mathcal{T}}\right)
$$
(see "Combined Reductions" on pp. 53-54).
Define
$$
\begin{array}{lcl}
\Omega & := & A\times S \\
\Xi & := & \mathcal{A}\otimes\mathcal{S} \\
\Gamma & := & \mathcal{B}\vee\mathcal{T}\vee\mathcal{M} \\
\Gamma' & := & \left(\Omega,\Gamma\right) \\
\Delta_1 & := & \left(\mathcal{B}\vee\mathcal{M}\right)\otimes\left(\mathcal{T}\vee\mathcal{M}\right) \\
\Delta_1' & := & \left(\Omega\times\Omega,\Delta_1\right) \\
\Delta_2 & := & \left(\mathcal{T}\vee\mathcal{M}\right)\otimes\left(\mathcal{B}\vee\mathcal{M}\right) \\
\Delta_2' & := & \left(\Omega\times\Omega,\Delta_2\right)
\end{array}
$$
and define $X$ to be the function
$$
X:\Omega\rightarrow\left(\Omega\times\Omega\right),\hspace{10mm}X\left(\omega\right):=\left(\omega,\omega\right)
$$
Note that $X$ is a $\Gamma/\Delta_1$-measurable as well as $\Gamma/\Delta_2$-measurable.
$\mathcal{E}^\mathcal{M}_{\mathcal{B}\vee\mathcal{T}}$ is called regular iff $\Pi^\mathcal{M}_{\mathcal{B}\vee\mathcal{T}}$ is regular (the book does not make it clear whether $\Pi^\mathcal{M}_{\mathcal{B}\vee\mathcal{T}}$ should be assumed regular when $\mathcal{E}^\mathcal{M}_{\mathcal{B}\vee\mathcal{T}}$ is not regular) and there exist regular versions of $\mu^{\mathcal{T}\vee\mathcal{M}}_\mathcal{B\vee\mathcal{M}}$ and $P^{\mathcal{B}\vee\mathcal{M}}_{\mathcal{T}\vee\mathcal{M}}$.
If this is the case,
$$
\mu^\mathcal{M}_{\mathcal{B}\vee\mathcal{M}}\otimes P^{\mathcal{B}\vee\mathcal{M}}_{\mathcal{T}\vee\mathcal{M}}
$$
is a Markov kernel from $\mathcal{M}$ to $\Delta_1$ and for all $D\in\Delta_1$,
$$
\Pi^\mathcal{M}_{\mathcal{B}\vee\mathcal{T}\vee\mathcal{M}}\left(\omega, X^{-1}(D)\right)=\left(\mu^\mathcal{M}_{\mathcal{B}\vee\mathcal{M}}\otimes P^{\mathcal{B}\vee\mathcal{M}}_{\mathcal{T}\vee\mathcal{M}}\right)\left(\omega,D\right)\tag{1}
$$
for $\left[\Xi,\Pi_\mathcal{M}\right]$-almost every $\omega\in\Omega$. Write $\Pi^\mathcal{M}_{\mathcal{B}\vee\mathcal{M},\mathcal{T}\vee\mathcal{M}}\left(\omega,D\right)$ as a shorthand for $\Pi^\mathcal{M}_{\mathcal{B}\vee\mathcal{T}\vee\mathcal{M}}\left(\omega, X^{-1}(D)\right)$, $D\in\Delta_1$.
In the same vein,
$$
P^\mathcal{M}_{\mathcal{T}\vee\mathcal{M}}\otimes \mu^{\mathcal{T}\vee\mathcal{M}}_{\mathcal{B}\vee\mathcal{M}}
$$
is a Markov kernel from $\mathcal{M}$ to $\Delta_2$ and for all $D\in\Delta_2$,
$$
\Pi^\mathcal{M}_{\mathcal{B}\vee\mathcal{T}\vee\mathcal{M}}\left(\omega,X^{-1}(D)\right)=\left(P^\mathcal{M}_{\mathcal{T}\vee\mathcal{M}}\otimes\mu^{\mathcal{T}\vee\mathcal{M}}_{\mathcal{B}\vee\mathcal{M}}\right)\left(\omega,D\right)\tag{2}
$$
for $\left[\Xi,\Pi_\mathcal{M}\right]$-almost every $\omega\in\Omega$. Write $\Pi^\mathcal{M}_{\mathcal{T}\vee\mathcal{M},\mathcal{B}\vee\mathcal{M}}\left(\omega,D\right)$ as a shorthand for $\Pi^\mathcal{M}_{\mathcal{B}\vee\mathcal{T}\vee\mathcal{M}}\left(\omega, X^{-1}(D)\right)$, $D\in\Delta_2$.
Equations $(1)$ and $(2)$ together constitute the rigorous interpretation of equations $1.4.16$ in Florens et al.'s book. See here for more on that.
$X$ is an embedding of $\Gamma'$ in $\Delta'_1$ in the sense that $X$ is injective and measurable and $\Gamma=X^{-1}\left(\Delta_1\right)$.
Moreover, from Doob's Functional Representation Lemma (Lemma 1.13 in Kallenberg's Foundations of Modern Probability (2002)), also known as The Factorisation Lemma, if $\left(H,\mathcal{B}\right)$ is a Borel space, then $f:\Omega\rightarrow H$ is $\Gamma/\mathcal{B}$-measurable iff there is some $\Delta_1/\mathcal{B}$-measurable function $h$ such that $f=h\circ X$.
Additionally, if we equip $\Gamma'$ with a probability measure $\phi$ (e.g. $\phi=\Pi$ or $\phi=\Pi^\mathcal{M}_{\mathcal{B}\vee\mathcal{T}}\left(\omega,\cdot\right)$ for some fixed $\omega\in\Omega$) and equip $\Delta'_1$ with $X$'s distribution function, $\phi_X$, then $f$ and $h$ have the same distributions. Furthermore, if $\mathcal{B}$ is the standard Borel field on the extended real line, we have by the Substitution Lemma (Lemma 1.22 in Kallenberg's book)$^*$, that $f$ has an integral w.r.t. $\left(\Gamma',\phi\right)$ iff $h$ has an integral w.r.t. $\left(\Delta'_1,\phi_X\right)$ and in this case the values of the integrals are identical.
In like manner, $X$ is an embedding of $\Gamma'$ in $\Delta'_2$.

$(*)$ Actually, Theorem 1.6.12 in Ash's Probability and Measure Theory (2000) is more appropriate for the level of generality stated here.

Regular conditional Bayesian experiment


Navbar transparente Bootstrap

Question: Boa tarde,
Como eu faço pra minha pagina iniciar com a navbar transparente e quando eu der o Scroll pra baixo ela ficar como "inverse"? Eu já tentei dar um background-color: transparent !important, mas ficou estranho, quanto ao scroll, não compreendi muito bem essa função do Jquery. Poderiam me dar um exemplo, por favor?
Comment: voce vai ter que trocar o css quando o scroll rolar. posta o que voce tem de codigo para termos algo onde partir
Answer: No do exemplo temos o seguinte trecho de código Jquery no arquivo:

// Offset for Main Navigation
$('#mainNav').affix({
  offset: {
    top: 100
  }
})
.affix-top {
  background-color: transparent !important;
}

.affix {
  background-color: black;
}

h1 {
  margin-top: 100px !important;
}

header {
  position: relative;
  width: 100%;
  min-height: auto;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
  background-position: center;
  background-image: url('https://blackrockdigital.github.io/startbootstrap-creative/img/header.jpg');
  text-align: center;
  color: white;
  display: table !important;
}

.navbar-nav {
    background: #f8f8f8;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation Menu
      </button>
      Start Bootstrap

          About

          Services

          Portfolio

          Contact

Your Favorite Source of Free Bootstrap Themes

 Duis pharetra, mauris et eleifend pretium, mauris est suscipit eros, et blandit lectus velit nec turpis. Morbi ullamcorper tortor a viverra interdum. Proin bibendum mattis est et maximus. Praesent tristique arcu sed consequat molestie. Etiam id
        hendrerit felis. Ut lobortis erat neque, at dictum tortor cursus eget. Donec consequat nisl at semper iaculis. Phasellus eros lacus, porta in sagittis at, congue sed dolor.

Curabitur nec tortor sagittis, elementum ipsum et, commodo libero. Vestibulum mattis ultricies luctus. Sed sem justo, aliquam id aliquet quis, accumsan a magna. Quisque non fringilla leo, vel rutrum metus. Aliquam placerat, orci nec finibus suscipit,
        erat eros volutpat leo, eget maximus sapien enim in arcu. Curabitur aliquet tortor quam, quis bibendum leo rutrum in. Quisque vitae lobortis augue. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Phasellus
        sagittis leo et consequat bibendum. Nunc cursus lectus non sem laoreet, ut vulputate dolor malesuada.

Ultricies metus. Sed vel tincidunt quam. Duis et justo hendrerit, ultrices elit non, mollis erat. Nunc porta accumsan dolor. Ut ut enim scelerisque, pretium odio ac, blandit nunc. Duis dapibus bibendum mi mattis sollicitudin. Proin dictum commodo
        dolor ut venenatis.

Quisque sed urna accumsan, posuere ex nec, tempor lacus. Pellentesque hendrerit sodales felis, sit amet maximus elit convallis in. Aenean lorem erat, ornare vitae iaculis vitae, gravida et metus. Nulla molestie placerat turpis eget vestibulum. Pellentesque
        aliquet massa ipsum, et ultrices dolor ornare vitae. Nulla consectetur aliquam quam sed sollicitudin. Aenean porttitor mollis feugiat. Integer a magna sit amet dui hendrerit bibendum non sit amet nisl. Donec tristique nunc non lorem ultrices venenatis.
        Aliquam erat volutpat. Quisque ac dignissim dui, luctus pellentesque turpis. Duis lectus felis, vulputate non purus a, efficitur dignissim tortor. Aliquam nec nunc viverra, commodo augue sit amet, molestie nisl. Quisque consequat fermentum turpis,
        id mattis nibh aliquet sed.

Quisque sed urna accumsan, posuere ex nec, tempor lacus. Pellentesque hendrerit sodales felis, sit amet maximus elit convallis in. Aenean lorem erat, ornare vitae iaculis vitae, gravida et metus. Nulla molestie placerat turpis eget vestibulum. Pellentesque
        aliquet massa ipsum, et ultrices dolor ornare vitae. Nulla consectetur aliquam quam sed sollicitudin. Aenean porttitor mollis feugiat. Integer a magna sit amet dui hendrerit bibendum non sit amet nisl. Donec tristique nunc non lorem ultrices venenatis.
        Aliquam erat volutpat. Quisque ac dignissim dui, luctus pellentesque turpis. Duis lectus felis, vulputate non purus a, efficitur dignissim tortor. Aliquam nec nunc viverra, commodo augue sit amet, molestie nisl. Quisque consequat fermentum turpis,
        id mattis nibh aliquet sed.

Quisque sed urna accumsan, posuere ex nec, tempor lacus. Pellentesque hendrerit sodales felis, sit amet maximus elit convallis in. Aenean lorem erat, ornare vitae iaculis vitae, gravida et metus. Nulla molestie placerat turpis eget vestibulum. Pellentesque
        aliquet massa ipsum, et ultrices dolor ornare vitae. Nulla consectetur aliquam quam sed sollicitudin. Aenean porttitor mollis feugiat. Integer a magna sit amet dui hendrerit bibendum non sit amet nisl. Donec tristique nunc non lorem ultrices venenatis.
        Aliquam erat volutpat. Quisque ac dignissim dui, luctus pellentesque turpis. Duis lectus felis, vulputate non purus a, efficitur dignissim tortor. Aliquam nec nunc viverra, commodo augue sit amet, molestie nisl. Quisque consequat fermentum turpis,
        id mattis nibh aliquet sed.

Quisque sed urna accumsan, posuere ex nec, tempor lacus. Pellentesque hendrerit sodales felis, sit amet maximus elit convallis in. Aenean lorem erat, ornare vitae iaculis vitae, gravida et metus. Nulla molestie placerat turpis eget vestibulum. Pellentesque
        aliquet massa ipsum, et ultrices dolor ornare vitae. Nulla consectetur aliquam quam sed sollicitudin. Aenean porttitor mollis feugiat. Integer a magna sit amet dui hendrerit bibendum non sit amet nisl. Donec tristique nunc non lorem ultrices venenatis.
        Aliquam erat volutpat. Quisque ac dignissim dui, luctus pellentesque turpis. Duis lectus felis, vulputate non purus a, efficitur dignissim tortor. Aliquam nec nunc viverra, commodo augue sit amet, molestie nisl. Quisque consequat fermentum turpis,
        id mattis nibh aliquet sed.

Quisque sed urna accumsan, posuere ex nec, tempor lacus. Pellentesque hendrerit sodales felis, sit amet maximus elit convallis in. Aenean lorem erat, ornare vitae iaculis vitae, gravida et metus. Nulla molestie placerat turpis eget vestibulum. Pellentesque
        aliquet massa ipsum, et ultrices dolor ornare vitae. Nulla consectetur aliquam quam sed sollicitudin. Aenean porttitor mollis feugiat. Integer a magna sit amet dui hendrerit bibendum non sit amet nisl. Donec tristique nunc non lorem ultrices venenatis.
        Aliquam erat volutpat. Quisque ac dignissim dui, luctus pellentesque turpis. Duis lectus felis, vulputate non purus a, efficitur dignissim tortor. Aliquam nec nunc viverra, commodo augue sit amet, molestie nisl. Quisque consequat fermentum turpis,
        id mattis nibh aliquet sed.

Quisque sed urna accumsan, posuere ex nec, tempor lacus. Pellentesque hendrerit sodales felis, sit amet maximus elit convallis in. Aenean lorem erat, ornare vitae iaculis vitae, gravida et metus. Nulla molestie placerat turpis eget vestibulum. Pellentesque
        aliquet massa ipsum, et ultrices dolor ornare vitae. Nulla consectetur aliquam quam sed sollicitudin. Aenean porttitor mollis feugiat. Integer a magna sit amet dui hendrerit bibendum non sit amet nisl. Donec tristique nunc non lorem ultrices venenatis.
        Aliquam erat volutpat. Quisque ac dignissim dui, luctus pellentesque turpis. Duis lectus felis, vulputate non purus a, efficitur dignissim tortor. Aliquam nec nunc viverra, commodo augue sit amet, molestie nisl. Quisque consequat fermentum turpis,
        id mattis nibh aliquet sed.

Ultricies metus. Sed vel tincidunt quam. Duis et justo hendrerit, ultrices elit non, mollis erat. Nunc porta accumsan dolor. Ut ut enim scelerisque, pretium odio ac, blandit nunc. Duis dapibus bibendum mi mattis sollicitudin. Proin dictum commodo
        dolor ut venenatis.

 Duis pharetra, mauris et eleifend pretium, mauris est suscipit eros, et blandit lectus velit nec turpis. Morbi ullamcorper tortor a viverra interdum. Proin bibendum mattis est et maximus. Praesent tristique arcu sed consequat molestie. Etiam id
        hendrerit felis. Ut lobortis erat neque, at dictum tortor cursus eget. Donec consequat nisl at semper iaculis. Phasellus eros lacus, porta in sagittis at, congue sed dolor.

 Duis pharetra, mauris et eleifend pretium, mauris est suscipit eros, et blandit lectus velit nec turpis. Morbi ullamcorper tortor a viverra interdum. Proin bibendum mattis est et maximus. Praesent tristique arcu sed consequat molestie. Etiam id
        hendrerit felis. Ut lobortis erat neque, at dictum tortor cursus eget. Donec consequat nisl at semper iaculis. Phasellus eros lacus, porta in sagittis at, congue sed dolor.

      Find Out More

Este trecho de código Jquery abaixo faz com que a div que contém o id="mainNav" seja incremetada com a classe="affix-top" ou classe="affix", dependendo da altura.
// Offset for Main Navigation
$('#mainNav').affix({
offset: {
top: 100
}
})

Sendo assim, voce pode escrever no seu css com cores diferente para cada classe incrementada no momento.
exemplo:
.affix-top {
  background-color: transparent;
}
.affix{
  background-color: black;
}

Comment: as pessoas que votaram contra precisar revogar o voto contra delas ou alguem que foi ajudado pelo seu comentário manda up - Eu por exemplo acabei de mandar um up...
Comment: Eu editei e melhorei minha resposta, mesmo assim continuo com -2. Porque?

Navbar transparente Bootstrap


What is a good fingering for this left-hand, F-sharp minor arpeggio?

Question:
The notes are played with the left hand in the bass clef. My current fingering is: (5,1)-5-2-1-2-1
The octave jump feels strange not matter what fingers I use. I'd appreciate the help.
If the picture doesn't show, these are the notes; they are all ascending:
F3#-F4# (octave), F4#, C3#, F5#, A, C4#
Edit: The key is A major, so there were typos above (fixed). F and C have sharps. The piece is around 50 beats per minute for a quarter note, and it is in 4/4 time.
Comment: I think (51)-1-4-2-1-2 works better because it's hard to stretch the 4 and the 3rd fingers. I think jumping with the 4th fingers feels more comfortable too. Thanks for your input. The tempo for the quarter note is around 90-100 beats per minute.
Comment: I'm confused about the notation.  You say the first two notes are F, then there are F# and C#?  How can this be without accidentals (whether we assume a 2 sharps key signature or not?
Comment: Asking the inernet for fingerings is a bad idea, since everyone's hands, training and habits are very different. I wouldn't even think about playing this any other way than 51-1-5-3-2-1, but that doesn't mean that *you* should play it this way *at all*.
Comment: Hard for me to test viability without a keyboard in front of me, and I don't know the tempo or style... but does (51)-1-4-3-2-1 work?
Comment: There's going to be some kind of jump after the octave — that's unavoidable. I'm more concerned about the 1-2-1 at the end for a ♯-♮-♯ sequence.
Comment: This is a mistake.... I forgot to include the key signature. F, C, and G should have sharps. Thanks for pointing that out.
Answer: There is never a "correct" answer for fingering, but I suggest:
(51)-5-3-2-1-2 (but the last finger depends rather on what comes next)
At the beginning: it is usually better to avoid repeating a finger on a key, and the thinking behind the perhaps surprising initial jump is that your hand "knows" where the second F# is, because your thumb is sitting on it. So it is very easy for 5 to land on it -- and particularly because it is a black note. Then you are ready to move up smoothly, instead of having to start with a hand over movement.
Answer: We don't know the tempo, but since the 16-notes are marked as two triplets, not one sextuplet, it might be better to move your hand on the (half)-beat, i.e. something like 51-3-1 4-2-1 or 51-2-1 5-2-1.
There's nothing obviously "wrong" with your 51-5-2 1-2-1 (or 51-5-3 1-3-1), if that works for you.
A fingering like 51-1-5-3-2-1 might tend to put a false accent on the second or third note, if the notation of two triplets not one sextuplet is significant.
If all the notes are really on the black keys (either because your description in the OP has some typos, or because you don't understand what key signatures mean) then somebody with big hands might prefer 51-5-4-3-2-1, letting your hand move up as you play the arpeggio. With big hands you might prefer 41 or even 31 on the low octave, with your wrist turned to the left so your hand moves less distance than with 51. The black keys are easier to hit cleanly than the white ones!
Whatever fingering you use, don't squirm around trying to play the notes legato. That's what the sustain pedal is for!


Which hook for code after a node has been deleted from the DB?

Question: I'm running Drupal 7 and I want to re-save the user account of the node author after deleting a node of content type picture.  I want to do this because I have some code called in hook_user_presave() that counts the number of pictures a user has added and saves it in an integer field in the user.
I looked at hook_node_delete() and hook_entity_delete() as suggested in this question, but when then are invoked, the node is not yet deleted, so if I save the user at that point, the int value is one more than it should be (because the deleted file has not actually been deleted yet).
Is there a hook for responding to node deletion after it has taken place?
Related question: Hook for reacting after adding node
Answer: There isn't one. If you look at node_delete_multiple(), which node_delete is a wrapper function for, you can see that the only hook invocations (the above hooks) are triggered before the DB delete statements.
If your Drupal site only allows deleting through the node/$nid/delete form, one alternative to a post-delete hook is appending a submission handler to the node deletion confirmation form:
function MYMODULE_form_node_delete_confirm_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'MYMODULE_node_delete_confirm_submit';
}

function MYMODULE_node_delete_confirm_submit($form, &$form_state) {
  //@TODO: Post-node-delete code here
}