How can I get a list of domain names managed by a DNS server?

Question: For example, how can I get a list of domains whose name server is ns1.example.com? If it is not possible to get the complete list, can I get part of the list?
Comment: Various online services give you that, but not for free. How they do it? "Easy". You resolve "all" names, you record the nameservers used, you store the data, and now you can answer queries such as yours. With various limits, like getting really all domains, or the freshness of data. It also depends why you need this data. Registrars can have part of this data from reports done by  registries. But few will expose that to end clients most probably.
Answer: Long story short: unless you have the access to the DNS server configuration files on the ns1.example.com - you can't. There's no technical way to ask the NS "hey, mate, what zones do you serve ?". You can only ask if it serves a certain specific zone.


How does masking work to make neural networks use varying input lengths

Question: A well known solution to make Neural Networks (NNs) work with varying lengths of input data is to use padding and then masking the padded inputs (padded with zero, a common approach in natural language processing). It's being said that this approach makes the NN skip the padded inputs. I want to know what's the mechanism behind such skipping. For me NNs are all about matrix multiplication. So here are my questions:

Is masking done by forcing some weights to zero?
How is it different than simply using the padded values that are
zero without masking (zero times anything is zero again, hence I
suppose the answer to my 1st question should be no, because there is
no point in forcing the weights to zero when the input is zero
itself)
I assume masking didn't suddenly emerge out of thin air, so I want
to know who invented the method? Are there any academic papers
talking about it?
Answer: Masking is not enforcing weights to be zero, masking enforces network inputs and intermediate hidden states to be zero. Setting the inputs to be zero at the begging is not enough; many places in a NN would make the states non-zero.
A typical feed-forward layer with an activation function $\sigma$ is $\sigma(Wx + b)$, and the output will be non-zero because of the bias $b$. When using batch normalization, an estimated mean is subtracted from the activation, which makes it non-zero. Layer normalization has a learned bias term, which also would make the hidden state non-zero.
Masking is, however, only relevant when there is a danger that the invalid mask-out hidden states would influence the network output. This happens, e.g., in Transformers in the self-attention layers: you only want the attention to consider valid positions. This is done by modifying the attention distribution (before normalization) by setting zeros to invalid positions, so it only considers the positions that were part of the input. Hidden states on the invalid position will get some values in the feed-forward layers and during layer normalization, but it does not matter as long as it does not influence the valid states.
Masking invalid input positions is considered a technical detail, and such details are often not discussed in papers. The first time I encountered masking was in 2014 when the original attention paper appeared on arXiv. They released an implementation on Github which did the masking in the attention mechanism, but the paper did not say a word about it.
Comment: Thanks for your explanation. I've seen masking only implemented for Transformers, LSTM and etc. But not for simple Dense layers. I want to make a simple MLP work with missing values in the predictors by simply masking those inputs. Do you know if that's possible?
Comment: In theory, I would say, why not, but I never say anything like this. IMO it would make more sense to make a special value for missing values for categorical features or a flag feature saying that some input values are missing for numerical features.
Comment: Thank you, I made a quick implementation. Could you please check and see whether it is OK? This is the link: https://stats.stackexchange.com/questions/606509/how-to-check-whether-masking-works-ok-in-tensorlow-keras


Error in Exercises from Charles Pinter Abstract Algebra 3.A.3

Question: In Exercise 3.A.3, he asks if $\{x\in \mathbb{R}\mid x \ne -1\}$ with $x*y=x+y+xy$, is an Abelian group, and it follows all needs except that $x*y$ isn't an operation. Since $x\ne-1$, but you can find $y$ such that $x*y=-1$ ($y = \frac{-1-x}{1+x}$), it isn't an operation. Is this correct?
Comment: Did you notice that $\frac{-1-x}{1+x} = -\frac{1+x}{1+x} = -1$?
Answer: This is an operation. Your value for $y$ is
$$y = \frac{-1-x}{1+x} = \frac{-(1+x)}{1+x} = -1,$$
which is not in your set. So in fact, $y$ cannot take that value.


Continuity of a map to a Frechet space

Question: Let $(A,\| \cdot \|)$ be a normed space and $B$ be a Frechet space equipped with a family $\{ p_k \}_{k \in \mathbb{N}}$ of seminorms.
Let $\phi: A \to B$ be a linear transformation satisfying the following: There is a $C > 0$ such that for all $k$
$$ p_k(\phi(u)) \leq C\| u \|.$$
Does it follow that $\phi$ is continuous on $A$? How about uniformly continuous on $A$?
Comment: Do you assume that $\phi$ is linear?
Comment: @Daniel Yeah, sorry forgot that detail. I've edited it now.
Answer: The answers follow from the standard fact that $B$ has the metric $d(x,y) = \sum_{k=1}^\infty c_kp_k(x,y)/[1+p_k(x,y)]$ where $c_k$ is any sequence of scalars such that $\sum c_k < \infty$. E.g. $c_k=1/2^k$.

Continuity of a map to a Frechet space


Are there any easy-to-understand and working tutorials for JBox2D?

Question: I am looking for some beginner tutorials for the newest release of JBox2D. The ones I have found are all outdated. If possible a tutorial on how to apply the whole thing on android would also be good. I am simply trying to make some walls that the player cant go through and apply some gravity.
Thanks in advance.
Answer: you can find JBox2D tutorials for beginners here
Answer: Hмм, the first google result seems useful:
http://www.4feets.com/2009/03/2d-physics-on-android-using-box2d/
However, if you know c++ or actionscript a little, you can successfully use tutorials for these languages. Box2d code in c++ and actionscript is quite similar to Java code.
So you can try to learn these tutorials written in c++:
http://www.kerp.net/box2d/
Answer: If you are trying to learn how to work with the physics engine, please look at the wiki here, specifically at the Testbed page.  The testbed provides everything you need to run the engine so you only have to work with the physics code itself.


TestCafe using client Functions to get data from a HTML dataTable

Question: I am trying to scrape data from a bricklet in the UI(i.e. HTML dataTable) and using a testCafe client function to do this but I haven't been successful. I have a few questions about my code and would like someone to point me in the right direction.
I first put my client function in the test file(test.js) which houses all my other test cases and called the function from one of my tests. Just like this example here: - https://devexpress.github.io/testcafe/documentation/test-api/obtaining-data-from-the-client/examples-of-using-client-functions.html   check section "complex DOM queries"   but testCafe gets stuck, the browser closes but the execution is stuck
Here is my client function. It is in my file that houses all my tests - test.js
fixture`Getting Started`
    .page`${config.baseUrl}`;

    const getTableRowValues = ClientFunction(() => {
        console.log("inside client function");
        const elements = document.querySelector('#bricklet_summary_studtable > tbody').querySelectorAll('tr td');
        const array = [];
        console.log(elements.length);
        for (let i = 0; i <= elements.length; i++) {
            console.log("inside for");
            const customerName  = elements[i].textContent;
                array.push(customerName);
        }
        return array;
 });

Here is my test case:
test('My 4th test - Check the bricklet data matches the expected data', async t => {
    await t.navigateTo('https://myurl.com/app/home/students');
    await page_studTest.click_studentlink();
    await t
        .expect(await page_studTest.exists_ListPageHeader()).ok('do something async', { allowUnawaitedPromise: true })//check the compare button does not exists
    await t        .navigateTo('https://myurl.com/app/home/students/application/stud/id/details/test.html')
    await t
        .expect(await page_studTest.getText_studHeader(t)).eql('student123',
            "the header text does not match");
    let arr = await getTableRowValues();
    await console.log(arr);
});

