How can I get Sphinx autosummary to generate full API documentation for classes, as well as a *summary table* for those classes?

Question: I'm sure this is user error at one level or another but I'm going mad slowly here and would really appreciate some help.
I've gotten both sphinx-apidoc and the excellent third party sphinx-autoapi to work, but can't repeat the trick with sphinx.ext.autosummary. It's driving me mad... plus neither of these options give you the really neat package/module member summary tables that are (presumably) the main selling point of sphinx.ext.autosummary.
I have a really simple project:
|_ TEST
   |_ docs
      |_ conf.py
      |_ index.rst
   |_ myproject
      |_ __init__.py
      |_ mymodule.py

conf.py looks like this:
import os
import sys
sys.path.insert(0, os.path.abspath('../../myproject'))

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary'
]

autosummary_generate = True

index.rst looks like this:
.. autosummary::
   :toctree: _autosummary

   myproject.mymodule

mymodule.py looks like this:
"""
Module containing a class and a function.
"""

class TestClass:
    """
    A class representing a test.

    I wish I could get this to stuff to show up but I can't and I don't know why.

    Why isn't this documentation visible?!? :-(
    """
    def __init__(self):
        """
        Instantiate.
        """
        pass

    def Func_in_test_class(self):
        """
        Cool function that does stuff.

        :return: Some new stuff.
        """
        pass

def GlobalFunc():
    """
    Utility function.

    Does some good stuff.
    """
    pass

Running make html from the docs directory makes this lovely Readthedocs-style HTML:

What I want to do is click on the TestClass function in the summary table and visit a new page that shows the API documentation for this class in full. How can I achieve that?
(Or am I missing the point, and I have to combine sphinx.ext.autosummary with sphinx-apidoc to get what I need..?)
Comment: If your project really is that simple, I wonder if it wouldn't be easier to just create the needed RST markup "by hand" instead of using sphinx-apidoc. Maybe this is what you want: https://stackoverflow.com/a/14621772/407651
Answer: From Sphinx version 3.1 (June 2020), sphinx.ext.autosummary finally has recursion!
I've answered my own question here: https://stackoverflow.com/a/62613202/12014259
Comment: It seems as though python 2.7 is only supported up to Sphinx 1.8.6, which means it does not support recursion.


Questions about equivalence hypothesis testing

Question: The setup for the current question is the same as a previous question of mine, with one important difference: I have decided to go for a paired test, by always performing two consecutive experiments with the two possible inputs (zero or random), although I randomize the order (zeros first and random second, or vice-versa) for each measurement, seeking to avoid certain domain-specific biases (if anyone cares, related to the out-of-order execution capability of the underlying CPU).
After more research into the issue, I've learned about equivalence tests, and the more I read about them, the more I'm convinced they're the correct approach for my problem. Not only it answers the "correct" question, but I believe it sidesteps an issue described on that question, of having too many samples, so that a test would reject the null hypothesis by identifying a difference that is too small to be relevant to my problem at hand.
In particular I've come across the EQUIVNONINF R package and have been reading its documentation, as well as the associated monograph "Testing Statistical Hypotheses of Equivalence and Noninferiority" by Stefan Wellek.
Given the particulars of my data set (paired, non-normal, discrete [integer, actually] data with high probability of ties), I believe the srktie functions, which perform a signed rank equivalence test generalized for discrete data, are most appropriate for my problem. In particular, the srktie_m, which is said to be faster, is applicable, so that's the one I planned to go with. This leads to my first question:
Question 1: is the srktie_m really the "best" choice in my case?
I understand that I need to define, prior to running the tests, the equivalence interval in my case, and that it is something that needs to be answered by domain-specific knowledge. I have decided that any differences below one clock cycle must be attributable to measurement noise, since a CPU is a digital electronic circuit which operates in quantums of clock cycles.
I believe the equivalence interval is related to the eps1 and eps2 parameters to the srktie_m function. They are defined as left-hand and right-hand limits of the hypothetical equivalence range for $q_+/(1 − q_0) − 1/2$, where $q_+ = P[D_i + D_j > 0]$ and $q_0 = P[D_i + D_j = 0]$, where, as I understand, $D_i$ and $D_j$ are the differences in clock cycles between a "zeros" input and a "random" input for two randomly selected measurements. I am unsure how to relate this to my 1 clock cycle equivalence hypothesis (I feel it has to do with the variance of the distribution somehow), which leads me to my second question:
Question 2: how do I choose eps1 and eps2 in srktie_m so that differences of less than one clock cycle are considered equivalent?
As I'm looking to run this test by the book, I would like to perform a power analysis first, to determine the required sample size before actually running the test. Note that these are computer experiments, for which I can easily perform a million measurements, and perhaps even a billion wouldn't be out of the question, but I have no idea if a million samples is too little or enough; or if a billion samples is too much (or worse, still too little). I understand it would be "cheating" to simply rerun the tests with more samples if I got a "non-equivalent" response.
Although I can find some functions that appear suitable for power calculation for other tests in the EQUIVNONINF package, I can't seem to find one for the srktie functions. Skimming through Wellek's monograph, I also haven't found anything about this. Which leads to my third question:
Question 3: how to calculate power and sample size for the signed-rank with ties equivalence test?
Lastly, I'm trying to understand if I should apply the Bonferroni correction, given that I have (as stated in my previous question) an ensemble composed of different parameter sets (security levels for the underlying cryptographic algorithm), implementations and other parameters.
Although these are not multiple comparisons within the same data set (as each parameter generates a different set of measurements), ultimately the research question that I'm trying to answer is "does the hardware display data-independent timing?", and I collect evidence to answer that question through these different parameter sets and implementations. This leads me to the fourth and final question:
Question 4: would it be proper to apply the Bonferroni correction to my ensemble of measurements?
Answer: These are quite a few questions. Maybe I can focus on addressing the third one. However, you may need to tailor it to suit your specific situation. The pwrss R package effectively manages power for equivalence tests for both independent and dependent groups, although grasping its functionality solely from the documentation can be challenging. It took me some time to understand.
To begin, you'll need to establish a minimal effect size to define the bounds for equivalence. How much disparity can you accept? It could be simpler to articulate this value in terms of Cohen's d (at least in social science).
library(pwrss)

# Cohen's d = 0.25 - 0.25 = 0 for a paired sample
# need not be 0.25 - 0.25, can be 0.50 - 0.50 or even 0 - 0
np.desing <- pwrss.np.2groups(mu1 = 0.25, mu2 = 0.25, margin = 0.10,
                              paired = TRUE, power = 0.80,
                              alternative = "equivalent")

# Non-parametric Difference between Two Groups (Dependent samples)
# Wilcoxon signed-rank Test for Matched Pairs
# Method: GUENTHER
# ------------------------------
#  Statistical power = 0.8
#  n = 899
# ------------------------------
# Alternative = "equivalent"
# Non-centrality parameter = -2.929
# Degrees of freedom = 856.74
# Type I error rate = 0.05
# Type II error rate = 0.2

For what exactly do we need a minimum of 899 observations? Let's try to make sense of effect size margins in terms of probability of superiority.
# probability of superiority for d = 0 under equivalence
np.desing$parms$prob1

# [1] 0.5

# tolerance for probability of superiority under equivalence
delta <- np.desing$parms$prob1margin - np.desing$parms$prob1

# lower bound for probability of superiority
lb.margin <- np.desing$parms$prob1 - delta

# upper bound for probability of superiority
ub.margin <- np.desing$parms$prob1 + delta

# equivalence bounds for probability of superiority
round(c(lb.margin, ub.margin), 2)

# [1] 0.47 0.53