I thought this will get the values from the UI in an array and I will compare it to another array of test values that I will hard code later.
At first, I tried client functions in my page class(page object model: https://devexpress.github.io/testcafe/documentation/recipes/use-page-model.html) and I put the client function in the constructor and called it from a async function in same page class and called the async function from my test.js. All my tests are structured this way but this only prints the following in the console
Valuesfunction __$$clientFunction$$() {
            const testRun = builder._getTestRun();
            const callsite = (0, _getCallsite.getCallsiteForMethod)(builder.callsiteNames.execution);
            const args = [];

            // OPTIMIZATION: don't leak `arguments` object.
            for (let i = 0; i < arguments.length; i++) args.push(arguments[i]);

            return builder._executeCommand(args, testRun, callsite);
        }

which is not useful to debug the problem.
There are no examples on testCafe site as to how/where to put the client function when you use the page-object model. Could someone, please share some insight? I am interested in knowing the best way to structure my tests.
Comment: I tried adding a testCafe sleep to the end of the test case thinking probably the client function needs time to execute. TestCafe waits for 15 seconds and closes the window after that but the execution is stuck in the console
Answer: I didn't find any problems in your code which can make TestCafe hang. I didn't find any syntax errors or incorrect calls to TestCafe methods either. I only wish that you take note that the await keyword should not be called before console.log. Though this should not lead to any issues.

Probably the use of a custom promise with the { allowUnawaitedPromise: true } option can lead to problems, however it's difficult to determine it without the full project.
I recommend you prepare a simple project with a sample test file to demonstrate the issue and create a separate bug report in the TestCafe repository using the following  form
Comment: Thanks for looking into this one and other Qs regarding testCafe. appreciate your time.
Answer: So, finally I tried to return a promise from my client function and then it worked.
const getTableRowValues = ClientFunction(() => {
    const array = [];
    return new Promise(resolve => {
        var elements = document.querySelectorAll('#bricklet_summary_studtable > tbody > tr > *');
        elements.forEach(function (element, i) {
            let text = element.textContent;
            array[i] = text.trim();
        });
        resolve(array);
    });
});

I resolve a single dimensional array as the assertion wasn't working with a 2D array in the test when I compare the result of the client function to a 2D expected value.However this serves the purpose for now.
Comment: I find this as the most challenging part with most of the javascript frameworks out there( protractor etc). The async behavior of javascript and how to wrap page objects, helper functions( client functions in test cafe) into a promise and structure a code in such a way that the browser object doesn't run ahead of test execution. TestCafe is awesome as it waits for page transitions and assertions. However when complex tests are wirtten, there will be many service calls and DB calls and in depth knowledge of promises/callback is important


Uptime of K8s Service over a period of time - Prometheus?

Question: What is the simplest way to find out the Availability of a K8s service over a period of time, lets say 24h. Should I target a pod or find a way to calculate service reachability
Comment: subsets of pods may be respawned, that does not means service is down.
Comment: @P.... Your correct, how do you suggest to go abou this?
Answer: I'd recommend to not approach it from a binary (is it up or down) but from a "how long does it take to serve requests" perspective. In other words, phrase your availability in terms of SLOs. You can get a very nice automatically generated SLO-based alter rules from PromTools. One concrete example rule from there, showing the PromQL part:
1 - (
 sum(rate(http_request_duration_seconds_bucket{job="prometheus",le="0.10000000000000001",code!~"5.."}[30m]))
 /
 sum(rate(http_request_duration_seconds_count{job="prometheus"}[30m]))
)

Above captures the ratio of how long it took the service to serve non-500 (non-server errors, that is, assumed good responses) in less than 100ms to overall responses over the last 30 min with http_request_duration_seconds being the histogram, capturing the distribution of the requests of your service.
Comment: So if I had only 2 requests within 30min with 1 of them below the threshold, the system will consider it had a 50% uptime. Even though theoretically, system could have fulfilled another 100 requests within the SLO. I'm thinking maybe there has to be a watcher service to generate a continuous load to provide an even measurement throughout the month, especially if there are several indicators (not only HTTP requests durations) which I want to combine sequentially (by multiplying respetive uptimes)


How to get element ID dynamically in javascript

Question: I have a major div which holds a group of divs. when divs inside are selected, I need to get their id in a dynamically way.
I tried a few options but i got Not a number or Undifined.
//HTML

 Sunday

1

 2

 3

 4

 5

//jquery
 $("#Sunday").selectable({
            stop: function () {
                  var result = $("#select-result").empty();
                $(".ui-selected", this).each(function () {
            ***      var index = $("#Sunday DIV").children("Div").prop('id'); - option 1
            ***     var index = $("#Sunday DIV").children("Div").id; -  option 2
            ***     var index = $("#Sunday DIV").children("Div").attr("id") -  option 3
                       result.append(index);
                });}});

Comment: What are you trying to do? You are appending `id` in `#select-result` div. Do you want to append all the ids or all the elements ?
Comment: All the ids, i already got all elements.
Answer: The value of this inside each() will resolve to the element you are interested in, try this:
$(".ui-selected", this).each(function () {
    var id = this.id;
}

Comment: you can use `this.id` as well
Comment: I was on cruise control - you are correct and this is the fastest way to retrieve the `id`
Answer: this will also work
$(".ui-selectee").each(function( index, element ) {
    // element == current element
    var id = $(element).attr("id");
});


Log4j2 - Transaction logging in file and application logging on console

Question: I am developing a logger where certain transaction messages need to be logged to a file and some application logs need to be logged to the console. Currently, the transaction messages are also being logged onto the console and I want to avoid that.
for eg:
if i write logger.info("application process started");
this needs to be logged on console.
and when i write logger.info(new ObjectArrayMessage("msg1","msg2","msg3"));
this need to be logged to a csv file.
This is my current output:
19:18:42.230 [main5] INFO  New.CSVlog.App - application process started
19:18:42.233 [main5] INFO  New.CSVlog.App - [msg1,msg2,msg3]

I want to log only the first log to the console and the second one to the CSV file.
I have the following properties file:
appenders = csvFile, console

appender.csvFile.type = RollingFile
appender.csvFile.name = CSVFILE
appender.csvFile.fileName = csvLog.csv
appender.csvFile.filePattern= csvLog-%d{MM-dd-yyyy}-%i.csv
appender.csvFile.layout.type = CsvParameterLayout
appender.csvFile.layout.delimiter = ,
appender.csvFile.layout.header = column1,column2,column3\n
appender.csvFile.policies.type = Policies
appender.csvFile.policies.time.type = TimeBasedTriggeringPolicy
appender.csvFile.policies.time.interval = 1
appender.csvFile.policies.time.modulate = true
appender.csvFile.policies.size.type = SizeBasedTriggeringPolicy
appender.csvFile.policies.size.size=10MB
appender.csvFile.strategy.type = DefaultRolloverStrategy
appender.csvFile.strategy.max = 200

appender.console.type = Console
appender.console.name = consoleLog
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{HH:mm:ss.SSS} [%t5] %-5level %logger{36} - %msg%n

rootLogger.level =debug
rootLogger.appenderRefs = csvFile, consoleLog
rootLogger.appenderRef.csvFile.ref = CSVFILE

rootLogger.appenderRef.console.ref = consoleLog

Can anyone please help me to use the same logger for both transaction and application logging?
and what changes do I need to make in my properties file? Thanks!
Comment: Why do you want to use the same logger instance?
Comment: @cyberbrain client requirements. If i use two different logger instances how to i configure one for file and the other for the console. I am sorry, i am quite new to this.
Comment: i have configured two different loggers for a file and console. But i want to know how to use a single logger for both operations? and is it even possible to do with a single logger instance?
Answer: You can use Filters to seperate ObjectArrayMessage messages from the rest (cf. documentation). Although there is no built-in filter that checks the class of the Message object, you can easily write one:
@Plugin(name = "ObjectArrayMessageFilter", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE)
public class ObjectArrayMessageFilter extends AbstractFilter {

    public static class Builder extends AbstractFilterBuilder<Builder>
            implements org.apache.logging.log4j.core.util.Builder<ObjectArrayMessageFilter> {

        @Override
        public ObjectArrayMessageFilter build() {
            return new ObjectArrayMessageFilter(getOnMatch(), getOnMismatch());
        }
    }

    @PluginBuilderFactory
    public static Builder newBuilder() {
        return new Builder();
    }

    private ObjectArrayMessageFilter(Result onMatch, Result onMismatch) {
        super(onMatch, onMismatch);
    }

    private static Result filter(Object msg) {
        return msg instanceof ObjectArrayMessage ? onMatch : onMismatch;
    }

    @Override
    public Result filter(final LogEvent event) {
        return filter(event.getMessage());
    }

    @Override
    public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
            final Throwable t) {
        return filter(msg);
    }

    @Override
    public Result filter(final Logger logger, final Level level, final Marker marker, final Object msg,
            final Throwable t) {
        return filter(msg);
    }
}

You can then attach the filter to the appenders, so that it is always applied to a given appender:
appender.csvFile.type = RollingFile
...
appender.csvFile.filter.omaf.type = ObjectArrayMessageFilter
appender.csvFile.filter.omaf.onMatch = ACCEPT
appender.csvFile.filter.omaf.onMismatch = DENY
appender.console.type = Console
...
appender.console.filter.omaf.type = ObjectArrayMessageFilter
appender.console.filter.omaf.onMatch = DENY
appender.console.filter.omaf.onMismatch = ACCEPT

Remark: When developing custom plugins, some standard rules apply: cf. documentation. Basically the plugin's code must be compiled with the annotation processor in log4j-core.
Comment: Hey @Piotr, thanks for the answer, I will try to implement the functionality using your code.


Can a player touch the line while the ball is landing - Outdoor Volleyball (Beach or Grass)

Question: Scenario: The ball is heading towards a boundary line and the player is chasing it down.
The player contacts the line boundary line and the line moves at the same time the ball lands. Typical example, they step on the line.
Is the ball in or out (or replay point?)
Answer: For FIVB Beach Volleyball, this is covered by 5.1.5 in the 2022 Casebook:

What should the referee do if a ball landed inside the
line, but obviously the line had been displaced
substantially during a previous defending action?
The 1st Referee should have the line corrected, and
then call the ball "in" or "out", depending on where
the ball landed.

If the 1st Referee is unable to make a clear decision as to whether the ball was in or out, the rally should be replayed as it would for any other situation where the 1st Referee is unsure as to the correct judgement.
This obvious works a lot better on sand where the ball is likely to leave a clear mark than it does on grass; however as there are no professional level tournaments played on grass "nobody cares".


How to monitor Windows server Registry changes

Question: Hi i want tools or audit policy that can help me to track all changes made to windows server registry (include who done the change - what is the old value -what is new value -change type {delete -create - modify)
Your support is highly appreciated
Comment: I Just found few articles regarding monitore registry through WMI    http://stackoverflow.com/questions/144468/tracking-changes-in-windows-registry

http://code.msdn.microsoft.com/windowsdesktop/CSMonitorRegistryChange-d297cdf0

http://social.msdn.microsoft.com/Forums/en-US/65dc039e-3645-4a01-a8fa-7cb373aac36b/using-wmi-to-monitor-registry
Answer: Windows Security Log Event ID 4657 will tell you when someone edits a registry key, so you can look for that in your Event Viewer.  The only caveat to this is that you have to turn on auditing first.  See this to turn on auditing for both domain and workgroup environments.
This is also a link from Microsoft supporting the method from techtarget.com.
Comment: i tried this one but the issue that it will create bulk of events and most of them was for querying key only i need something more specified like editing keys, removing, creating
Comment: You may have to look at a third party tool then, although in my mind I wouldn't want to do that.  The more native tools/functions I can use the better in my mind.


what to do when the multivariable second derivative test is inconclusive?

Question: What do we do when the second derivative test fails? How do we approach it, and is there a general method to further find whether a critical point is a maximum, minimum or a saddle point?
For example, I'm asked to find all the critical points of the function $$f(x,y)=-x^{2012}-y^{2012}$$ and determine the nature of the critical points. The critical point that I have found is at $(0,0)$, but I'm unable to determine its nature as the second derivative test fails here.
Comment: works only for smooth functions: if the first $2n-1$ derivatives are zero and the $2n$-th derivative is negative, then you have a local maximum. (i remember this theorem from first semesters but no idea what book to find it in.)
Answer: You should think geometrically. The function $$f(x,y)=-x^{2012}-y^{2012}$$ can be written $$f(x,y)=-(x^{2012}+y^{2012})$$ But because 2012 is even, $x^{2012}\geq0$ and $y^{2012}\geq 0$. Therefore $x^{2012}+y^{2012}\geq0$ and so $f(x,y)\leq 0$ for all points $(x,y)$. Therefore your critical point $(0,0)$ is a global maximum.
Whoever assigned this problem probably wanted you to notice that your function $f$ is similar to
$$g(x,y)=x^2+y^2$$which is an upward-opening elliptic paraboloid that has a global minimum at the origin. Similarly, $$h(x,y)=-x^2-y^2$$ is a downward-opening elliptic paraboloid that has a global maximum at the origin.
The only difference between these functions and your function $f$ is that $f$ rises much, much faster when $|x|>1$ and $|y|>1$ and is much, much flatter when $|x|<1$ and $|y|<1$, because the exponent is so much higher. In fact, the graph would look more like a box than a paraboloid because the walls of the surface are so steep.
In general, there's no surefire method for analyzing the local behavior of functions where the second derivative test comes back inconclusive. In practice, you should think geometrically or look at higher order derivatives to get a sense of what's going on.
To use the latter approach, consider taking the 2012th partial derivatives of your function. Both the $x$ and $y$ partial at the origin will be $-2012!$, and combining this with the multivariate Taylor expansion (and reflecting on the mixed partials) gives another way of seeing that your function is negative definite near the origin. (The reason the second derivative test fails for this function is that it is too flat near its critical point. This extreme flatness is what makes so many of the higher-order derivatives zero.)
But your function is so simple to understand that its global properties are obvious if you think geometrically. Other functions might require you to think harder about what's happening graphically, in which case the analytic approach with higher derivatives could be helpful.


Approaches to Forecasting with Daily Timeseries

Question: I have just started to learn about forecasting. I thought it would be easy to create forecast models for a daily time series but have encountered a number of difficulties. Firstly most examples and available datasets are either in months or quarters. It is rare to find examples for weeks and days. Secondly it also appears difficult to create a timeseries object for days (365) and weeks (52) as these vary between years. This may just be the way the timeseries object works in R. I have had to use Zoo. I also have a concern that my data may not be properly modeled for use in packages like Forecast and HTS.
I am interested in how best to approach this problem. Any examples of forecasting to daily events that may cycle across years would be greatly appreciated.
Comment: See http://robjhyndman.com/hyndsight/dailydata/
Answer: Daily data is often impacted by 1) day-of-the-week-profiles and changes in these profiles ; 2) week of the year ; 3) Time trends ( note the plural ) ; 4)  Level Shifts ; 5) monthly effects ; 6) particular days of the month E.G. the first,15th etc ; 7) Lead, contemporaneous and lag effects around known events e.g Christmas , JUly4th etc ) ; 8) Unusual values ; 9)Long weekends around events ; 10) particular week in month effects ; ARIMA structure reflecting unspecified stochastic input series
That should be enough to start with.
When you think that your equation deals effectively with the above then start to consider the impact of parmeters that change over time and an error variance that may change over time.
Comment: How do I model these things eg public holidays and weekends as an initial start to try to forecast at the daily level. My data has a seasonal trend that goes for a year, then there is a weekly trend with weekends needed to be zero and public holidays also needing to be zero. The dates for these events are known. I am not sure how to model ARIMA or ETS to take these events into consideration. Do I use xreg? It is very hard to find any useful articles or tutorials on doing this on the web. Any pointers in the correct direction would be appreciated.
Comment: You would start with a model that 6 indicators for the day of the week , 11 indicators for the month of the year , 14-15 indicators reperesenting the major holidays and then either use commercially avialable software like AUTOBOX/SAS/SPSS to detect the specific window of response around each holiday/event, the presence of level shifts and or local time trends , dynamic changes un the day-of-the-week effects , pulse effects , parameter change effects over tome and carinace change effects over time OR spend a lot of time yourself with free tools which don't exist.


Probability generating function of some "random walk"

Question:
Let $S_n=\sum^n_{r=0}X_r$ be a left-continuous random walk on the integers
  with a retaining barrier at zero. More specifically, we assume that
  the $X_r$ are identically distributed integer-valued random variables
  with $X_1\geq -1, \mathbb{P}(X_1=0)\neq 0$, and
$$ S_{n+1} =  \left\{ \begin{matrix} S_n+X_{n+1},\mbox{  if  }
> S_n>0,\\ S_n+X_{n+1}+1,\mbox{  if  } S_n=0. \end{matrix} \right.$$
Show that the distribution of $S_0$ may be chosen in such a way that
  $\mathbb{E}(z^{S_n})=\mathbb{E}(z^{S_0})$ for all $n$, if and only if
  $\mathbb{E}(X_1)<0$, and in this case
$$\mathbb{E}(z^{S_n})=\dfrac{(1-z)\mathbb{E}(X_1)\mathbb{E}(z^{X_1})}{1-\mathbb{E}(z^{X_1})}$$

Attempt
I want to prove the "=>" part:
The probability generating function for $S_n$ and $X_n$ are
$$ \mathbb{E}(z^{S_n}) = \sum^{+\infty}_{i=0} z^i \mathbb{P}(S_n=i)$$
$$ \mathbb{E}(z^{X_1}) = \sum^{+\infty}_{i=-1} z^i \mathbb{P}(X_n=i)$$
We have
\begin{align}
P(S_n=i) &= \sum_{k=1}^{i+1} P(S_n=k)P(X_{n+1}=i-k) + P(S_n=0)P(X_{n+1}=i-1)\\
&= \sum_{k=1}^{i+1} P(S_0=k)P(X_{1}=i-k) + P(S_0=0)P(X_{1}=i-1)\\
&= \sum_{k=0}^{i+1} P(S_0=k)P(X_{1}=i-k) + P(S_0=0)P(X_{1}=i-1) - P(S_0=0)P(X_1=i)\\
\end{align}
for all $i\geq 0$.
Multiply both sides by $z^i$, we have
$$z^i P(S_n=i) = \sum_{k=0}^{i+1} z^k P(S_0=k)z^{i-k}P(X_{1}=i-k) + zP(S_0=0)z^{i-1}P(X_{1}=i-1) - P(S_0=0)z^iP(X_1=i)
$$
Sum both sides over $i\geq 0$, we have
$$
\mathbb{E}(z^{S_0}) = \mathbb{E}(z^{S_0})\mathbb{E}(z^{X_1}) + zP(S_0=0)\mathbb{E}(z^{X_1}) - P(S_0=0)\left(\mathbb{E}(z^{X_1})-\frac{P(X_1=-1)}{z}\right)
$$
Finally we get
$$
\mathbb{E}(z^{S_0}) = \dfrac{\mathbb{E}(z^{X_1})P(S_0=0)(z-1)+P(S_0=0)P(X_1=-1)/z}{1-\mathbb{E}(z^{X_1})}
$$
What's the problem here?
Answer: For simplicity, I will write $q_k$ for $P(S=k)$ and $p_k$ for $P(X=k)$
while dropping the subscripts on $S_0$ and $X_1$.
Your double summation is not quite correct; when you exchange the order
of summation the lower bound should be $i=(k-1)_+$, not $i=k-1$.
This is because $i$ can never be negative. Of course, this only makes
a difference when $k=0$.
The correct simplification  for the double summation  is
$$\sum_{i=0}^\infty \sum_{k=0}^{i+1}z^k q_k  z^{i-k} p_{i-k}=
\sum_{k=0}^\infty z^k q_k \sum_{i=(k-1)_+}^\infty z^{i-k} p_{i-k}=
\mathbb{E}(z^S)\mathbb{E}(z^X)-q_0p_{-1}/z.$$
Plugging this into your otherwise correct expression gives
\begin{eqnarray*}
\mathbb{E}(z^{S}) &=&
 \left[\mathbb{E}(z^{S})\mathbb{E}(z^{X})-q_0p_{-1}/z\right] + z q_0 \mathbb{E}(z^{X})
- q_0 \left(\mathbb{E}(z^{X})-p_{-1}/z\right)\\[8pt]
&=&
 \mathbb{E}(z^{S})\mathbb{E}(z^{X}) + (z-1)q_0\mathbb{E}(z^{X})
\end{eqnarray*}
which leads to
$$\mathbb{E}(z^{S})={(z-1) q_0 \mathbb{E}(z^{X}) \over 1-\mathbb{E}(z^X)}, $$ the same as the given solution.
It is a nice exercise to show that, in this problem, we have
$q_0=-\mathbb{E}(X)$.


Equivariant map in compact homogeneous space is a diffeomorphism

Question: I don't see why an equivariant $G$-map $f: M \rightarrow M$, where $M$ is a compact homogeneous space, is necessarily a difeomorphism. Any idea?
Answer: I just wanted to complement freakish's (perfectly fine) answer with details about smoothness.  To that end, recall that any homogeneous space $M$ is equivariantly diffeomorphic to a coset space $M\cong G/H$, where the $G$ action on $G/H$ is just left multiplication.  I'll use the notation $N_G(H)$ for the normalizer of $H$ in $G$.
Lemma:  Suppose $f:G/H\rightarrow G/H$ is equivariant.  Then there is a $g\in N_G(H)$ for which $f(kH) = kgH$ for all $kH\in G/H$.
Proof:  Choose $g\in G$ with $f(eH) = gH$ (with $e\in G$ the identity).  Then, for any coset $kH$, we have $f(kH) = f(keH) = kf(eH) = kgH$.
To see $g\in N_G(H)$, note that for any $h\in H$, $f(kH) = f(khH)$, which implies that $kg = khg h'$ for some $h'\in H$.  Canceling $k$ and rearranging gives $g^{-1} h^{-1} g \in H$, which then easily implies $g\in N_G(H)$.  $\square$
Now, if $\pi:G\rightarrow G/H$ is the obvious projection and $R_g$ is right multiplication by $g$, it follows that $f\circ \pi = \pi \circ R_g$.  The map $\pi\circ R_g$ is obviously smooth, so $f\circ \pi $.  Because $\pi$ is a submersion, smoothness of $f\circ \pi$ implies smoothness of $f$.  (See this MSE question for a proof of this last statement.)
Finally, to see $f$ is a diffeomorphism, simply note that if $f(kH) = kgH$, then $f^{-1}(kH) = kg^{-1} H$, so it's smooth for the same reason $f$ is.
Comment: Great answer. Just to fill one detail in case someone wonders where compactness matters: otherwise $M$ need not be equivariantly diffeomorphic to $G/H$.
Comment: @freakish:  I typically never think about non-compact Lie groups.  Do you have an example in mind where compactness is important?
Comment: Consider discrete $\mathbb{Z}$ acting on $S^1\subseteq\mathbb{C}$ via $(n,z)\mapsto e^{2\pi i\theta n}\cdot z$ where $\theta$ is irrational, i.e. $\mathbb{Z}$ acts on $S^1$ via irrational rotation. Note that the orbit of say $1$ is an infinite countable dense subset of $S^1$, and so not discrete, unlike any quotient of $\mathbb{Z}$. So these aren't even homeomorphic. However the orbit is not a manifold. Now that I think about it I'm not sure if there is a counterexample when dealing with homogenous manifolds.
Comment: Yeah, when dealing with homogenous manifolds this seems to hold for any Lie group: https://math.stackexchange.com/questions/4187728/exact-requirements-for-stabilizer-orbit-theorem-for-lie-groups
Comment: @freakish:  Thanks for the clarification!
Answer: Partial answer:
So $f(gx)=gf(x)$ for any $g\in G$, $x\in M$. Since $M$ is homogenous this means that $f$ is uniquely determined by a single value on a single element $x_0\in M$, say $y_0=f(x_0)$. Therefore we can construct the inverse $h:M\to M$ by $h(y_0)=x_0$ which uniquely extends to entire $M$ via $h(gy_0):=gh(y_0)$.
And so $f$ is a continuous bijection. Which means it is a homeomorphism since $M$ is compact.
Now you also ask about diffeomorphism so I assume that $M$ is additionally a smooth manifold. Typically smooth homeomorphisms need not be diffeomorphisms. The $x\mapsto x^3$ map is a smooth map that is not a diffeomorphism (the derivative at $0$ is $0$). I think we can turn that example into compact case by considering $[-1,1]$ interval and glueing ends into $S^1$. But this example does not include the action of $G$ on $M$, so I might actually be wrong here.


Find if a procedure is running in another form

Question: I have a form X with the following procedure:
Public Sub PrintUT_Click()

If Forms!frmDisclosure.Command280.Visible = True Then
    Forms!frmDisclosure.GoToLastRecord
End If

RemoveSchma
DoCmd.TransferText acExportMerge, "", "qryUndertaking", conAddrPth &   "\DataSource.txt", True, "", 1252
OpenWordDoc

ExecuteFile "E:\Peter\Desktop\Update Service.pdf", printfile

End Sub

It is called from another form (form Y) from one of two command buttons. If called fom one button I want 'ExecuteFile "E:\Peter\Desktop\Update Service.pdf", printfile' to run. If called from the other button, I don't want 'Exceute...' to run. What 'If... Then' prodecure can I set up in form X to achive this?
Answer: Easiest way is to add a boolean switch as a parameter, moving the routine out of a button event and into it's own sub.
Private Sub Button1()
RoutineNameHere
End Sub

Private Sub Button2()
RoutineNameHere False
End Sub

Public Sub RoutineNameHere(Optional blnExecute as Boolean=True)
If Forms!frmDisclosure.Command280.Visible = True Then
    Forms!frmDisclosure.GoToLastRecord
End If

RemoveSchma
DoCmd.TransferText acExportMerge, "", "qryUndertaking", conAddrPth &   "\DataSource.txt", True, "", 1252
OpenWordDoc

If blnExecute Then
    ExecuteFile "E:\Peter\Desktop\Update Service.pdf", printfile
End If
End Sub


How add tab menu item with external link to article node content

Question: I want to add an extra tab menu item to article node type.
I mean a new menu item beside view, edit and other tabs only in article node.
but this tab menu item has external link to another site and it's target is _blank (to open destination in new window)
what is your solution for my issue?
Comment: I believe with hook_menu and title callback
Answer:
Create custom module  Replace mymdulename with your module name.
implement hook menu to add "Menu local task" which let your menu
item to show along with view, edit ..
page call back to add the
redirect rule, in below example I am redirecting to google.com, you
can add a check according to node and add redirection rule.
access callback ensures this menu tabs gets attached to nodes for article
content type.

/**  * Implements hook_menu().  */
function mymodulename_menu() {
  $items = array();

  $items['node/%node/movies'] = array(
    'title' => 'Movies',
    'page callback' => 'mymodulename_redirect',
    'page arguments' => array('node', 1),
    'access callback' => 'mymodulename_content_type_check',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 100,
  );

  return $items;
}

/**
* Access callback
*/
function mymodulename_content_type_check($node) {
  if ($node->type != 'article') {
    return FALSE;
  }
  return TRUE;
}

function mymodulename_redirect($node) {
  dpm($node);
  $url = "http://www.google.com";
  drupal_goto($url, array('external' => TRUE));
}

Update
to open the external link in new tab use jquery to add '_blank' attribute
in your custom
jQuery('.tabs a').attr("target","_blank");

Remember to pick unique classes instead of ".tab" to avoid having this behaviour to all tabs.


Iterate through a list argument in Lilypond define-scheme-function

Question: I'm trying to write my first define-scheme-function in Lilypond, and I'm stuck. I'm wanting to output a variable number of handbell 'echo' notations within a single measure.
This is working for a static number (2-4):
echoTwoThreeFour = #(define-scheme-function
 (halign)
 (number?)
 #{ \markup { \halign #halign \center-column {⮍ 2} \center-column {⮍ 3} \center-column {⮍ 4} } #}
 )