```


Loosing reference to state when listening to characteristics

Question: So I've tried multiple solutions to store states but for some reason I can't figure out why I'm loosing the (latest) state of some context. I'm using the following function to get an update on a specific characteristic (I also tried the .monitor() directly on the characteristic).
// This is in the BluetoothProvider
device.monitorCharacteristicForService(
    service.uuid,
    characteristic.uuid,
    onUpdate)

Further I have a function to check the state:
// This is in the BluetoothProvider
const updating = () => {
    if (currentMatch != null && currentPerson != null) {
        console.log('found person')
    } else {
        console.log('no person')
    }
}

The properties are stored in a reducer with an API/Data MatchProvider provider:
const { currentMatch, currentPerson } = useContext(MatchDataContext)

The onUpdate function:
const onUpdate = (
    error: BleError | null,
    characteristic: Characteristic | null
) => {
    updating()
}

The provider is in the the correct place:
<MatchProvider>
    <BluetoothProvider>
      <Routes>
      </Routes>
    </BluetoothProvider>
  </MatchProvider>

I've tried moving it to another component/provider/redux it doesn't matter. The onUpdate function just can't get the correct state. The UI works perfectly and the state is stored but the onUpdate method never gets the value.
Answer: Eventually I found the fix, what I did was add the following to the BluetoothProvider
const matchRef = useRef(currentMatch);
const personRef = useRef(currentPerson);

React.useEffect(() => {
    matchRef.current = currentMatch
    personRef.current = currentPerson
}, [currentMatch, currentPerson]);

This allowed me to listen to the updates from the MatchDataContext and store the references. Because down the file I had a subscription that was triggered when the bluetooth device received a new message, and this wasn't up-to-date on the latest state.
const onUpdate = (
    error: BleError | null,
    characteristic: Characteristic | null
) => {
    if (matchRef.current != null && personRef.current != null) {
        console.log('using match', JSON.stringify(matchRef.current, null, 2))
    }
}

For some reason all debugging tools indicated that the value was there, in the BluetoothProvider but when I called the property it was null.


How can I implement multiclass k-NN?

Question: I want to implement k-NN to use in a multi-class dataset. I found "A k-Nearest Neighbor Based Algorithm for Multi-label Classification" but didn't get the algorithm.
Do you know any clear explanation of it?
What I have in mind it works as follows:

Calculate posterior probabilities for each class (simply by dividing number of samples who are labelled as class_i to the number of total samples).
Then, for each test sample find it's nearest neighbours (e.g. assume k = 5, so we find top 5 nearest neighbour among all samples in the training set).
Then take majority class among these 5 neighbours as the class of the test sample (so if 3 of the 5 nearest neighbour has the Classx, then we'll classify the test sample as Classx).

Would that be a correct implementation?
Comment: As bayer answered, I think you meant multi-class classification. The paper you cited talk about multi-label classification, i.e. every record has many different labels. For multi-class classification with kNN just have a look to classical Data Mining book as "Introduction to Data Mining" by Tan et al.
Answer: It depends on what you mean by multi class--are you talking of a setting where (a) one item can have multiple classes or (b) an item can have one of many classes (as opposed to binary classification)?
From your proposal algorithm I take that you mean (b).
In that case, your idea is right, except that there is no need to take the prior (I think you mean prior instead of posterior probabilities in 1.) into account. That's typically not done, although I have no solid argument for that right now.
Answer: For corret multi label classification, means several catergories in result you have tune you algorithm measuring method. So you have to evaluate set(examples) to set(predicted result) comparison and also try several tresholds(radius of sphere) in which you select all categories.

How can I implement multiclass k-NN?


How to programmatically set the color scheme for a theme?

Question: Is there a way to programmatically change the color scheme, set by the color module, for a certain theme in Drupal 6 (in PHP or using drush)? For example, I can change Garland's color scheme from the UI:

but I want to do it programatically.
Comment: What do you mean by setting the color scheme? Changing the colors of what?
Comment: I mean it in regards to the color module. Edited the post to make it more clear.
Answer: No - this is not possible in 6.x due to how color is intended to work. Its meant to be a simple way to change a very basic theme, not for advanced users. In 6.x, when you change your color settings, it is doing the following:

Replaces hexidecimal colour values in CSS files
Creates sliced images with the new colours for use as CSS background images
Copies unchanged images without alterations

This creates a dump of 'color files' that looks like this in your files directory (for the Garland theme)
bg-bar-white.png
bg-bar.png
bg-content-left.png
bg-content-right.png
...
style.css

It also creates a random number for the folder each time, so the folder is getting deleted and recreated each time you save the changes.
All of this is to make it easier for novice users to change their colors, with I assume the understanding that if users could configure their own CSS and theme in code, they wouldn't be using the color module to begin with. This approach is also confirmed here on D.O by Jeff Burnz

Currently there is no way in Drupal core to export your custom color
  scheme to file, i.e. no way to capture the configuration

Conversely, there is no way to import an existing dump of colors files into your site.
Comment: If you can change it through the UI, you can change it through code (at the end of the day they're one and the same thing). You can't import/export config, but if you want to programatically change the colours, you just need to follow the code in [`color_scheme_form_submit()`](https://api.drupal.org/api/drupal/modules%21color%21color.module/function/color_scheme_form_submit/6)
Comment: ... but you would re-create those files every time. May be bad, might be okay. Depending on case.
Answer: As per @clive's suggestion, looking at what color_sheme_form_submit() is doing:
_submit() will delete previous files listed in variable
color_garland_files.
But renaming the public files folder color/garland-dda79d31 to color/garland-RED will give you a permanent copy of that folder full of garland color files.
(Let color module generate that folder for you -- make a permanent copy)
Inside a "good hook" (I use _page_alter()) ... you can dynamically, temporarily over-write the $conf array (full of variable_get() variables for this current page call:
function modulename_ctools_render_alter() {
 // look at all the variables
 global $conf;
 kpr($conf);
 // look at the one we need
 $RED = variable_get('color_garland_stylesheets');
 // this, we will re-use:
 echo var_export($RED);
}

... will show you a PHP-formed array of said variable. Over-write it.
// this is how they look
#$STYLES = variable_get('color_garland_stylesheets');
#echo var_export($STYLES);
// over-write
$conf['color_garland_stylesheets'] = array(
    0 => 'public://color/garland-RED/style.css',
    1 => 'public://color/garland-RED/style-rtl.css',
  );

That was sufficient for me. All files in that folder can keep their filenames. All .css stays and works.


Doctrine targetEntity abstract class

Question: I get unnecessary queries then entity has ManyToOne relationship with abstract class.
My classes structure:
/**
 * @ORM\Entity
 * @ORM\Table(name="tb_payment_info")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="type", type="integer")
 * @ORM\DiscriminatorMap({
 *          "0" = "PaymentInfoPaypal",
 *          "1" = "PaymentInfoSkrill",
 * })
 */
abstract class AbstractPaymentInfo
{
    /**
     * @ORM\Column(name="payment_info_id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;
}

/**
 * @ORM\Entity
 * @ORM\Table(name="tb_payment_info_paypal")
 */
class PaymentInfoPaypal extends AbstractPaymentInfo
{
}

/**
 * @ORM\Entity
 * @ORM\Table(name="tb_payment_info_skrill")
 */
class PaymentInfoSkrill extends AbstractPaymentInfo
{
}

My Payout class contains payment_info_id column from tb_payment_info table.
/**
 * @ORM\Entity
 * @ORM\Table(name="tb_payout")
 */
class Payout
{
    /**
     * @var AbstractPaymentInfo
     *
     * @ORM\ManyToOne(targetEntity="AbstractPaymentInfo")
     * @ORM\JoinColumn(name="payment_info_id", referencedColumnName="payment_info_id")
     */
    private $paymentInfo;
}

When I try to get any Payout entity, its paymentInfo initialize automatically. So:
$this->getEntityManager()->getRepository('TuoPayBundle:Payout')->find(255);

got 2 queries: first for Payout and second for its paymentInfo
$this->getEntityManager()->getRepository('TuoPayBundle:Payout')->findBy(['id'=>[255,256]]);

got 3 queries: first for Payout and second, third separate queries to init paymentInfo
How to achieve lazy load?
Answer: You cannot declare an abstract class in Doctrine 2 with @ORM\Entity notation. If you want to use abstract classes in your object model I suggest you check the documentation on Mapped Superclasses on how to do that correctly.
Most importantly you should declare the class with a special @ORM\MappedSuperClass annotation.
Keep in mind that Mapped superclasses come with restrictions. I quote:

A mapped superclass cannot be an entity, it is not query-able and persistent relationships defined by a mapped superclass must be unidirectional (with an owning side only). This means that One-To-Many associations are not possible on a mapped superclass at all. Furthermore Many-To-Many associations are only possible if the mapped superclass is only used in exactly one entity at the moment. For further support of inheritance, the single or joined table inheritance features have to be used.
Comment: On **[Google](https://s-media-cache-ak0.pinimg.com/736x/90/69/55/906955ddebb869ec8fb4797509a37ca3.jpg)** you can find a lot of things. You should refer to the official documentation.
Comment: I try to use MappedSuperClass before this post. But I get Exception: Its not supported to define inheritance information on a mapped superclass
Comment: What exception. Maybe post a separate question about that...? I am sure that what you do here is not correct and will lead to issues!
Comment: You are mixing up class inheritance and abstract mapping. You should maybe consider only using abstract mapping for common properties and skip the inheritance...
Comment: In google I found that it occures because of ORM\InheritanceType("JOINED"). I don't try, but google say me that with ORM\InheritanceType("SINGLE_TABLE") it work's fine. But I need "JOINED". So we must found another approach.

Doctrine targetEntity abstract class


How to count this in a faster way?

Question: It's a homework problem, it took me 20mins to do it,
and what's even worse is that I didn't get the correct exact answer....
(we are only asked to give an approximate number, I didn't lose any point tho...)
initially, a=0, b=0, C=0.
C is used to count the number of times of algorithm.
when a=0, b start from 0, 1, 2,... to whenever a^2+b^2 >= 2500, then stop
then a=1, b start from 0, 1, 2,... to whenever a^2+b^2 >= 2500, then stop
.
.
.
.
keep going on, and the last loop will be a=49, b=0,1,2,...9.
The question is the value of C.
I did it step by step, like when a=3, a^2=9,
then doing some "square" & "subtract" work knowing that b stops at b=49.
I'm wondering if there's a SMART way to do it fast and correctly without computers...
Thanks!!
Comment: This is the [Gauss circle problem](http://en.wikipedia.org/wiki/Gauss_circle_problem) There is no easy exact expression, though there are approximations.
Comment: @RossMillikan, Thanks for the heads up!!
Answer: For any particular $a$, $b$ can go up to the largest integer below $\sqrt{2500-a^2}$. So for any particular $a$ we have the count equal to $\lfloor\sqrt{(2500-a^2)}\rfloor$. The half brackets mean the floor function. Then you would sum this up from $a=0$ up to $a=49$. (You could also sum to $a=50$, but the floor of 0 is 0.)
Plugging into wolframalpha I get
$\sum_{a=0}^{a=49} \lfloor\sqrt{(2500-a^2)}\rfloor = 1961$
This is assuming that C is not incremented when $a^2+b^2 \ge 2500$. If C is incremented on the iteration on which this condition is satisfied, then we use the ceiling function instead to get $\sum_{a=0}^{a=49} \lceil\sqrt{(2500-a^2)}\rceil = 2006$
Comment: that's exactly how I did. but I'm thinking maybe there's another way to get C. otherwise, it really gonna take a long while to get to the answer.....
Comment: the answer is 2006 ><
Comment: Sorry, the factor of a should not be there. I took it out in an edit.
Comment: The answer is 2006 if you use the ceiling function. This means that when you hit the condition that a^2+b^2 >= 2500, then C is again incremented. I assumed from the problem statement that the a^2+b^2 >= 2500 condition was the loop control that determined if C would be incremented.
Comment: i see~~ thank u so much

How to count this in a faster way?


How to implement unknown/optional fields in SQLAlchemy, where the user can add their own new fields?

Question: I am writing a python program also using Sqlalchemy, which stores an entry for something, but I would like to let the user add their own fields.
Here's my model at the moment, using Python 3 and Sqlalchemy
class Item(Base):
    __tablename__ = 'items'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('folders.id'),     nullable=True)
    name = Column(String(128))
    key = Column(String(256))
    value = Column(String(512))
    extras = Column(Binary)
    next_scheduled = Column(DateTime)
    new = Column(Integer)

How should I go about functionality for the user adding their own fields?
Answer: Here's how I would do it:
Create two new tables, one for fields and one for answers.  Make the answer a child of both the question (user-defined field) and original item.  Users can add fields by adding lines to the fields table, and you can retrieve the answers to all custom fields whenever you pull the original item:
class CustomField(Base):
    __tablename__ = 'custom_fields'
    id = Column(Integer, primary_key=True)
    name = Column(String(128)) # internal name in this case
    title = Column(Text) # Text of field label

class CustomResponse(Base):
    __tablename__ = 'custom_responses'
    id = Column(Integer, primary_key=True)
    item_id = Column(Integer, ForeignKey('items.id'))
    item = relationship('Item', backref='custom_responses')
    custom_field_id = Column(Integer, ForeignKey('custom_fields.id'))
    custom_field = relationship('CustomField') # put backref here if needed
    value = Column(Text) # Actual answer

You can even provide instructions to whatever you're using to draw the form by putting a widget = Column(...) column on your custom_fields table, or any other options/instructions.  If you want to have each custom field available to only one item, then duplicate the item_id column and item relationship on the CustomField model.
No sense in trying to force all the data on one row; let sqlalchemy take care of relationships.  In this case, you could get all custom field questions and answers through the relationships:
If i = Item(), then i.custom_responses will return a list of all completed CustomResponse objects associated with that item, and for each custom_response, you can get the question with custom_response.custom_field.


How can I simplify this expressions to get one formula?

Question: the expressions are :
f(1) = (a^0)
f(2) = (a+1)
f(3) = (a^2+a+1)
and the answer is f(n)= (a^n-1) /a-1, it is the formula for the sum of the geometric series right ?
I have tried to find the formula but I stuck in this :
f(1)= a^(n-1)
f(2)= a^(n-1)+a^(n-2)
f(3)= a^(n-1)+a^(n-2)+a^(n-3)
how can I make the 3 equations below to find that the formula is the sum of geometric series ,,
Comment: You use the ^ in two different ways. By f^1 do you mean $f(1)$ or $f_1$?  On the right it looks like normal exponentiation.
Comment: You wrote $f^1=a^0$. Did you mean $f_0=a_0$? I imagine you did.
Comment: @TheCount:  I don't think so, I think OP means $f(1)=a^0=1$.  It is one term of the geometric series.
Comment: @RossMillikan It seems like that would be an odd way to write the first term, but also I see your contextual argument too.
Comment: @AsterZen here is a website to help you format your question so it is easier to understand and answer: https://latex.wikia.com/wiki/List_of_LaTeX_symbols
Comment: yes that's right, sorry I made a mistake, I have change them, thank you @RossMillikan
Comment: Please read this [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) on how to typeset mathematics on this site.
Answer: Assuming that by f^1 you mean $f(1)$ and so on there is no way to find that $f(n)$ is the sum of the geometric series aside from recognizing the pattern.  Nothing in the data you are given tells you what $f(4)$ is.  The geometric series is (to my eye) the simplest explanation for the first three terms and problems where you are given the first few terms of a series or sequence are intended to be solved by finding the simplest pattern (to the setter's eye) and extending it.
Whenever somebody posts a sequence or series problem there are those who complain (I would say correctly but pedantically) that you can extend the sequence or series any way you want so there is no solution.  I believe the setter owes us enough information to make one solution stand out as the simplest and it can be a fun problem to find it.  Here  I would go with the geometric series as you suggest.


Mapeamento de rota não funciona no ASP.NET Core 2.2

Question: Sempre utilizei ASP.NET MVC 4 e agora estou aprendendo ASP.NET Core na versão 2.2, estou fazendo alguns testes e notei que o roteamento não está funcionando.
Estou utilizando o projeto padrão que já vem configurado.

Dentro de Startup.cs configuro a rota da seguinte maneira:
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseMvc(routes =>
        {
            routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
        });
 }

Então insiro o seguinte na página index.cshtml:
@Html.ActionLink("Link para a Action About no mesmo controlador", "About")

Porém quando vou ver o resultado na View Index.cshml me é retornado:

Estou fazendo algo de errado?
Comment: Você tá usando ASP.NET "normal" com .NET Core? O.o
Comment: ASP.NET Core 2.2
Comment: No asp.net core tens uma forma mais "limpa" de criar links
    Link para a Action About no mesmo controlador
Além do action podes especificar a Area e o Controller.
Comment: Outra coisa importante no .net core (que já era no MVC 4) é respeitar as convenções (regras de código), o compilador/interpretador respeita essas regras na hora de interpretar o teu código, refiro isto porque na estrutura do teu projeto faltam algumas das pastas da convenção MVC... para o ActionLink o controller e o action tem que existir e respeitar a convenção para serem reconhecidos como tal. Só assim na hora de gerar o link o .net core saberá qual a route correta para gerar o <a href=...
Answer: O projeto que você está trabalhando não é do template do MVC, a rota que você diz que não funciona porque não existem controllers ou views nessa estrutura. Você iniciou seu projeto escolhendo a opção de Web Application, também conhecido como Razor Pages que tem por padrão de rota inicial a página index.

Pegando como exemplo a página About, para onde você queria criar o ActionLink, perceba que ela é composta por um template Razor (.cshmtl) com o bind à uma classe de PageModel (cshtml.cs), que vai controlar as suas ações em forma de eventos... como se fossem as actions de uma controller.
About.cshml
@page
@model AboutModel
@{
    ViewData["Title"] = "About";
}

@ViewData["Title"]

@Model.Message

Use this area to provide additional information.

About.cshtml.cs
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace WebApplication.Razor.Pages
{
    public class AboutModel : PageModel
    {
        public string Message { get; set; }

        public void OnGet()
        {
            Message = "Your application description page.";
        }
    }
}

E nessa estrutura, para você adicionar um link na Index para a about, basta você adicionar na Index.cshml a seguinte marcação:
About

Contudo, se você deseja continuar trabalhando com o MVC no asp.net core, basta você criar o seu projeto utilizando o templante "Web Application (Model-View-Controller)".

A estrutura é quase a mesma da que você está acostumado no MVC4, porém implementação os recursos disponíveis são um tanto diferente. E segue abaixo forma recomendada de criar o seu ActionLink nessa versão.
About

Answer: Esta faltando O Controller e as Views, sugiro que crie outro projeto. E apos isso você configura o controller pra renderizar as paginas que vocÊ quer


PHP's ctype_digit security

Question: Can anything dangerous get by 'ctype_digit' ? May be hexadecimal characters like '0x' ?
My reasoning is that not much harm can be done with just number characters.
I know 'mysqli_real_escape_string' is available but thought the ctype_digit is more restrictive and is more suitable for this case.
I'm sending the values via PHP's 'file_get_contents' for the numeric ID of the visitor.
The data is going to be sent to a MySQL query.
I know 'file_get_contents' is another can of worms.
Answer: ctype_digit() only allows 0123456789. Anything else will return false. In other words,  if you only allow digits then this function will do exactly that.
Answer: ctype_digit is a safe function when validating data.
Just ensure that you're passing a string to it.
Older PHPs convert ints to their corresponding characters as per ascii table.
so
ctype_digit( 48 )  ==> true equivalent to `ctype_digit( "0" );
but
ctype_digit( 1234 ) ==> false and this is something many would not expect (unless the documetation has been read with attention).
Actual PHP (8.1.9) has still this behaviour but raises a warning.
Future PHPs will turn the integer into string (as per PHP warning).