<c e g c>1 -$(echoTwoThreeFour -3)

This outputs:

However, I'd really like to send as an argument a list of beat numbers (list 2 3 4) so that I can use a single function for variable numbers of echoes, called like:
<c e g c>1 -$(echoVariable (list 2 3 4) -3)
How can I iterate through a list of numbers within a scheme function and output the appropriate markup?
Answer: For example like this. map creates a list of function results for each entry of a list. This can be used to create the individual markups. Then we simply make a line markup from this list of markups.
echoN =
#(define-scheme-function
 (halign iterations)
 ((number? -3) list?)
 (let* ((marks (map (lambda (c) #{ \markup\center-column {⮍ #(number->string c) } #}) iterations))
        (basemup (make-line-markup marks)))
   #{ \markup \halign #halign #marks #}))

{ <c e g c>1 -\echoN #'(1 2 3) }

Edit: But I think you are actually using \halign for the purpose of \hspace. You'd probably want to do
echoN =
#(define-scheme-function
 (space iterations)
 ((number? 3) list?)
 (let ((marks (map (lambda (c) #{ \markup\center-column {⮍ #(number->string c) } #}) iterations)))
   (make-line-markup (cons (make-hspace-markup space) marks))))

Note that this can then also be called with this nice scheme-free syntax
{ <c e g c>1 -\echoN 2 1,2,3 }

Comment: @Mark See here https://lilypond.org/doc/v2.24/Documentation/extending/scheme-function-definitions.html the stuff about optional arguments.
Comment: Thanks, @Lazy! I will try this out. Thanks for the hint on halign vs. hspace. I'm guessing I have lots of such things going on in my first few scores, due to copying/pasting without fully understanding.
Comment: Perhaps someday my eyes will be able to read scheme/lisp without so much effort. Are you missing a parameter in the first snippet `-\echoN #'(1 2 3)`?


Converting to complex form

Question: Write each of the given numbers in the form $a+bi$.
a.) $e^{\frac{-i\pi}{4}}$
b.) ${\frac{e^{1+i3\pi}}{e^{-1+i\pi /2}}}$
c.) $e^{e^i}$
For a, I got $(\frac{\sqrt 2}{2} -\frac{\sqrt 2}{2}i)$, which I think is right. I am stuck on how to do b and c.
Answer: You are right on $a$.
For $(b)$, $$\dfrac{e^{1+3 \pi i}}{e^{-1 + i \pi/2}} = \underbrace{e^{2+ 5 \pi i/2} = e^2 e^{i \pi/2}}_{\text{since }e^{2\pi i+ i \theta} = e^{i \theta}} = e^2 i$$
For $(c)$, note that $e^{i} = \cos(1) + i \sin(1)$.
$$e^{e^i} = e^{\cos(1) + i\sin(1)} = e^{\cos(1)}  e^{i\sin(1)} = e^{\cos(1)}\left(\cos(\sin(1)) + i \sin(\sin(1))\right)$$
Comment: Thanks! I understand how to do c now but I am confused on part b. How did you $e^{2+ 5 \pi i/2} = e^2 e^{i \pi /2}$. I understand how you got $e^{2+ 5 \pi i/2}$ but not $e^2 e^{i \pi/2}$.
Comment: @Q.matin As I mentioned in my post, we have $$e^{2+5 \pi i/2} = e^{2}e^{5 \pi i/2} = \underbrace{e^{2}e^{2 \pi i + \pi i/2} = e^2 e^{i \pi/2}}_{e^{2 \pi i + i \theta} = e^{i \theta}}$$ I used the fact that $$e^{2 \pi i + i \theta} = e^{i \theta}$$ since $e^{2 \pi i} = 1$.
Comment: Oh, so $e^{2 \pi i + \pi i/2}$ is an identity equal to $e^{i\theta}$?
Comment: @Q.matin The main thing is $e^{2 k \pi i} = 1$ when $k$ is an integer and use the fact that $e^{a+b} = e^a \cdot e^b$. Hence, $e^{2 \pi i + i \theta} = e^{2 \pi i} \cdot e^{i \theta} =1 \cdot e^{i \theta} = e^{i \theta}$.

Converting to complex form


SVM importance of predictor variables

Question: I am building a model in R using support vector machine (SVM) with KBF kernel.
The model seems to work quite well. I would like to assess the relative importance of predictor variables.
Can anyone tell me how this can done. Does there exist an R script for that?
Comment: Have a look at this question.
Stackoverflow: SVM equations from e1071 R package?  http://stackoverflow.com/questions/7390173/svm-equations-from-e1071-r-package
Answer: Unfortunately, there is no direct way to get such information with SVMs, in contrast to, for example, logistic regression.
If you want, you can estimate the contribution of a single predictor ad hoc by training a model on all predictors except that specific predictor. The difference in performance between that model and the one with all predictors may then be considered the marginal contribution of that predictor.
If time permits, you can perform this procedure for all predictors.
Comment: Wouldn't the varImp() function work in that case?
Answer: If you use R, the variable importance can be calculated with Importance method in rminer package. This is my sample code:
<code>library(rminer)
M <- fit(y~., data=train, model="svm", kpar=list(sigma=0.10), C=2)
svm.imp <- Importance(M, data=train)
</code>
In detail, refer to the following link https://cran.r-project.org/web/packages/rminer/rminer.pdf
Comment: Can you expand a bit on how it does it as if the link goes dead your answer will become worthless?

SVM importance of predictor variables


mysqlx plugin unreachable on Amazon RDS (MySQL 8.0)

Question: Running local instances okay but have problem connecting to MySQL RDS AWS, not a connectivity issue to RDS private network.

This is the error when attempting to make a connection. ERROR - Unable
to sync database. Connection attempt to the server was aborted.
Timeout of 10000 ms was exceeded.

<code>mysql> SELECT * FROM performance_schema.global_variables WHERE variable_name LIKE 'mysqlx%';
| VARIABLE_NAME | VARIABLE_VALUE |
</code>

+| mysqlx_bind_address | *
+| mysqlx_connect_timeout | 30
+| mysqlx_idle_worker_thread_timeout | 60
+| mysqlx_max_allowed_packet | 1048576
+| mysqlx_max_connections | 100
+| mysqlx_min_worker_threads | 2
+| mysqlx_port | 33060
+| mysqlx_port_open_timeout | 0
and the plugin is active as well, from sql, show plugins shows: mysqlx
| ACTIVE | DAEMON | mysqlx.so | GPL |

Referencing to contributors on this thread.
Basing on this thread.
Does AWS RDS supports MySQL as document store
@ruiquelhas /Mr. Rui Quelhas seems to suggest there is a way to enable RDS running X-protocol based on the current MySQL RDS setup mentioned by others above.
My existing MySql RDS instance shows disablement of mysqlx.

Using MySql Community RDS 8.0.21 version on Node.Js with mysql/xdevapi 8.0.21.
RDS AWS seems to make mysqlx parameters non-modifiable on initiation of the database as shown.

However, they do allow installation of new plugin by using Mysql statement as shown
So we can't do this setting mysqlx=1 in my MySQL configuration file. Large portion of our application is written with mysqlx, hope someone can show us the workaround? Google SQL doesn't support X Plugin.
Answer: Kevin, sorry for the confusion but by the time that answer was written, Amazon RDS was based on a MySQL 5.7.x version, which doesn't come with the X Plugin installed by default. However, it doesn't mean you can't spin up MySQL 8.x and disable the X Plugin altogether, which seems to be the case.
According the Amazon RDS user guide, X Plugin is not supported (that's why it is disabled). If you are looking for an alternative DBaaS, MySQL Database Service on Oracle Cloud is probably the only equivalent alternative that supports it, as far as I can tell.
Disclaimer: I'm the lead developer of the MySQL X DevAPI Connector for Node.js


C - runtime error while printing string(using a pointer)

Question: I have a problem with a simple C program and i need your help.I declare a string, using a pointer.Using scanf I give it a value from stdin.Later I try printing this string.It all compiles well,but when i run the program, it accepts my string,and when it gets to printing, i recieve a run-time error with return value 3221225477.
Where is the problem here?
 I'm using DEV C++ IDE btw.
Note: I also tried doing the same on ideone.com online compiler and it doesn't give a runtime error,but instead of string given in stdin, it prints (null).
 Here is the code:
<code>#include <stdio.h>

int     main(void)
{
    char *string;

    scanf("%s", string);
    printf("Hello,%s !", string);

    return 0;
}
</code>
Comment: 1.) there are no "runtime errors" in C. 2.) `string` isn't initialized and doesn't point to any usable memory, writing there is undefined behavior.
Answer: You need to allocate space for the variable string.
For example:
<code>char *string;
int i;
scanf("%d", &i);
string = (char*)malloc(sizeof(char)*i);
</code>
And then you can read from input and print the string


What is this called?

Question: We have several time series: $Y, X_1, X_2, X_3, ..., X_n$
The steps taken are:

Regress $X_2, X_3, ..., X_n$ on $X_1$ to get residuals of each $X_{(>1)}$
Regress $Y$ on $X_1, r_{X_2}, r_{X_3}, ..., r_{X_n}$ to obtain:

$$
Y = \alpha + (\beta_{X_1} * X_1) + (\beta_{X_2} * r_{X_2}) + (\beta_{X_3} * r_{X_3}) + ... + (\beta_{X_n} * r_{X_n})
$$

The question proposed to me was:

The 2nd step is quite straight forward if you pass in time series for
  the 1st stage. However, if we pass in a variance-covariance matrix in
  the 1st step, how would you proceed to solve 2nd step?

I dont know how to begin approaching this question because I am not sure what this technique, (regressing against one factor and the residuals from step 1) is called.
Can anyone answer the question proposed to me, or at least tell me what this is called so I can desperately attempt to figure it out myself?

The concept behind this is that $Y$ is a portfolio of securities that I am attempting to analyze the risk of. The end equation represents a risk function where $X_1$ represents the returns of the overall stock market and $X_{2...n}$ represents the returns of sectors within the market (ex. Technology, Utilities, Consumer Discretionary ... etc.)
Comment: This appears to be a version of "linear matching" as explained at http://stats.stackexchange.com/a/46508/919.
Comment: Could you tell me how to answer the question proposed to me?

_"The 2nd step is quite straight forward if you pass in time series for the 1st stage. However, if we pass in a variance-covariance matrix in the 1st step, how would you proceed to solve 2nd step?"_

@whuber
Answer: assume you have just three time series $Y,X_1,X_2$ then the model is
\begin{align}
Y&=\beta_1X_1+\beta_2 (X_2-a_1X_1)+\beta_3(X_3-a_2X_1)\\
&=X_1(\beta_1-\beta_2a_1-\beta_3a_2)+\beta_2X_2+\beta_3X_3\\
&=X_1\tilde\beta_1+\beta_2X_2+\beta_3X_3
\end{align}
That is not more that a linear model (for simplicity I assumed variables are centered).
If I understand your model well, that is a simple linear model that needs just one step to estimate parameters.  Then proposing a two step optimization procedure is not necessary.
Comment: So how do you suggest I answer, "_The 2nd step is quite straight forward if you pass in time series for the 1st stage. However, if we pass in a variance-covariance matrix in the 1st step, how would you proceed to solve 2nd step?_"

What is this called?


Por quê quando utilizo método save do spring boot ele altera a persistência do dado em vários lugares?

Question: Fala pessoal, tudo bem?
No meu contexto, preciso fazer um método desfazer, dessa fora utilizando um objeto de array que salva na memória meu último dado persintência do banco e, quando salvo esse dado no array e chamo o método save (do SpringBoot do JPA), com o novo dado alterado no banco, esse método save, altera a persistência dentro do array.
public ResponseEntity putLoja(@Valid @RequestBody Loja atualizaLoja, @PathVariable int idLoja) {
        if (lojaRepository.existsById(idLoja)) {
            atualizaLoja.setId(idLoja);
            lojaRepository.save(atualizaLoja);
            pilhaLojaAuxiliar.push(lojaRepository.findById(idLoja).get());
            return ResponseEntity.status(200).build();
        } else {
            return ResponseEntity.status(400).build();
        }
    }

Answer: Olá, no seu caso a solução mais simples é executar a desestruturação do objeto crinado um novo, assim mantera a percistencia já que o dado do seu arrey não estara mais vinculado ao dado sendo salvo pelo metodo save()
public ResponseEntity putLoja(@Valid @RequestBody Loja atualizaLoja, @PathVariable int idLoja) {
    if (lojaRepository.existsById(idLoja)) {
        atualizaLoja.setId(idLoja);
        lojaRepository.save(atualizaLoja);
        //Solução aqui
        Loja lojaDataPast = lojaRepository.findById(idLoja).get()
        Loja lojaDataArray = new Loja();
        lojaDataArray.setId(idLoja);
        lojaDataArray.setNome(lojaDataPast.getNome())
        pilhaLojaAuxiliar.push(lojaDataArray);
        //Fim Solução
        return ResponseEntity.status(200).build();
    } else {
        return ResponseEntity.status(400).build();
    }
}


How Can I install multiple cronjobs using helm?

Question: I have a cronjob file in helm that looks like the below:
apiVersion: batch/v1
kind: CronJob
metadata:
  name: job-1
  namespace: default
  ...
apiVersion: batch/v1
kind: CronJob
metadata:
  name: job-2
  namespace: default
  ...
apiVersion: batch/v1
kind: CronJob
metadata:
  name: job-3
  namespace: default
  ...

How do I install all cronjobs with their names as job-1, job-2 and job-3 using just one helm install command: helm install $name $chart
I tried installing it and it only installs job-1. I was expecting it to install all three jobs and when I run kubectl get cronjobs I should be able to see all three jobs
Answer: Put each CronJob in a separate file in the templates directory.
In principle it is also possible to split this into separate YAML documents, but this isn't usually a preferred approach.  (It's necessary if you use the Helm template range construct to create multiple documents using a loop, though.)  Put --- on its own line before each document.
---
apiVersion: batch/v1
kind: CronJob
metadata:
  name: job-1
---
apiVersion: batch/v1
kind: CronJob
metadata:
  name: job-2
---
apiVersion: batch/v1
kind: CronJob
metadata:
  name: job-3

Without these markers, this is taken as a single mapping with duplicated key: value pairs.  That is, there's a single YAML file as its output, that happens to contain metadata: multiple times.  Different tools handle this YAML in different ways, typically either producing an error or by discarding all but the last copy of a given key.  Running helm template over your chart will tell you for sure what Helm is generating.
Comment: Running `helm template` generated the file I pasted in my question. I was wondering if there is a way helm will just install all cronjobs with a single command.
Comment: To put this answer differently: if the YAML file you included is accepted by a YAML parser, it only includes one CronJob resource, probably made from the last `metadata:` and `spec:` there.  You either need to split it into three files or explicitly separate it into three documents in the same file.


Changing a locale for embedded signing

Question: How can I change a locale for embedded signing via API for each unique recipient? Currently I use a query parameter which I add to embedded signing URL - "&locale={lang}", but I guess there should be some option in API(Ruby SDK) for it.
In previous answers I saw "emailNotification" object and "language"(or smth similar) as its key, but in the current version of SDK it seems not to exist any longer.
Answer: See this question Embedded DocuSign signing: using recipient's language
The emailNotification property for each recipient (Signer etc.) can be used to specify supported languages.
Note that if they already set their lang themselves - this may override your API request.
Comment: Thank you for the answer! I've looked through once more and found that property in REST API. Now it's only needed to find it in SDK.
Comment: Each recipient type has it. Here is the Signer one - https://github.com/docusign/docusign-ruby-client/blob/a8c9654f8820ff5266d606e3295c1558640fd895/lib/docusign_esign/models/signer.rb
 :'email_notification' => :'emailNotification'

Changing a locale for embedded signing


FileStream.Read() Throws ArgumentException

Question: I would like to make some secure container for my application, and here's the map :

I finished opening/saving code now, and tested it, however, ArgumentException was thrown.
The code will run like this.

Create byte[] type variable for containing not crypted user data.
FileStream Writes Magic Number to first 5 bytes.
RijndaelManaged accepts key, and generates Initialization Vector.
FileStream Writes Initialization Vector to next 16 bytes. <- Exception thrown!
CryptoStream transform the variable from 1.
FileStream Writes the crypted data from 22th bytes.

Debugging, and I found the reason that FileStream.Read() has been thrown the Exception. and the message is:
Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.
I tried to set the length of stream as (user data) + 21. but it doesn't work. I attach entire code for saving file, and I hope this problem will be solved.
Thank you!
    private bool SaveFile(string FilePath, bool IsCrypt)
    {
        byte[] Data = Encoding.UTF8.GetBytes(WorkspaceList[CurrentIndex]._textbox.Text);

        using (var Stream = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {

            if (IsCrypt)
            {
                Stream.SetLength(Data.Length + 21); // Tried when I got Exception
                Stream.Write(MagicNumber, 0, 5); //Magic Number

                using (var CryptoHandler = new RijndaelManaged()) // AES256 Encryption
                {
                    CryptoHandler.BlockSize = 128;
                    CryptoHandler.KeySize = 256;
                    CryptoHandler.Padding = PaddingMode.PKCS7;
                    CryptoHandler.Mode = CipherMode.CBC;

                    var tempKey = WorkspaceList[CurrentIndex]._cryptkey;

                    if(tempKey.Length < 32)
                    {
                        tempKey.PadRight(32);
                    }
                    else if (tempKey.Length > 32)
                    {
                        tempKey.Remove(33);
                    }

                    CryptoHandler.Key = Encoding.UTF8.GetBytes(WorkspaceList[CurrentIndex]._cryptkey.PadRight(32));
                    CryptoHandler.GenerateIV();

                    Stream.Write(CryptoHandler.IV, 5, 16); //IV Insertion *** ArgumentException ***
                    var CryptoInstance = CryptoHandler.CreateEncryptor(CryptoHandler.Key, CryptoHandler.IV);

                    using (var MemoryHandler = new MemoryStream())
                    {
                        using (var Crypto = new CryptoStream(MemoryHandler, CryptoInstance, CryptoStreamMode.Write))
                        {
                            byte[] _Buffer = Data;
                            Crypto.Read(Data, 0, Data.Length);
                            _Buffer = MemoryHandler.ToArray();

                            Stream.Write(_Buffer, 21, _Buffer.Length); // Insert Crypted Data
                            Stream.Close();

                            return true;
                        }
                    }
                }
            }
            else
            {
                Stream.Write(Data, 0, Data.Length);
                Stream.Close();
                return true;
            }
        }
    }

Comment: 5 makes no sense, it is not the offset in the file.  Pass 0 instead so you'll write all of the bytes in the IV.  Favor CryptoHandler.IV.Length instead of 16.  It is wrong again at 21.
Answer: Replace Stream.Write(CryptoHandler.IV, 5, 16); //IV Insertion
With Stream.Write(CryptoHandler.IV, 0, CryptoHandler.IV.Length); //IV Insertion
array = CryptoHandler.IV (the data you want to write)
offset  = 0 (you write from the first byte of array)
count = CryptoHandler.IV.Length (you write all bytes from CryptoHandler.IV)
Note that offset is intrinsic to array, not to the Stream. After a successful Write operation, the stream cursor waits at the last written position. I suppose you specified an offset of 5 to take into account the MagicNumber?
You would have add the same problem with Stream.Write(_Buffer, 21, _Buffer.Length);


Calculating moments of a binomial distribution

Question: I have the following problem:
If $X$ satisfies a binomial distribution with parameters $n$ and $p$, its expected value is $np$ and variance is $np(1-p)$. Prove these using formulas given in pages 8 and 10.
On page 8 we have been given that
$E(X)=\sum_{i=1}^k P(X=x_i)x_i$,
$\operatorname{Var}(X)=\sigma^2=\sum_{i=1}^kp_i(x_i-\mu)^2=\sum_{i=1}^kP(X=x_i)(x_i-\mu)^2$
and on page 10 we have formulas for $E(a+bX), \operatorname{Var}(a+bX), E(X+Y), \operatorname{Var}(X\pm Y)$.
I already managed to find a proof using the identity $x^2\binom{n}{x}=xn\binom{n-1}{x-1}$ which does not use the formulas above but as we haven't given that identity in the course, I was wondering whether there is an alternative proof.
Answer: \begin{align}
E(X) &= \sum x P(x)\\
&= \sum x .C^n_x.p^x(1-p)^{n-x} \\
&= \sum x .\dfrac{n!}{x!(n-x)!}.p^x(1-p)^{n-x} \\
&= \sum \dfrac{n!}{(x-1)!(n-x)!}.p^x(1-p)^{n-x} \\
&= np\sum \dfrac{(n-1)!}{(x-1)!(n-x)!}.p^{x-1}(1-p)^{(n-1)-(x-1)} \\
&= np\sum C^{n-1}_{x-1}.p^{x-1}(1-p)^{(n-1)-(x-1)} \\
&= np\times 1\\
&= np
\end{align}
Answer: Do you happen to know ProofWiki?
http://www.proofwiki.org/wiki/Expectation_of_Binomial_Distribution
This might be helpful for further work.
Comment: Ah. I think it's the proof 2 in that web site the professor wants. Thanks for the link!


How to fix the colours of the Spectrum with Numpy Python

Question: So far I have written a code that through which I was able to create a spectrum.
Here's the code:
def draw(self):
        x = np.linspace(0, 1, self.resolution)
        y = np.linspace(0, 1, self.resolution)
        X, Y = np.meshgrid(x, y)
        R = X
        G = Y
        B = np.ones_like(X) * 0.5
        print(R,G,B)
        self.output = np.stack([R, G, B], axis=-1)
        return self.output.copy()

But it's giving me a spectrum with light colours:
Current spectrum
But I want to create an Image like this:
Required spectrum
Any help would be appreciated or if you can recommend where I can learn about this fix it.
Answer: You add 0.5 to the blue color channel everywhere, while in your target image the amount of blue fades from left to right.
def draw(self):
        x = np.linspace(0, 1, self.resolution)
        y = np.linspace(0, 1, self.resolution)
        X, Y = np.meshgrid(x, y)
        R = X
        G = Y
        B = X[:, ::-1]
        print(R,G,B)
        self.output = np.stack([R, G, B], axis=-1)
        return self.output.copy()

Comment: Ok this is working now - could you please share the resources where I can learn more on this?


1-byte MIDI messages through USB-MIDI converter

Question: I have a "Fore" USB-MIDI converter and I suspect it is not properly handling the 1-byte MIDI messages that my Windows PC-based sequencer is sending.  The codes are 0xf8 (timing code), 0xfa (MIDI start), and 0xfc (MIDI stop).  The converter seems to generate a bogus note-on event to its MIDI-out for almost every 1-byte message it receives.  The bogus note-on event uses the velocity value and status byte from a previous note-on event, using the velocity value as both the note code and velocity value for the bogus note-on event.  This of course causes hung notes.
If I route the sequencer to an internal MIDI device (i.e., Microsoft GS Wavetable Synth), there are no hung notes.  If I put the converter in loopback mode (connect MIDI-out to MIDI-in) and capture MIDI in data on the PC (using Windows mmeapi MIDI in "driver"), and print out all the MIDI data received, I can see the bogus notes:

[0xfa, MIDI start code sent from sequencer]
MIDI in: 90 54 54 <-- bogus note
MIDI in: 90 35 54 <-- first real note
...

So I bought another USB-MIDI converter of a different brand (Wersi). It does the exact same thing.  In fact, it looks like it uses the exact same PCB and housing (same oval cross section, length, and bright red LED). It even came in an identical box.
Any ideas where to go from here?
Comment: Picture of the converter might help. If it has something that looks a bit like a teble clef but isn't one, then just throw it away & buy one with a name you've heard of, or at least from a music store not eBay for a fiver.
Comment: ah, Google found it - seems to have a lot of advertising on social media & available only from the finest retailers… those named after Brasilian rivers, or rhyme with meBay ;) I'd send it back & get one from at least a musician's box-shifter - https://www.thomann.de/gb/search_dir.html?smcs=7d334d_3838&oa=pra&sw=usb%20midi%20interface&cme=false&filter=true I really don't know who is making this chip-set, but you'd think they'd be able to get it right by now - it's not like there have been any major advances in midi transmission protocol in the last 35 years :\
Answer: Should I turn this into an answer… perhaps so…
It seems to be that someone, somewhere made a couple of million of these chips a decade or more ago & didn't know how to offload them, until Amazon & eBay came along.
People buy these things for a fiver - then fail to send them back & report the sellers when they don't work because they're too cheap to really care about having to deal with the return. It seems the latest incarnation of these, they've now upped their packaging & started selling them at $£€20 not 5. Can we spell 'scam'? These are the same people, hidden behind a myriad offshore guises, who will sell you a 16TB SSD for $£€ 70.
This technology was perfected in the late 80s. There is no excuse any more to still be selling this stuff.
What you really need to do is send it back, report the seller for a product 'not to expectation' or 'not fit for purpose' [these are legal terms in the UK - your territory is likely to have something similar.]
Then buy one from a music store, or online musical 'box shifter' who will at least stand by their products, and have very probably tested them first.
One box shifter I would trust in the UK/EU is Thomann. They came from nowhere a few years back, but seem to actually be keeping tabs on what they sell & are building a reputation. For the US, Sweetwater has a similar, and much longer-lived, reputation. This is not to discredit smaller presences online, just that if someone is shifting this much stuff, all in one 'genre', then they probably have their act together.
Comment: Thanks Tetsujin.  I got them both on Amazon, closer to $15. I'll return the new one, but too late on the old one.  You're right - I should report the sellers, or at least post a review with my findings.  Looks like closer to $40 for something from Sweetwater with a brand I've heard of (Roland).
Comment: If they're from a proper musical box-shifter like Sweetwater or Thomann, you can probably get away with the cheapest they sell - if it didn't work, they'd probably have pulled it from sale by now. They have reputations to live up to… which is why you can usually trust them to either sell you the right one, or quickly fess up & replace anything that wasn't up to spec. 'AmaBay' sellers just run away & set up another shop with a different name. They're often off-shore so no-one can touch them legally. Different trust levels entirely.


JAX-RS one mapper for all custom exceptions

Question: I've created a custom exception to notify user if something went wrong. E.g. if user send some not correct data from front-end and check for that is happening somewhere deep in back-end than all I need to do it just to

throw new CustomException("Message", 406)

with message and error code. And after that will immediately send a response to front-end with error code and text message which I can show on UI e.g. as a snackbar.
CustomException
public class CustomException extends RuntimeException {

  private final int errorCode;

  private static final long serialVersionUID = 6220614065727287629L;

  public CustomException(String message, int errorCode) {
    super(message);
    this.errorCode = errorCode;
  }

  int getErrorCode() {
    return errorCode;
  }
}

CustomExceptionMapper
@Provider
public class CustomExceptionMapper implements ExceptionMapper<CustomException> {

  @Override
  public Response toResponse(CustomException ex) {

    ErrorResponse response = new ErrorResponse(ex.getMessage(), ex.getErrorCode());
    return Response.status(ex.getErrorCode()).entity(response).build();
  }
}

ErrorResponse
public class ErrorResponse {
 private Error error;

  ErrorResponse(String errorMessage, int errorCode) {
    createError(errorMessage, errorCode);
  }

  private void createError(String message, int code) {
    setError(new Error(message, code));
  }

  public Error getError() {
    return error;
  }

  public void setError(Error error) {
    this.error = error;
  }

}

Error
public class Error {
  private String message;
  private int code;

  public Error(String message, int code) {
    this.message = message;
    this.code = code;
  }

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public int getCode() {
    return code;
  }

  public void setCode(int code) {
    this.code = code;
  }
}

But now I need some extra functionality. For form validation in back-end I need to send also which text field was not correct. So I think the best way to do that is to create a new child exception of CustomException and add there a new property.
CustomFormException
public class CustomFormException extends CustomException {

  private final String formField;

  private static final long serialVersionUID = 6220614065727287630L;

  public CustomFormException(String message, int errorCode, String formField) {
    super(message, errorCode);
    this.formField = formField;
  }

  String getFormField() {
    return formField;
  }
}

Than I can modify a little bit ErrorResponse and Error classes. Add new constructor and new property textField
public class ErrorResponse {

  private Error error;

  ErrorResponse(String errorMessage, int errorCode) {
    createError(errorMessage, errorCode);
  }

  ErrorResponse(String errorMessage, int errorCode, String textField) {
    createError(errorMessage, errorCode, textField);
  }

  private void createError(String message, int code) {
    setError(new Error(message, code));
  }

   private void createError(String message, int code, String textField) {
    setError(new Error(message, code, textField));
  }

  public Error getError() {
    return error;
  }

  public void setError(Error error) {
    this.error = error;
  }

}

Error
public class Error {
  private String message;
  private int code;
  private int String textField;

  public Error(String message, int code) {
    this.message = message;
    this.code = code;
  }

  public Error(String message, int code, String textField) {
    this.message = message;
    this.code = code;
    this.textField = textField;
  }

  // setters and getters
}

But then I need also create a new Mapper because the old one is made for CustomException and in CustomException there is no textField property.
Is it possible to use somehow one Mapper for all custom exceptions and not create for every custom exception extra mapper?
Answer: You can use a common base class for all your custom exception and use Base class in Exception mapper.
Eg:
public class MyServiceException extends RuntimeException {

  private ErrorCode errorCode;
  private boolean customMessage;

  public boolean haveCustomMessage() {
    return customMessage;
  }

  public MyServiceException(ErrorCode errorCode) {
    super(errorCode.getMessage());
    this.errorCode = errorCode;
  }

  public MyServiceException(ErrorCode errorCode, String msg) {
    super(msg);
    customMessage = true;
    this.errorCode = errorCode;
  }

  private static final long serialVersionUID = 5212119866822715497L;

  public HttpError getHttpError() {

    return new HttpError(errorCode);
  }
}

public class DataNotFoundException extends MyServiceException {

  private static final long serialVersionUID = 1L;

  public DataNotFoundException() {
    super(ErrorCode.DATA_NOT_FOUND);
  }

}

public class InternalServerException extends MyServiceException {

  private static final long serialVersionUID = 1L;

  public InternalServerException() {
    super(ErrorCode.INTERNAL_SERVER_ERROR);
  }

}

@Provider
public class MyServiceExceptionMapper implements ExceptionMapper<MyServiceException> {

  @Override
  public Response toResponse(MyServiceException exception) {
    return Response.status(exception.getHttpError().getErrorCode().getCode())
        .entity(exception.getHttpError().getErrorCode().getMessage()).type("text/plain").build();
  }
}

public class HttpError {

  public HttpError(ErrorCode errorCode) {
    this.errorCode = errorCode;
  }

  private ErrorCode errorCode;

  public ErrorCode getErrorCode() {
    return errorCode;
  }

}

public enum ErrorCode {

  INTERNAL_SERVER_ERROR(
      Code.INTERNAL_SERVER_ERROR, Messages.INTERNAL_SERVER_ERROR), DATA_NOT_FOUND(Code.DATA_NOT_FOUND,
      "Data not found ");

  private int errorCode;
  private String errorMessage;

  private ErrorCode(int errorCode, String errorMessage) {
    this.errorCode = errorCode;
    this.errorMessage = errorMessage;
  }

  private interface Code {

    int DATA_NOT_FOUND = 404;
    int INTERNAL_SERVER_ERROR = 500;
  }

  public int getCode() {
    return errorCode;
  }

  public String getMessage() {
    return errorMessage;
  }
}


Docusign API - Recipient and Sender View Timeout

Question: I am using both the REST API and the .NET library to work with Docusign from our site. I was just checking if there were any properties anywhere inside the envelope that let you know if a sender or recipient has the envelope "open" (aka the signing or tagging view URL was loaded, but the user hasn't finished).
Within our web app, we can easily tell when they've "opened" it because when users sign or place tags, they click on one of our own internal links first before being redirected, but unless the user finished the process (either clicking SEND or FINISH or just plain TIMING OUT and getting redirected back to our page), we can't tell is the user currently is looking at the document or if they opened it and then closed it.
So basically, I guess I'm asking if the user closes their browser without sending or signing, is there some kind of date or flag that can tell this?
One follow-up question: Speaking of Timeout, I set ours to 15 minutes. Once you open the console URL to place signature tags or to sign, does the timeout start and then ONLY stop once you've SENT or FINISHED the envelope? Do other actions like scrolling, partially signing, etc reset the timer? Or is it X minutes after the console is open, no matter what?
Comment: FYI, I just realized that in the recipient view, I can use PINGURL and PINGFREQUENCY to tell if the user is still active every 60 seconds. Is there anything like this for the sender view?
Answer: Sorry, no, the sender view does not offer a ping facility.
In the usual use case, the sender is motivated to send out the envelope for signing. So the problem of the user "abandoning" the sender view is generally not a concern.
You can check the envelope's status periodically or register for a webhook message when the envelope is sent. The envelope will be sent when the sender successfully finishes using the sender view.
If the sender is a concern, I suggest that you not use the sender view. Instead, get the necessary information (docs, recipients, notes, etc) from the sender, then send the envelope programmatically. Use "the Send on Behalf of" (SOBO) feature to send the envelope for the sender.


Using RPi.GPIO with django

Question: I have django project set on my pc and copy of that project on Raspberry pi 3. I deploy changes through pyCharm to raspi. Raspberry is my server where I host my website. I wanted to play with led light through web app. In my app I've imported import RPI.GPIO as GPIO but after server run there was ImportError: No module named 'RPi'. I've managed to install only gpio on pc (No matching distribution found for RPi), but there is still ImportError : No module named 'gpio'. Here is my code in views.py
import gpio
LED_PIN = 18
def turnOn(request):
    gpio.setmode(gpio.BOARD)
    gpio.output(LED_PIN, 1)
    return HttpResponse('')

Is there any possibility to use RPi.GPIO in django on pc?
Comment: You cannot get RPi.GPIO on your pc, there are different io connections. However, if you deploy the code to your raspberry pi and run you can use RPi.GPIO.
Answer: RPi.GPIO is Raspberry-specific and you really cannot use it on your computer - it even has no GPIO ports. You should deploy your code to RPi and use it there.
Answer: I found a solution. With help of wiringPi and subprocess I could execute command.
def turnOn(request):
subprocess.call(['gpio', '-g', 'mode', '3', 'out'])
subprocess.call(['gpio', '-g', 'write', '3', '1'])
return HttpResponse('')

Using RPi.GPIO with django