In short, ensure to pass the function a string

PHP's ctype_digit security


Pegar valor string de um txt

Question: Tenho em um txt que é espelho de uma impressora fiscal, gostaria de pegar o número do COO correspondente apenas da REDUÇÃO Z,
no exemplo a baixo gostaria de pegar apenas o valor 031717.
02/01/2014 11:50:06                   COO:031717

         REDUÇÃO Z
MOVIMENTO DO DIA: 01/01/2014

02/01/2014 11:50:06                   COO:031718

         LEITURA X
MOVIMENTO DO DIA: 01/01/2014

No meu Código eu consigo pegar todos os COO e colocar em outro arquivo, mas gostaria de pegar apenas o da Redução Z.
Segue trecho do código:
BufferedReader br = new BufferedReader(new FileReader("arquivo.txt"));
        String linha;
        while ((linha = br.readLine())!=null) {
            String texto="";
            if (linha.contains("COO:")) {
                texto = linha.substring(linha.length()-6, linha.length());
                FileWriter escrever = new FileWriter(new SimpleDateFormat("dd-MM-yyyy").format(new Date())+".txt", true);
                escrever.append(texto+"\n");
                escrever.close();
            }
        }

Comment: Depois do C00, a próxima palavra é sempre o termo associado (REDUÇÃO Z, LEITURA X, ...)?
Comment: Sim, mas em linha diferente
Answer: Se sempre for LEITURA ou REDUCAO, ao passar pelo COO crie um objeto que tenha dois campos, COO e tipo. Ai você guarda o COO e o tipo e guarda esse objeto numa lista. No final você vai ter uma lista de objetos já processados, então é só filtrar esses objetos os que tem REDUCAO ou LEITURA, conforme o que você precisar.

Pegar valor string de um txt


Cannot delete or edit files on ProFTPD server

Question: I have an Linux server running Ubuntu Jaunty. I have successfully set up an FTP server for the user 'fileserver' using this configuration in proftpd.conf:
<Global>
  <Limit ALL>
    DenyAll
    AllowUser fileserver
  </Limit>
</Global>

I this allows only the 'fileserver' user to login, and nobody else. I am able to upload files fine. This is what I want so far. The problem is, I cannot edit, overwrite, delete or move any files. I would like to have full, unrestricted access when I log in. How can I do this?
I've seen this ProFTPD tutorial, but I still can't figure out how to allow a user to have all the permissions, to enable deletes and edits.
Comment: be careful when playing with these settings, there are some traversal attacks that might bite you
Answer: From a quick read of the docs on limits, your limit configuration looks like it should do what you want. The problem is likely file system permissions.
You may want to read up on the mode and umask settings here. ProFTPD creates files with a base mode of 666 (read/write/no execute). The umask setting is used to further restrict the permissions specified by the mode. Check your .conf for a umask setting that may be restricting permissions and preventing you from overwriting, moving or deleting files.
example:
# Umask 022 is a good standard umask to prevent new dirs and files
# from being group and world writable.
Umask               022

If there is any umask setting in the .conf file, try commenting it out and upload a file, then verify the file system permissions on it and experiment from there. Good luck.
Answer: You could check the ownership & file permissions on the fileserver user's home directory (or FTP directory, if this is different)
Answer: Apparently also check to see that the fileserver login owns the folder(s).
This from an accepted answer to a similar question on another certain IT community site:

supposing you used the standard user
  for proftpd you need to first make
  this user the owner of the folder
  (when your accessing the FTP the
  system will recognise the server as
  this user regardless of who you login
  as)
run code snippet 1) first
secondly you need to ensure this user
  has read/write access and presumably
  other users can only read from it. Use
  code snippet 2)

Code Snippets
1) chown -R userftp /home/FTP-shared/read-write
2) chmod -R 0755 /home/FTP-shared/read-write


ActiveAdmin resource controller override / resource delete issue

Question: I describe how I'm override the resource controller here in another question which I self-answered:  Override ActiveAdmin resource controller for only some resources
This has been working without any issue for a year now, but I recently updated ActiveAdmin and now when I delete and hit the function:
def destroy
      if HIPPA_CLASS_ARRAY.include? self.resource_class.name
        if !params[:comment].nil? && !params[:comment].empty?
          @comment=ActiveAdmin::Comment.new(namespace: "admin", author: current_admin_user, resource: resource, body: params[:comment]  )
          @comment.save
          Utils.track_action(request, current_admin_user, "admin_#{params[:action]}", "web", params, false,  resource)
          resource.destroy

          flash[:notice] = "Delete was successful."

    #=> THE FOLLOWING IS THE PROBLEM

          redirect_to { action: "index" }

        else
           flash[:notice] = "A delete comment can not be blank."
            render :js => 'window.location.reload()'
        end
      else
        super
      end
    end

Out of nowhere I'm now getting:

ActionController::RoutingError (No route matches [DELETE] "/admin/products"):

I've tried:
redirect_to { action: "index" } and return

redirect_to({ action: 'index' }, notice: "Delete was successful.", status: 302) and return

redirect_back fallback_location: { action: "index" } and return

None of these work; the resource gets deleted, but it doesn't redirect to the resource's index anymore.
Answer: Might be a change in how your browser is handling redirect from delete method. Try this:
redirect_to { action: 'index', status: 303 }
Comment: Still not working; since the delete is triggered from either the resource.show (detail) page in active admin or hitting 'delete' in the action on the index page, I created a gist of what is in the log:  https://gist.github.com/grimmwerks/bf6bd76d4fffe8a370d9aa4c25f36306         Basically it tries to redirect but it doesn't I even attempted    redirect_to({action: 'index', status: 303 }) and return


Erro de PHP, 'exit' (T_EXIT)

Question: Estou praticando um pouco de php, e quando vou executa-lo, aparece esse erro na tela do local host:

Parse error: syntax error, unexpected 'exit' (T_EXIT), expecting ','
  or ';' in C:\xampp\htdocs\login.php on line 22

eu entendo o que é erro de sintaxe, porém, eu gostaria de entender o erro.
[
<?php

$host = "localhost";
$user = "root";
$pass = "";
$db = "users";

mysql_connect($host, $user, $pass);
mysql_select_db($db);

if (isset($_POST['username'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];

    $sql = "SELECT * FROM user WHERE username='".$username."'AND password='".$password."'LIMIT 1";
    $res = mysql_query($sql);
    if (mysql_num_rows($res) == 1) {
    echo "logado";
    exit();
    } else {
    echo "dados incorretos"
        exit();
    }
    }

?>
]

Comment: Parece que faltou um `;` no echo antes do `exit();`, `} else {
    echo "dados incorretos"` vc está usando alguma IDE?
Comment: Sim, estou usando uma IDE, Brackets, embora ainda não indicada para server side, é só para teste mesmo.
Answer: O erro diz que a função exit() não era esperada e sim um ; ou seja o erro está na linha anterior ao exit().
} else {
   echo "dados incorretos" <---- cade o ponto e virgula ?
exit();

Para evitar esse tipo de erro utilize alguma IDE como o eclipse ou editores de texto com funcionalidades avançadas como o notepad++ ou sublimetext.
Comment: Não tem nada a ver com a IDE, mas sim o erro de sintaxe da virgula.. `+1`
Comment: Silvio, a questão é que o uso de uma IDE previne o erro, já que informa o erro, e define métodos de correção.
Comment: é, me disseram que o eclipse é bem recomendado. mas por enquanto estou usando a atual para treino mesmo.

Erro de PHP, 'exit' (T_EXIT)


How do i factor out the vector $\vec{a}$?

Question: Hello i have come to the following expression and i would like to factor $\vec{a}$ in some way so that i can get the aceleration, but i am in doubt on how to do this, can someone help me ?
$$\vec{a} + \frac{\vec{v}\cdot\vec{a}}{c^2-u^2}\vec{v} = \frac{q}{m}\sqrt{1-\frac{u^2}{c^2}}(\vec{E}+\vec{u}\times\vec{B})$$
Comment: What do these brackets stand for?
Comment: nothing really, they are there only to separete the terms
Comment: Separate from what? The equality sign has the least precedence level, the brackets just make it more confusing.
Comment: well originally i was trying to factor out the $\vec{a}$ so those brackets would separate the $\vec{a}$ from some other vector
Answer: $\newcommand{\vect}[1]{{\bf #1}}$
If you define $\vect{a}$ as a column vector, then $\vect{a}\cdot \vect{b}$ is just $\vect{a}^T\vect{b}$ therefore, you can also write your equation as
$$
\left[\vect{1} + \frac{\vect{v} \vect{v}^T }{c^2-u^2} \right]\vect{a}  = \frac{q}{m}\sqrt{1 - \frac{u^2}{c^2}}(\vect{E} + \vect{u}\times\vect{B})
$$
which is just a problem of the form $\vect{A}\vect{x} = \vect{b}$, $\vect{x} = \vect{a}$
Comment: @stressed-out

$$
\{v v^T\}a = \left\{\left(\begin{matrix}1\\0\end{matrix}\right)(1~0)\right\}\left(\begin{matrix}0\\1\end{matrix}\right) = \left(\begin{matrix}1 & 0 \\0 & 0\end{matrix}\right)\left(\begin{matrix}0\\1\end{matrix}\right) = \left(\begin{matrix}0\\0\end{matrix}\right)
$$

$$
\{v^T a\}v = \left\{(1~0) \left(\begin{matrix}0\\1\end{matrix}\right)\right\}\left(\begin{matrix}1\\0\end{matrix}\right) = 0\left(\begin{matrix}1\\0\end{matrix}\right) = \left(\begin{matrix}0\\0\end{matrix}\right)
$$

I am definitely failing at grasping what is your actual concern
Comment: is the 1 a vector ?
Comment: @FelipeDilho ${\bf 1}$ is the identity matrix
Comment: Why is $(\vec{v}\vec{v}^{T})\vec{a}$ equal to $(\vec{a}\cdot \vec{v}) \vec{v}$?
Comment: @stressed-out $({\bf a}\cdot {\bf v}){\bf v} = {\bf v}({\bf v}\cdot{\bf a})$
Comment: @caverac: I agree with the identity you wrote now, but the identity I'm asking about is a different one:  the first expression is something scaled in the direction of $\vec{a}$ while the second expression is something scaled in the direction of $\vec{v}$. Unless $\vec{v}$ and $\vec{a}$ were linearly dependent, why should these two agree?
Comment: Because $(\vec{v}\vec{v}^T) \vec{a}=\vec{v} \vec{v}^T\vec{a} = \vec{v} (\vec{v}\cdot \vec{a})$. Since the euclidean metric is symmetric we have $ a \cdot v = v \cdot a$. Because It's a scalar $v (v\cdot a) = (a \cdot v) v$
Comment: @Triatticus: Your first identity which is the identity I'm talking about (and it's this identity that we need to have for that factorization, I guess) is obviously wrong. For a counter-example, take $\vec{v}=\vec{e_1}=(1,0)$ and $\vec{a}=\vec{e_2}=(0,1)$. Then $(\vec{v}\cdot \vec{v})\vec{a}=\vec{a}$ but $(\vec{a}\cdot\vec{v})\vec{v}=\vec{0}$ and $\vec{a} \neq \vec{0}$.
Comment: $v v^T\neq v \cdot v$ It's actually a matrix/array, I believe it's called a dayad formed from the outer product of two vectors.
Comment: @Triatticus: $vv^T$ is supposed to be the dot product in the original question of the OP and the first line of this answer. Look at what the OP has asked for. Plus, I don't think if the dimension of it were larger the situation would've been any better. It will probably become worse.
Comment: No because it is dotted with $a$ so it must be of the form $v^T a$ and it doesn't matter where the other v is because the dotted term is a scalar, the only way to rearrange it to make sense is to break it down how this answer does
Comment: @Triatticus: as my counter-example shows, it does matter where the other $\vec{v}$ is because the expression lacks associativity. In general, $(\vec{v} \cdot \vec{v}) \vec{a} = (\vec{v} \cdot \vec{a}) \vec{v}$ is certainly wrong when $\vec{a}$ and $\vec{v}$ are linearly independent. It's very obvious. If you claim the otherwise, prove it. Even expanding them and writing them out in components show that they don't have to be equal. The LHS is a scalar of $\vec{a}$ and the RHS is a scalar of $\vec{v}$. Hence, $\vec{a}$ and $\vec{v}$ have to be linearly dependent which is not necessarily true.
Comment: @stressed-out Please note that I'm ***not*** claiming $(\vec{v}\cdot\vec{v})\vec{a} = (\vec{v}\cdot\vec{a})\vec{v}$. The dot product is $v^T a$, ***not*** $v a^T$ as you insist. This being the case
$$
(\vec{v}\cdot \vec{a})\vec{v} = (v^T a)v = v(v^T a) = (vv^T)a
$$
Comment: @caverac: Yes, if we work with column vectors then $\vec{a} \cdot \vec{v} = a^Tv$. It doesn't matter whether we work with column vectors or row vectors, I think. They are isomorphic. The problem is not fixed because your last step is still wrong. $\vec{v}(\vec{v}^T\vec{a}) \neq (\vec{v}\vec{v}^T)\vec{a}$. You can't move the parentheses just like that. It's not associative. So, if the dot product in physics has the same meaning as it has in mathematics, that identity is definitely and obviously wrong when $\vec{a}$ and $\vec{v}$ are linearly independent.
Comment: @stressed-out Yes you can, it's called the "associative property"
Comment: @caverac: No, you can't. As I said, the "associative property" does not hold here. Not every algebraic structure has to be associative. See my counter-example. How do you justify that? Plus, the "associative property" works when you're dealing with a binary operation $*$ and you have $(a*b)*c=a*(b*c)$ in some algebraic structure. Here, you have two different operations, namely the dot product defined on $V \times V$ and a scalar product that's defined on $\mathbb{R} \times V$ where $V=\mathbb{R}^3$ is a vector space.
Comment: @caverac: This is super cool. I checked it by writing the components and it works! It will go straight to my notes. Even though the first line is not a dot product anymore but the equality that we need for this answer to work holds and I retract my objection. I think you were talking about the tensor product and all the time I was like "what operation on vectors is he/she talking about?". :)


Pegar dados de campos de mesmo nome mas de tabelas diferentes

Question: Tenho um select que ele busca dados de três tabelas diferentes, mas tem alguns campos em comum entre essas três tabelas. Minha dúvida é como pegar os dados desse campos, que tem o nome em comum com as outras tabelas.
Meu select está assim:
    SELECT suporte_cad.reg,suporte_cad.data,suporte_cad.status,
    suporte_cad.nmcontato, suporte_cad.mensagem ,
    serv_cad.nmgrupo,serv_cad.dsservico, suporte_det.reg,
    suporte_det.data, suporte_det.nmContato, suporte_det.nmUsuario,
    suporte_det.mensagem

    FROM suporte_cad,serv_cad,suporte_det where cnpj='$getCnpj'
    and suporte_cad.idservcad=serv_cad.idservcad and suporte_det.reg='$reg'
    and suporte_cad.reg = '$reg'

Quero pegar o campo mensagem  da tabelas suporte_cad e suporte_det
Comment: SQL AS http://www.w3schools.com/sql/sql_alias.asp
Comment: @bigown Estou supondo que o problema é na outra ponta (PHP?), na hora de ler os resultados pelo nome da coluna.
Comment: O ALIAS me resolveu, fez exatamente o que eu queria
Comment: Não entendi, você está pegando os campos que deseja.
Comment: @bfavaretto matou, acho que é isto mesmo, ele iria usar em outro lugar, talvez até no `JOIN` que seria colocado depois.
Answer: Use um alias em cada um desses campos, que você define com AS:
SELECT
    suporte_cad.reg,
    suporte_cad.data,
    suporte_cad.status,
    suporte_cad.nmcontato,
    suporte_cad.mensagem AS mensagem_cad,
    serv_cad.nmgrupo,
    serv_cad.dsservico,
    suporte_det.reg,
    suporte_det.data,
    suporte_det.nmContato,
    suporte_det.nmUsuario,
    suporte_det.mensagem AS mensagem_det
...


How does one find the quotient in a polynomial ring in 2 and more variables?

Question: Given the polynomial ring in 2 variables, how do we prove the following: $k[x,y]/(y-x^2) \cong k[x,x^2]$ ? In one variable I can follow the argument. Also in case the ideal we take the quotient with is generated by monomials for which we can perform a polynomial division. Thanks for your comment or explanation.
Comment: Well the relation tells you $y = x^2$. So the explicit bijection to use should be clear hopefully
Comment: The fundamental isomorphism theorems still apply.
Comment: Please [search for answers](https://math.meta.stackexchange.com/a/29267/242) before posting questions.
Answer: Intuitively you 'divide out' any factors of $(y-x^2)$ just as you would with modular arithmetic. In the same way (if we denote the the reduction Mod $(y-x^2)$ by a bar) we have that $\overline{y-x^2} = \overline{0}$ so $\overline{y} = \overline{x^2}$.
Now to prove that $k[x,y]/(y-x^2) \cong k[x,x^2]$ we need the first Isomorphism theorem which states that if $\xi:R \to S$ is a ring homomorphism, then $R/\ker{\xi} \cong \xi(R)$.
We can construct this homomorphism as follows:
\begin{align*}
\xi: k[x,y] &\to k[x,x^2]\\
(x,y) &\mapsto (x,x^2)
\end{align*}
(this is an evaluation map).
Now you only need to prove that the kernel is the ideal generated by $y-x^2$
Comment: @BillDubuque Josef K. is a member for whole 44 days. I think taking care about the site should also include caring about its member without which the site wouldn't exist.
Comment: @Ennar Actually organizing the site is far from boring, In many cases it can be more interesting than repeating the same old answers ad infinitum - since it forces one to think about how various proofs are related to one another as one iteratively refines prior answers.
Comment: Please strive not to post more (dupe) answers to dupes of FAQs, cf. recent site policy announcement [here](https://math.meta.stackexchange.com/q/33508/242).
Comment: @BillDubuque, to be fair, the answer was posted before you marked this question as a duplicate.
Comment: @Ennar Please do read the linked meta post. Users are expected to help organize the site - which means not posting (dupe) answers to common exercises that have surely been answered many times already over the past 13 years.
Comment: @Ennar I don't follow your logic. You think that informing new members about site policy is "uncaring"???
Comment: @BillDubuque the point is that posting impersonal copy-paste comments is probably not the best way to teach new users the policies of the site, at least in cases like this. To you and me, this was clear to be duplicate, but why expect a new user to recognize it? Surely, if you believe that all users should search for duplicates before answering, you can also take time to customize your message according to circumstances to make it more friendly, and less bot-like.
Comment: @Ennar I post a huge number of such comments, There is generally no time for customization.
Comment: @BillDubuque well, people may also not find time to check for duplicates. I'm grateful that you are doing the boring administrative work, but I think we should all appreciate the work people do when they write answers. Perhaps add another c/p comment of this type to be able to appreciate subtlety of the situation.
Comment: @BillDubuque to me it's interesting to find out what exactly does someone asking a question not understand and to address that, even when it's a question asked many times before. This is a subtlety I think the site policy doesn't recognize: even when it's the same exercise, people might actually be asking different questions about it. I think it's useful to link these as duplicates, but I don't think there is no value in answering anyway, since the specific misunderstanding askers may have might differ, and addressing that might make no sense at all in different thread.


Ajuda em Get List (Refatoração Código)

Question: Eu tenho uma classe com 2 atributos:
public class Classe(){
 private String conteudo;
 private String tipoConteudo;

 getters...setters..
}

Então eu tenho um ArrayList com 3 ou mais objetos dessa classe, como eu faço em uma linha um get de um Objeto específico de um certo conteúdo??
Por exemplo, se eu quero o objeto que o Tipo é azul, em várias linhas seria:
Classe objetoFinal;

for(int i;i<List.size();i++){
  if(objetoFinal.tipoConteudo.equals("azul")
     objetoFinal = List.get(i);
}

Então a dúvida é: como fazer isso em uma linha (preciso colocar em uma página JSF :D)
Comment: Você não pode fazer um método com o seu código de pesquisa e depois utilizar ele na outra página?
Comment: Porque deve ser em uma linha? O que esse requisito tem a ver com o JSF?
Comment: @mgibsonbr se for esse mesmo o caso, a solução do Fábio é perfeita.
Comment: Eu recomendaria [uma abordagem funcional](http://functionaljava.org/).
Comment: @MiguelCartagena provavelmente porque ele está querendo usar isso numa expressão (ex.: `${ ... }`) que deve retornar um valor.
Answer: Para realizar essa operação em apenas uma linha deve-se colocar o código de busca em um método getter no ManagedBean, vejamos:
public class MyBean {
    public Object getObjetoFinal(){
        Object objetoFinal = null;

        for(int i;i<List.size();i++){
            if(objetoFinal.tipoConteudo.equals("azul")
                objetoFinal = List.get(i);
        }

        return objetoFinal;
     }
}

Então em uma página JSF coloca-se a expressão em apenas uma linha, veja:
    <h:outputText value = "#{myBean.objetoFinal.conteudo}" />

Desse modo você terá uma instância ou null caso não seja encontrado um objeto azul.
Comment: Não é melhor usar `for (Classe c : List) {...}`?
Comment: Sim. O for aprimorado é um atalho interessante em Java 6, mas preferi utilizar o trecho de código da própria pergunta para a resposta ficar simples e direta.
Comment: Certo, mas o código original está errado. Deveria ser `if (List.get(i).tipoConteudo.equals("azul"))`. Só deixei essa nota porque o `for` tradicional chamando `size` a cada iteração e depois fazendo um `get(i)` é menos eficiente e deixa o código mais poluído. Fora isso sua resposta está correta.
Answer: Em JSF, os dados podem ser recuperados em um facelet (arquivo .xhtml) ou mesmo em um JSP através da simples chamadas a métodos getter de beans JSF.
Não é necessário criar expression languages elaboradas, basta delegar a lógica necessário ao getter do Managed Bean.
Um ponto a ser considerado é que não há garantia de que um getter será chamado apenas uma vez. Se o código executado no getter tiver algum custo, por exemplo leitura no banco de dados, deve-se "cachear" o valor em um atributo do bean.
Exemplo:
private List<Classe> list;
public String getListClasses() {
    if (list == null) {
        list = dao.listaClassesDoBanco();
    }
    return list;
}

E, no caso de uma operação que faz busca por um atributo, dependendo do custo, poderia-se também criar um mapa cuja chave seja o valor do atributo.
Além disso, se a lista não é alterada na tela ela deve ser carregada uma só vez. Isso pode ser feito como no método acima ou ainda num método anotado com @PostConstruct, que é chamado sempre que o bean é recriado no seu devido escopo.
Exemplo:
public class ManagedBean {

    private List<Classe> list = new ArrayList<Classe>();
    private Map<String, Classe> mapaClasse;

    @PostConstruct
    public void init() {
        list = dao.listaClassesDoBanco();
    }

    private Map<String, Classe> getMapaClasse() {
        if (mapaClasse == null) {
            mapaClasse = new HashMap<String, Classe>();
            for (Classe c : list) {
                mapaClasse.put(c.tipoConteudo, c);
            }
        }
        return mapaClasse;
    }

    public Classe getObjetoAzul() {
        return getMapaClasse().get("azul");
    }

    ...

}

A expressão no seu facelet fica assim:
#{managedBean.objetoFinal.objetoAzul}

Também é possível acessar o valor do mapa diretamente:
#{managedBean.mapaClasse.azul}

Ou:
#{managedBean.mapaClasse['azul']}

Se estiver usando EL 2.2, pode ainda fazer isso:
public Classe getObjetoPorTipoConteudo(String tipoConteudo) {
    return getMapaClasse().get(tipoConteudo);
}

E usar a expressão:
#{managedBean.getObjetoPorTipoConteudo('azul')}

Answer: Desculpem a demora por responder, mas consegui solucionar o problema, mas agora eu ja mudei o codigo do projeto e não mais estou utilizando esse trecho do código, mas usei a ideia do primeiro comentario do liobntt
Comment: poste sua resposta em forma de resposta, como se voce estivesse respondendo uma pergunta de uma outra pessoa, pois sua resposta do jeito que está cabe mais como um comentário

Ajuda em Get List (Refatoração Código)


Range of $\sin x_1+\dots +\sin x_n$ constrained to $\cos x_1 +\dots +\cos x_n = c$

Question: I've recently come up with the following problem and have no clue how to approach it:
Let $f,g : \mathbb R^n \to \mathbb R$ with $f(x_1, \dots, x_n) = \sin x_1+\dots +\sin x_n$ and $g(x_1, \dots, x_n) = \cos x_1 +\dots +\cos x_n$.
Then for all $a,b \in [-n,n]$, there exists $\vec{x} = (x_1,\dots,x_n) \in \mathbb R^n$ such that $f(\vec{x}) = a$ and $g(\vec{x}) = b$.
Comment: There is no way it's true as stated:  If $f(\vec{x}) = n$, then $\sin x_i = 1$ for all $i$.  Then $\cos x_i = 0$ for all $i$ so $g(\vec{x}) = 0$.  In particular, if $a = n$, then $b$ must be $0$.  For the question in your title, I don't have time to work on it, but I'd start with Lagrange multipliers.  If you can find the max and min, you find the range since the range must be connected.  (I'm not sure Lagrange multipliers would work, but it is where I'd start.)
Answer: In fact, a necessary  condition is $a^2 + b^2 \le n^2$, obtained by applying the triangle inequality to $$\exp(i x_1) + \ldots \exp(i x_n) = a + i b$$  This is sufficient in the case $n \ge 2$ (it's obviously not if $n=1$).


Mask Jquery erro ao digitar uma letra

Question: Estou com o seguinte problema estou usando por exemplo o código de mask
 $(document).ready(function(){
 $('.cpf').mask('999.999.999-99');
 });

perfeito ele funciona e aceita só números, porém se eu aperar qualquer letra ele põe no input o ..- que são os caracteres da mascara, e não queria que nada fosse adicionado quando aperto qualquer letra.
Comment: Você quer que apareça apenas os números?
Comment: isso, na verdade se eu digitar só os números a mascara funciona perfeitamente, mas se eu digitar por exemplo a letra A no input aparece o ..-   que seria a mascara sem os numeros
Answer: É só verificar se a tecla pressionada é um número. Você pode usar a função isNaN() em um evento keydown para retornar false caso a tecla não seja numérica. Além disso, criei uma array com os códigos de algumas teclas de controle para que as mesmas não caiam no if, ou seja, para que elas funcionem no campo, já que não são numéricas, mas são úteis para controlar o cursor e seleção caso necessário:

$(document).ready(function(){

   var teclas = [
      8,    // backspace
      16,   // shift
      17,   // ctrl
      35,   // end
      36,   // home
      37,   // ←
      39,   // →
      46,   // delete
      13    // enter
   ];

   $('.cpf').mask('999.999.999-99').on("keydown", function(e){

      var key = e.key; // pega o valor da tecla
      var keycode = e.keyCode || e.which; // pega o código da tecla

      if(isNaN(key) && !~teclas.indexOf(keycode)) return false;

   });
});

<input class="cpf">

Resumindo, se a tecla pressionada não tiver um valor numérico e seu código não estiver na array, não irá surtir efeito no campo.
Comment: ficou perfeitoooooooooooooooo muito obrigado
Comment: blz... só fiz uma correção: a array `teclas` fora do evento.
Comment: agradeço mesmo amigo

Mask Jquery erro ao digitar uma letra


Unable to load internal .js files on webserver

Question: I am trying to load the highstocks files on my webserver, and when i use

It works completely fine, but on my server I try to load

And it dosent work, when I inspect the site (which you can look at: weather.wesleyweisenberger.com) the link points to the correct file, yet it does not load highcharts.
I have used chown -R and chmod -R 755 on the highstocks folder, yet I cannot load the file into the website. I have had similar issues with trying to load materialize or jQuery.
Help would be Appreaciated.
Answer: The order of imports matter in your case. You need to add the highstock import line before the export js lines, like below

Because exporting.js requires highstock.js, and the order is incorrect only when you add from local like below,

Comment: I don't actually require the exporting.js or the export-data.js anymore, but even with them removed I cannot import highstock.js
Comment: Now there is an error in line 102 : color: Highcharts.getOptions().colors[0]
You need to find some other way to provide color, because Highcharts.getOptions() does not have color defined. Fix it and there should be progress
Comment: Got it! I ended up loading highstocks/highstock.js rather than highstocks/js/highstock.js because it gave me a black screen, do you know why this is?
Comment: You included styled version of Highcharts (`js/something.js`). From docs: https://www.highcharts.com/docs/chart-design-and-style/style-by-css : `In these files, most presentational code is removed, so without styling it will draw an ugly black-and-white chart if anything.`


C++: Can thread race conditions corrupt static/global integer values on a per-byte level?

Question: Let's say I have two threads that randomly increment or decrement from a static int variable in the global scope. My program is not concerned with the exact value of this variable, only whether it is generally increasing or decreasing over-time.
Though I have written some assembly code during college, I am not familiar with how CPUs deal with multithreading and communicate between cores. Is there any chance that two simultaneous writes can corrupt a global variable on a per-byte level? Or are reads and writes to memory (e.g. move, load, store) always atomic?
I use Visual Studio 2022 and C++17, and am hoping to target all modern desktop CPUs (intel, AMD).
Comment: Undefined behavior means anything can happen.
Comment: C++ is not a glorified assembler. If you have a data race, you have undefined behaviour. If you have undefined behaviour, your program will explode in your face.
Comment: When dabbling in undefined behavior, it's not only the hardware you have to worry about, but also the compiler's optimizer.  The optimizer can and will take advantage of the fact that undefined behavior is forbidden to make optimizations that assume that undefined behavior doesn't ever occur… which means that if undefined behavior does occur, you are likely to see your program exhibit "interesting" behavior you wouldn't expect  just from reading the c++ source.
Comment: Does this mean that you cannot implement a mutex using a simple global integer or boolean value?
Comment: @MichaelSohnen *Does this mean that you cannot implement a mutex using a simple global integer or boolean value?* You need to use the operating system primitives for this.  A mere `bool` is insufficient.  Fortunately, C++11 and beyond has wrapped this into the language itself, using `std::mutex`, `std::atomic`, etc.
Comment: Also, [read about the as-if rule](https://stackoverflow.com/questions/15718262/what-exactly-is-the-as-if-rule).
Comment: @PaulMcKenzie Thank you for the clarification. I had some success with std::mutex, but I could not get my program to work reliably. I reverted my code to single-threaded and am going to learn more about thread synchronization before coming back to it.
Comment: You might appreciate some of the examples over at https://stackoverflow.com/questions/71866535/which-types-on-a-64-bit-computer-are-naturally-atomic-in-gnu-c-and-gnu-c-mea, especially the last one in which trying to use `bool` as a semaphore could yield impossible results.
Comment: The rule on x86-64, at the level of assembly, is that a single load or store instruction of up to 64 bits, if naturally aligned, is atomic.  But at the level of C++, there is no guarantee that for instance `bool flag; tmp = flag;` will actually *execute* a single load instruction. As Jeremy Friesner says, the compiler is entitled to optimize it in "interesting" ways that may completely break in the presence of concurrent access.  The idea is that if you can't accept such optimizations then you use `std::atomic`.
Answer: The CPU is the least of your problems here. C++ states that any of these interactions represents undefined behavior. As such, consider the following code:
int i; //Global variable.

void some_func()
{
  i = 5;

  if(i > 5)
  {
    //A
  }
}

The compiler can see all of the code between assigning to i and checking its value. It can see that there is no inter-thread synchronization between these two operations. Because the C++ standard states that any modifications to i from another thread under these circumstances yield undefined behavior, the compiler is free to assume that such modifications do not happen.
Therefore, the compiler knows that i will never be greater than 5 at this point and therefore may remove the block "A" and conditional test, not even emitting assembly that could be executed.
That is what "undefined behavior" means.
If you want to play around with things like that, if you want to actually use the behavior of your CPU/cache/etc in such scenarios, you're going to need to operate in a lower-level language. And for what it's worth, the C standard has more-or-less the same wording, so C ain't it.
So long as you are working in C or C++, the question you are asking is fundamentally unanswerable.


Node reference: Select an exisiting node, or create a new one

Question: I am using Drupal 7, with the References module installed.
I was wondering if there is a way (or perhaps another module) so I can select an existing node from the list or create a new one on the fly (ajax or non ajax)?
So for example I have a button for create new node and automatically select the new node as a reference?
I'd like to have the node reference as a LIST only, not auto complete.
Answer: Try the Node Reference Create Module.
Comment: Thank you but that modules doesn't work on drop down menues
Answer: I do not believe there is an existing module recipe that does everything you describe. You could combine the standard node reference list selector with the Node Reference URL Widget module to meet your requirements.  NodeReference_url expects the referencing nid as a parameter in the URL, so you could add a hyperlink through a module or theme template to render anywhere (next to the standard list or add an extra choice "Add New" to the list with a JQuery onChange).  Node Reference URL lets you set a return page to the "Previous page" when editing the node reference field admin/structure/types/manage/[your content type]/fields/field_[your field] for a smooth round trip.
I realize this is not an AJAX solution, but these pieces could be converted to such in a custom module and might get you started.
Out of the box, Node Reference Create is as close as you can get I'm afraid.
Answer: Check out References dialog also. The module extends reference fields like the user, entity and node reference fields by adding links to add, edit and search for references through a dialog.


combinatorics and divisibilty

Question: in how many ways we can form a $8$ digit numbers from $1,2,3,4,5$ with repetition allowed & divisible by $8$.
MY APPROACH :
to be divisible by 8 : last 3 digit of the no. must be divisible by 8 like $152 , 112$(as repetition allowed),.......[ let total no. of these 3 digit numbers are x ]
then total ways of other 5 diigit = 5^5
now for each way of first 5^5 combinations there will be further x combination for last three
so it becomes (5^5) $*$ (x^5)
is it correct???i dont think it is correct???how to solve it???
Comment: You need to figure out what $x$ is. Then you have $5^5$ choices for the first 5 digits, and $x$ choices for the last three, so your total is $5^5\cdot x$.
Comment: is there aby quick method to find x???
Comment: is 5^5 * x correct answer???
Comment: Yes, I just said that. To find $x$, first note that the last digit must be a 2 or a 4. Then you can exhaust the 50 choices that remain pretty easily.
Comment: @RitabrataGautam: Do you mean that for a number (with more than 3 digits) in general to be divisible by $8$ its last three digits must add to a multiple of $8$? How about 144; 1+4+4=9?
Comment: @user99680 Not what he meant. For a number to be divisible by $8$ the last $3$ digits have to be divisible by $8$ like $98123892112$. Since $112 = 8\cdot 14$, $98123892112$ is divisible by $8$.
Comment: @JohnHabert: right; sorry for my nonsense, let me get some caffeine...
Comment: @user99680 Perfectly understandable.
Answer: A number is divisible by $ 8 $ if the last three digits are divisible by $ 8$.
Now, we can arrange the first $5$ digits of our answer in $ 5^5 $ ways, because each of the position can take $ 1$ of $5$ values.
Now, our problem reduces to the following.
How many three digit numbers formed with $\{1,2,3,4,5\}$ are divisible by $8$?
We can enumerate all the possibilities, preferably in a programming language. In Python,
acc = 0
for x in range(1,6):
    for y in range(1,6):
        for z in range(1,6):
             if int(str(x)+str(y)+str(z))%8 == 0: acc += 1

print acc

This yields an output of $ 13 $. The favourable numbers are
112
144
152
224
232
312
344
352
424
432
512
544
552

Thus, since the last three digits can take any of these $ 13 $ values, and the first five digits can take $ 5^5 $ values, our final answer is $ 5^5 \times 13 = \boxed{40625} $
Answer: Of all the numbers that are formed with 1,2,3,4,5 - the last three digits need to be divisible
by 8.  There are 5^3 ways you could arrange the five numbers for the last three digits.  Of
these last three digits that are divisible by 8 are 312, 152, 512, 432, 352, 112, 232, 224,
144, 424, 344, 552, 544.  A total of 13 of them which I got by brute force in EXCEL by writing
a small program.  Divisibility by 8 is the screwist one.
With these as the last three digits with the first five from {1,2,3,4,5}.  The total number of ways then will be $13*5^5$
The answer is $13*5^5$

combinatorics and divisibilty


Image copying to pasteboard in ios

Question: I am having an app in which I want to copy an image and paste it in the sms app.
I am using the below code.
<code>- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Heritage" ofType:@"png"];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    [pasteboard setData:data forPasteboardType:@"public.png"];

}
</code>
I have got this code after searching on google and there are lots of code but somehow none of them seems to work for me.
When I run the app and go to sms app and press, the paste option doesn't show me there.
Heritage.png is an image in my app's bundle.
Where am I doing any mistake?
Please let me know.
Thanks...
Answer: Finally, I got a solution of my own.
I didn't enable the keyboard extension to allow full access.
Just forgot to set "RequestOpenAccess" to "YES".

Hope someone else does not forget to check this small things.
Thanks...

Image copying to pasteboard in ios


Running out of fretboard

Question: I was wondering, how often does it happen to "run out of fretboard" like Tommy Emmanuel (almost) does in this video around 0:30 ? Do you ever feel limited by the range of the guitar while improvising ?
Comment: Thanks for the brilliant link! They had already changed the key from its more usual Am/C into Em/G, probably to be able to get the high notes in. It's often an option used to accommodate the range of a particular instrument.
Comment: Note that the available fretted notes and the range of the guitar are two different things. Cf. Duane Allman's slide solo before the piano breakdown in *Layla*.
Answer: I "run out of fretboard" very frequently on guitar, but not while improvising, and not at the high end. When writing, I often wish I could play lower on the guitar.
I also play piano/keyboards and bass, and I like to be able to have a good low-end as a foundation in music that I write. On piano I can have it all, more or less, but even then I don't spend a lot of time playing the highest octaves on piano, but I do play down in the lowest octaves frequently.
Most of the time, I don't much care for the sound of the very highest notes on a guitar, so I'm not motivated to go above the 15th or 17th fret on the high E string in most cases.
Comment: Have you tried baritone and seven string guitars (which aren't a new idea, I bought one in Russia in the '60s)
Comment: That was one of  the reasons I changed to 5 string bass many years ago! However, I did pose a question about using a 4 string with BEAD tuning (and obviously thicker strings!). I did the change over a couple of years ago, and the result is great. Did it with a Bass Collection SGC Nanyo - my favourite bass guitar maker - and it also stops people from borrowing it on gigs! Incidentally, there are two distinct string spacings on 5ers - all 5 in the space of normal 4, or, my preference, 5, normally spaced out.
Comment: @Tim No, but I can just barely get my hands around a standard Fender or Gibson neck, so seven strings have never interested me. Regarding baritone, the issue isn't so much what the lowest note is per se (despite what I wrote in my answer), but that I *always want a lower note*. When I'm playing bass, I wish I had a five string, even though I'm an entire octave below the lowest note on guitar. When I'm playing piano, I want another octave on the bottom. It's only synthesizers that I can make go so low that I find the sound to be useless.
Comment: I do loves me some Whammy pedal doubling an octave below, though.
Comment: @Tim I'm suprised that bass players would be so put off by BEAD tuning that they wouldn't want to borrow it, but I suppose if a bass player said "BEAD? I can't do that" to me I would be relieved that they will not be exercising their inability to just move everything up one string on one of my instruments. And now I might have to go look at string sets and switch to BEAD because that sounds like a way to not "have" to buy a 5-string.
Comment: You could always take my idea and use thicker strings on a standard guitar - preferably a longer scale instrument - so it's a 6 string, but B-B. That's not far off a baritone. As used by Duane Eddy, The Eagles, etc. I guess .060 would be a good bottom. On the piano, it's got to be a Bosendorfer with that 'secret' octave in a box on the left!
Comment: I love my 7 string guitars for this exact reason - easy to go down to an A or lower :-)
Answer: To avoid running out of fretboard it is useful to be comfortable with a number of different scales and know how to play "beyond fret 0" when doing scales focused on a barre chord position/chord shape.
But then practising scales is not a popular occupation...
Comment: I'm struggling to understand how this answers the question.
Answer: I run out of fretboard frequently when I play solos on my acoustic guitar because I want to play very high pitches at points in the solo.

Running out of fretboard


How to validation of input text field in ajax?

Question: My javascript code is like this :
$.ajax({
    url:base_url+"agent_control/manage_booking/get_pax",
    type: "post",
    data: {id: id},
    success:function(data) {
        App.unblockUI();
        var code = JSON.parse(data);
        var isitable;
        var j;
        for(var i = 0; i < code.length; i++) {
            j = i + 1;
            isitable += '
';
            isitable += ''+code[i].transactionpax_title+' '+code[i].transactionpax_firstname+' '+code[i].transactionpax_lastname+'	';
            isitable += '<input type="text" id="tiket_number_'+i+'" class="form-control required" />	';
            isitable += '
';
        }
        isitable += '
 	<input type="button" value="Submit" class="btn blue dropdown-toggle submit_tiket_number" id="'+id+'" data="'+code.length+'" />
';
        $("#data_tiket_number").find("tbody").html(isitable);
        $('#data_tiket_number').modal('show');
    }
});

Look here : <input type="text" id="tiket_number_'+i+'" class="form-control required" />
I had add required in text input. But it's not working
If the text input is empty, when I click submit there was no message required
Any solution to solve my problem?
Thank you very much
Comment: In which sense does this not work?
Comment: If you have some event handlers for `input.required`  then I suggest you that  you use proper event delegation. like `$(document).on('event', 'input.required', function(){});`
Comment: @RejithRKrishnan, In my opinion, it does not work because the text input in ajax
Comment: instead of ``, use `` to use the native browser validation
Comment: @mosestoh is this table part of a ``..? If so, did you try mylee's suggestion..? Make sure your document id HTML5
Comment: @mosestoh Has it been solved?
Answer: You have to do three things:

make sure you have form around your table
move required out of the class
change your button type from button to submit

Check demo - Fiddle
for(var i = 0; i < code.length; i++) {
    j = i + 1;
    isitable += '
';
    isitable += ''+code[i].transactionpax_title+' '+code[i].transactionpax_firstname+' '+code[i].transactionpax_lastname+'	';
    isitable += '<input type="text" id="tiket_number_'+i+'" class="form-control" required/>	';
    isitable += '
';
}
isitable += '
 	<input type="submit" value="Submit" class="btn blue dropdown-toggle submit_tiket_number" id="'+id+'" data="'+code.length+'" />
';

Comment: I can't see this question
Comment: http://stackoverflow.com/questions/36126170/how-to-implement-redis-in-codeigniter
Comment: It is okay. Thank you
Comment: I need you help. Look here : http://stackoverflow.com/questions/38175735/how-to-get-data-in-function-extend-controller


Check convergence of an improper Integral

Question: Check for convergence and absolut convergence.
$$
\int_{0}^{\infty}{\sin^{n}\left(x\right)\over  x}\,\mathrm{d}x
$$
I know how to do it if $n = 1$ but i dont understand the integration by parts of $\sin^{n}\left(x\right)$, same goes for absolut convergence i cant find something for the direct comparison test of $\sin^{n}\left(x\right)$, I used the harmonic sequence for $n = 1$.
Thanks for Tips and Help
Answer: Some hints.
For $n=2m+1$, you can use that
$$(\sin(x))^{2m+1}=\sin(x) (1-\cos(x)^2)^m=\sum a_j\sin(x)(\cos(x))^j$$
(the $a_j$ are some constants) and then show that the integrals $\int_0^{+\infty}\frac{\sin(x)\cos(x)^j}{x} dx$ are convergent (use integration by parts, a primitive of $\sin(x)\cos(x)^j$ is $\frac{1}{j+1}(1-\cos(x)^{j+1})$), this show that for $n$ odd, the integral is convergent. For $n $ even, as we have $|\sin(x)|^{n}=(\sin(x))^n$, the integral is divergent, as they are all not absolutely convergent: use that
$$\int_{k\pi}^{(k+1)\pi}\frac{|\sin(x)|^n}{x}dx=\int_0^{\pi}\frac{|\sin(u)|^n}{u+k\pi} du \geq \int _0^{\pi}\frac{|\sin(u)|^n}{\pi+k\pi} du=\frac{c}{k+1}$$
Comment: Thanks for the Hints i was able to show the convergence for odd numbers with ur hint, but im a bit confused why do I not just show the convergence for 2m (even numbers) and use ur last inequality for the absolut convergence.
Comment: For $n=2m$, you have $(\sin(x))^{2m}=|\sin(x)|^{2m}$. So absolut convergence and convergence are the same.
Comment: thanks. Last question.. Can i show the absoult convergence for odd numbers with the same trick that u used in the bounderies? I just need to change the bounderies but the rest should stay the same right?
Comment: I do not understand your question. Your integrals are never absolutely convergent.
Comment: Yes but to proof that it really is never absolutely convergence i need to show it for odd numbers too?  I can't see why it should be enough only showing it for even numbers or do I misunderstand something?
Comment: See the last line of my answer. It is valid for all $n$, odd or even.


What functions can be used to dilate a probability distribution function?

Question: Convolving any distribution $p(x)$ by a $\delta(t-\tau)$ will horizontally shift the distribution by $\tau$. What mathematical operation can I perform on $p(x)$ that will horizontally dilate it (i.e., I want to generate some function $g(x)$ where $g(3x)=p(x)$). In my specific case, I'm working with probability distribution functions that I want to horizontally dilate by some constant.
New here, so please let me know if I should've asked the above question in a different way! Thanks!
Edit:
I mean probability density. To be more clear, I'm looking for a function that can be applied to p(x) directly instead of through substitution (i.e., $p(x) ?h(x)=g(x))$, where ? is some operator and $h(x)$ is some function/distribution. In the shifting example above, the delta function would be h(x).
Comment: Is $p(x)$ a probability density or a cumulative distribution function?
Answer: I'm assuming you meant probability density.
You know that
$$
\int_{-\infty}^{\infty}p(x)dx=1.
$$
Using the substitution rule with $x=3y$,
$$
\int_{-\infty}^{\infty}3p(3y)dy=1.
$$
So your "dilated" probability density is $y\mapsto3p(3y)$.
Comment: Yes, I mean probability density. To be more clear, I'm looking for a function that can be applied to p(x) directly instead of through substitution (i.e., $p(x) ?h(x)=g(x))$, where ? is some operator and $h(x)$ is some function/distribution. In the shifting example above, the delta function would be h(x).
Comment: Technically, $G$ defined by $(Gp)(y) = 3p(3y)$ is an operator... ;-)
Comment: You should narrow down your problem though, as it stands, it's too broad. Maybe pick a specific operator (e.g., multiplication).
Comment: Hmm I see. I've been thinking about mostly convolution or multiplication. In your example above you still don't derive an h(x) for $p(x)?h(x)=g(x)$. I'd like a form where I have both an operator (multiplication or convolution, ideally) and a function that does the transformation h(x).


DateTime.Now não Atualiza se a hora mudar

Question: Tenho em aplicação com um timer em execução, tendo um interval de 1000ms. Esse timer faz algumas rotinas a cada X tempo, e dentre estas rotinas a hora do cliente é muito importante. já percebemos que em alguns casos a hora do cliente que aparece no relógio no canto da tela está certo, mas na aplicação vem com uma hora a menos pelo fato do fuso horário dele estar errado.
Feito os ajustes no S.O. do cliente, a minha aplicação ainda continua capturando a data/hora errada(com o fuso horário errado).
linha de código que estou usando:
<code> Dim horariostatus As String = Format(System.DateTime.Now, "yyyy-MM-dd")
 horariostatus &= " " & Format(System.DateTime.UtcNow, "HH:mm:ss")
</code>
OBS: Sim, eu estou armazenando em uma String por depois esta informação tem algumas tratativas antes de enviar para nosso servidor;
Comment: a sua aplicação é executada no cliente?
Comment: @RicardoPontual sim, a aplicação é executada no cliente;
Answer: <code> Dim current As TimeZoneInfo = TimeZoneInfo.Local //Pega Time Zone do Local da Execução do programa
 Dim horaDestino As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time") //Selecionamos a região da data e hora que desejamos gravar
 Dim horaAtual As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(current.Id) //Selecona o Time Zone para fazer a alteração
 Dim horaConvertida as DateTime //Variável que vai receber a data e a hora convertida

 horaConvertida = TimeZoneInfo.ConvertTime(Now, horaAtual, horaDestino) //Converte para o horário do servidor aqui no caso como horário de Brasília
</code>


Javascript: go to error page when any variable is undefined or null

Question: I want to redirect to error page in the application , when any of the variable in the whole app is undefined or null.
Instead of crashing app, I want to redirect to error page.
Any help would be great.
Thank You.
Comment: Would you please provide your code and trials?
Answer: wrap your code in Try catch statement
try{
    var a = undefined;
    var b = a.length;
} catch(ex) {
    console.log(ex);
    //redirect to your error page
}

Answer: First of all, having a variable with a value of undefined or null is not necessarily an error. If in your case you consider it to be an error, you have two options in my opinion:
Use TypeScript and try-catch block
TypeScript does all the type-checking for you, and if you were careful with defining all the types correctly, an exception should be thrown when any of them becomes null or undefined, where you can then catch it inside a try-catch and redirect the user to the error page.
try {
  ...
} catch (Exception ex) {
  window.location.href = "https://www.example.com/error";
}

Continuously check for values
If you are not into using TypeScript, you can do the checking manually, either every time interval:
setInterval(checkAllValues(), 1000)

or upon certain operations that you suspect it might yield null or undefined.
let myValue = doSomeOperations();
if (myValue === undefined || myValue === null) {
  window.location.href = "https://www.example.com/error";
}

This solution might not very practical, as it requires you to know all the variables and might need to keep a centralised store for keeping them, but it should work fine for simple projects.


Chatting on three or four computers via LAN cables

Question: I have made a chat App using node.js and Soket.Io. To use my chat App you just enter your name and then you can start chatting. I can chat by two names in differrent browser of my computer. Now I want to connect three-four computers of my friends via LAN-CABLES and then use this chat App to chat. Can someone help me how to do this? How to carry out this whole process?
Comment: The same way you do in the two browsers just instead of localhost you use the ip of the computer running the node.js app (just make sure your firewall is not blocking it)
Comment: They also need to be connected to a switch, hub or router with appropriate IP addresses.
Answer: try to give the ip address of Lan to your friends,and when they put in the browser.it works.For that just need small networking..


Can the I IV V chords harmonize any major scale melody?

Question: Are the primary chords of the major scale (I IV V) enough to make any major scale melody sound good? These chords together seem to encompass all 7 notes of the key.
I ask this because as I'm learning songs I know in different keys I'd rather just focus on these three chords for now. I'm just playing by ear, and so far I find this to be true. But I want to check with other musicians.
I'm talking about the major scale as I found minor to be a bit different.
Comment: If you're *learning* all those songs in new keys, it's pretty counter-productive to only use I, IV and V. The point being, you'll eventually have to *re-learn* them to get them right. Either *only* play songs with those three chords, or go a bit further and put in the other three chords, which is probably what they'll have extra. Bear in mind that, put simply, the other three chords are the relative minors of I, IV and V in the same key. C/Am, F/Dm and G/Em.in key C.
Comment: Any note _can_ sound good above any chord.
Comment: Just moving from 3 to 4 chords in your base alone will massively increase the amount of pieces you can play, which makes me wonder whether you're solving the wrong problem.
Answer: A melody diatonic to the key can be accompanied with just I, IV and V chords, but this will give a less rich harmonization than using a wider variety of chords. But based on your question, you want to keep things simple.
That being said, do not feel you must match one of these chords to every single note of the melody. Using a reasonable harmonic rhythm, some of the melody notes, even though they belong to the key, will create a dissonance with the harmonizing chord. Listen carefully so you can harmonize in such a way to resolve these dissonances and make them pleasing.
Comment: "this will give a less rich harmonization than using a wider variety of chords" – "rich" being obviously subjective and relative. For some melodies, **Ⅰ** **Ⅳ** **Ⅴ** are just right and all what's needed, especially if the melody is sometimes dissonant to the harmony and thus already creates extra colour.
Comment: More rich does not equal better, of course. It depends on the piece. But a dessert with more sugar and fat is objectively more rich than a dessert with less, no matter whether or not it tastes good. Musical taste is what is going to decide the right amount of "richness".
Comment: totally agree on dissonant notes. In the beginning, some melody steps can be left un-accompanied. Sometimes it's easier to just play the chords when the melody reaches the right "resting" points.
Answer: Short answer. The short answer is yes: because all 7 scale degrees are represented by one of the chords, it is possible to make a harmonisation that only uses I, IV, and V. This is pretty close to how a typical treatise of music theory starts: start with these harmonies, and add more as need be.
Long answer. The longer answer is no. Although you can string together a progression of I's, IV's, and V's to accompany any melody, this does not necessarily mean that the accompaniment sounds good. This has to do with structural functions that each of the harmonies imply.
Concretely, a typical musical phrase will develop (on the large scale) as I IV V I or a variant thereof (e.g. I ii V I or simply I V I). There might be some other chords in between, but most likely all earlier incarnations of IV and V are in some inversion or otherwise have a weaker structural function. If you arrive on a V, in a lot of situations the only way out is to go to a I afterwards. Similarly, the strongest tendency for IV is to go to V (although back to I is also ok).
This is where other chords start coming in handy: if you move to IV or V too early, your melody is over and has to resolve. But sometimes you want to stretch it a bit longer, and then chords like vii˚, vi, iii, ii, and inversions of all triads become more important.
So what now? The harmonies I, IV, and V are certainly enough to get you started. But as you practise, you will start to notice that you want to do more, and that is probably the right time to add other harmonies to your repertoire.
Comment: @foreyez - Somewhere Over the Rainbow will suffer badly with only three chords.
Comment: @foreyez: so maybe my terminology feels like overkill. However, these songs have the same overarching harmonic frameworks as major works of classical music! But you might be right that the 'simpler' the song, the more likely that I, IV, and V suffice.
Comment: note that the songs I play are mainly children's songs, christmas songs, traditional songs, pop songs. Think silent night, london bridge, amazing grace, my heart will go on, somewhere over the rainbow. stuff like that.
Answer: The I, IV, and V chords will certainly be enough to make a progression that subjectively sounds like it 'works', by most normal people's standards, under any melody that genuinely restricts itself to the major scale. As you say, you have all 7 notes of the key contained within your chord options (which allows any note in the melody to be a chord tone if you wish) and the transitions between all of those chords will sound very standard and subjectively acceptable to most.
As to whether it's possible to always make something that sounds good is more subjective - you might always be able to make something someone would like - but I think you might be in danger of boring yourself by using such a restricted palette of harmony.

I ask this because as I'm learning songs I know in different keys

It sounds a bit strange to be asking about which chords to use if you're learning songs you know. If you're learning songs you know, you (IMO) need to use the chords from the songs, or they won't sound right! You could restrict yourself to songs that do only use I, IV, V chords and play them in different keys though, if that's what you mean - in fact that sounds like a great exercise to me.
Answer: You could accompany a diatonic melody with just I.   Bagpipes and hurdy-gurdys do it all the time.   Going up a notch, yes the 'three chord trick' will enable an accompaniment to a diatonic melody that doesn't sound painful.   But beware.  Many simple songs are not diatonic in one key.  And do you really want to merely avoid sounding dissonant, or do you want the RIGHT chords?   I strongly suggest you move your goal from being able to play ALL songs with just a few chords to learning THIS particular song with the right ones.  Then another...
Comment: I thought most or maybe all bagpipes played pentatonic scales. Am I wrong about that?
Comment: The question is - what are the right chords?  There are so many options. In some cases, it is possible to know what the original composer chose, but in many cases like folk tunes it is whatever you think sounds good. I just wrote a piece based on Shenandoah and harmonized the tune once in minor and once in major. And I have no idea if they were the "intended" chords.  Both sounded lovely, if I might say so myself.
Comment: A Pentatonic scale can be looked at as a Major scale with some notes missing!
Answer: In theory absolutely.  This is basic harmonization theory 100.
However, You have injected a bit of opinion into this question making it a little unfair.  You ask if the harmonization will "sound good".  That's a bit subjective.  The I IV and V are enough to harmonize anything and you do have the inversions each of which have a different harmonic character.
But if you ask me it won't sound "good" until you start putting tri-tone substitutes in there, I IV V, bV, etc.


Batik Swing SVG: Events on Objects in Canvas

Question: I'm looking for a java library to use SVG for work flow presentation.
My question:

is Batik this dynamic that you can move the objects in a svg drawing?
  E.g. moving icons in a canvas. Something like this: moveable
  objects
Answer: Yes, Batik's support for interactivity and scripting is very good. See here, where they say:

The latest revision of Batik, release
  1.7, is a conformant static SVG implementation and supports
  interactivity, linking and scripting
  features of the SVG specification.
  This release supports a nearly
  complete implementation of declarative
  animation, too.

You can see here that they score an A+, and one of the highest overall scores compared to other SVG implementations.
The language (JavaScript) and DOM interfaces are pretty much the same as what you would find in the browser environment as well, making it possible to write very portable UI code that runs well in both contexts.
Comment: Thanks for the info. Do you know any example to see the these features in real?
Comment: I guess I would to realize it with an Interactor. Has anyone an code example for that?


Computing endomorphism ring of finite groups via computer

Question: I'm trying to figure out the structure of endomorphisms of some some rather precise class of finte solvable groups and I'm looking for "the less" expensive way to compute End$(G)$ with some computer system. I've been trying with the GAP function AllHomomorphismsClasses, which gets overwhelmed by the number of generators of the group really soon, so I'm wondering if there is a better way to compute End$(G)$.
One of my tries has been the MAGMA function Homomorphisms, but it seems that it is even slower. A small instance of comparison between the two is the following.
g:=SmallGroup(1458,556);;
h:=AllHomomorphismClasses(g,g);;

in GAP gives me an answer in less than a minute, while
g:=SmallGroup(1458,556);;
g1:=FPGroup(g);;
h:=Homomorphisms(g1,g);;

in MAGMA is running forever (viz. >>1 minute).
So, is there a better way, particularly with MAGMA, that I'm missing?
(I guess I can apply Homomorphisms in MAGMA to a faithful permutation representation of $g$, but I don't think it would improve things that much)
Comment: There are two reasons for that. First, `Homomorphisms` will give you the homomorphisms *up to inner automorphisms*, similarly to GAP's `AllHomomorphismClasses`. Second, much to my personal distaste, the default setting of the parameter `Surjective` is `true`. Using `G := SmallGroup( 6, 1 ); Homomorphisms( FPGroup( G ), G : Surjective := false );` gives 3 homomorphisms instead of just the identity.
Comment: Yes, the only reason I was changing to GrpFP is that the first variable of the function _Homomorphisms_ (which, by the way, seems to act in a strange manner) must be in GrpFP.
Comment: OK, your command does apparently compute the set of all endomorphisms, which I thought it didn't before. (The documentation seems to only talk about abelian groups.) I tested this on a small group and it seemed to work, so the problem is likely that your group is just too big, i.e., has too many normal subgroups. I'm trying your code now
Comment: Incidentally, _Homomorphisms(FPGroup(SmallGroup(6,1)),SmallGroup(6,1))_ seems to give only the identity.
Comment: @sTertooy Wow, that's weird! But true, nevertheless. At the least the function is working, though one cannot use it for reasonably non-small groups, it seems.
Answer: In GAP, AllHomomorphismClasses is (and I'm writing this as the person who wrote the function) a "toy" function that is provided to try small examples in class. (Concretely, Gallian's textbook has exercises about homomorphisms between dihedral groups.) It tries out all possibilities in a backtrack search and thus is likely to be unperformative for groups of order more than a few hundred  that cannot be 2-generated.
What should work substantially better (for groups that are still reasonably small) is to test all subgroups and quotients for isomorphisms. This uses the fact that the isomorphism test performs typically much better than the brute-force image search.
The following function (which takes just a few seconds for the given group) does this:
EndoSeeds:=function(G)
local u,n,e,a,le,q,v,i,j,iso,fingerprint,asAuto,nat,qid;
  fingerprint:=function(sub)
    if Size(sub)<2000 and not Size(sub) in [512,1024] then
      return IdGroup(sub);
    else return Collected(List(ConjugacyClasses(sub),
      x->[Order(Representative(x)),Size(x)]));
    fi;
  end;
  a:=AutomorphismGroup(G);
  u:=List(ConjugacyClassesSubgroups(G),Representative);
  asAuto:=function(sub,hom) return Image(hom,sub);end;
  n:=NormalSubgroups(G);
  n:=List(Orbits(a,n,asAuto),x->x[1]);
  e:=[];
  # go through normal subgroups in deescending order
  SortBy(n,Size);
  n:=Reversed(n);
  for i in n do
    if Size(i)=1 then
      q:=G;
      le:=[IdentityMapping(G)];
    else
      nat:=NaturalHomomorphismByNormalSubgroup(G,i);
      q:=Image(nat);
      qid:=fingerprint(q);
      v:=Filtered(u,x->Size(x)=Size(q) and fingerprint(x)=qid);
      # fuse under automorphisms
      if Length(v)>1 then
        v:=List(Orbits(a,v,asAuto),x->x[1]);
      fi;
      le:=[];
      for j in v do
        iso:=IsomorphismGroups(q,j);
        if iso<>fail then
          Add(le,nat*iso);
        fi;
      od;
    fi;
    Print("Factor order ",Size(q),", ",Length(v)," subgroups, ",
      Length(le)," maps\n");
    Append(e,le);

  od;
  return e;
end;

It returns representatives of homomorphisms $\phi\colon G\to G$, up to the action of $\mbox{Aut}(G)\times\mbox{Aut}(G)$ on kernels and images, as well as the action of $\mbox{Aut}(\mbox{Image}(\phi))$ on the homomorphisms. It should not be hard to expand to the full set of endomorphisms.