How to create my own custom simple action in D8?

Question: I'm creating a view that is used to review migrated content that was flagged for review during the migration process. I want to provide a bulk action on this view that allows the user to select a bunch and mark them as "resolved".
I created a custom action to do this following some guidance from https://www.drupal.org/node/2330631:
config/install/pu_news_migrate.action.resolve_news_migration_flag.yml
langcode: en
status: true
dependencies:
  module:
    - node
id: resolve_news_migration_flag
label: 'Resolve news migration flag'
type: node
plugin: resolve_news_migration_flag
configuration: {  }

And created the action plugin implementation:
`src/Plugin/Action/ResolveNewsMigrationFlag.php
<?php

namespace Drupal\pu_news_migrate\Plugin\Action;

use Drupal\Core\Action\ActionBase;
use Drupal\Core\Session\AccountInterface;

/**
 * Removes the "needs review" flag on a migrated news article.
 *
 * @Action(
 *   id = "resolve_news_migration_flag",
 *   label = @Translation("Resolve news migration flag"),
 *   type = "node"
 * )
 */
class ResolveNewsMigrationFlag extends ActionBase {

  /**
   * {@inheritdoc}
   */
  public function execute($node = NULL) {
    if ($node) {
      /** @var \Drupal\node\NodeInterface $node */
      if (!$node->hasField('field_news_migration_review')) {
        throw new \RuntimeException("News migration field not found on node.");
      }
      $node->set('field_news_migration_review', FALSE);
      $node->save();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\node\NodeInterface $object */
    $result = $object->field_news_migration_review->access('edit', $account, TRUE)
      ->andIf($object->access('update', $account, TRUE));

    return $return_as_object ? $result : $result->isAllowed();
  }

}

I also added a schema file: config/schema/pu_news_migrate.schema.yml:
action.configuration.resolve_news_migration_flag:
  type: resolve_news_migration_flag
  label: 'Remove the "needs review" flag from a migrated article.'

I uninstalled the module and re-installed it so that the action definition is loaded into Drupal's config.
However, when I view the list of actions I can select in views, it doesn't appear there. I enabled the "Actions" module which displays a list of all actions, and it does not appear there either.
What did I do wrong here?
Comment: Kevin, that was it! If you post that as an answer I can can accept your answer and bounty.
Comment: Did you also provide a schema.yml file? Check the node module for an example. I also think the name of the file needs to be _system.action...._ not _pu_news_migrate_
Comment: Yes, just updated question with that snippet
Comment: Did you try renaming the plugin yaml file name to _system.action.._, uninstalling and reinstalling? The actions in node and user are named this way, not node.action.blahblah.
Comment: I thought so, just wanted to double check. Answer added.
Answer: Action plugin yaml definitions need to be prefixed with the name system.action.action_name.yml, and not mymodule.action_name.yml.
For reference, check the provided action plugins for node and user module in core in their config/install and config/schema folders.
Uninstall the module, rename the files, and install the module again so the changes are picked up. You should then see your custom action.
So:
config/install/system.action.resolve_news_migration_flag.yml


Logarithm and Uniqueness

Question: Fix $b>1, y>0$ and prove that there is a unique real $x$ such that $b^x = y$. So for uniqueness, $x_1 < x_2 \Rightarrow b^{x_1} < b^{x_2}$. Then consider the set $S = \{b^t: t \leq x \}$ and work from there?
Source: Chapter 1, Problem 7, Principles of Mathematical Analysis by Rudin
Comment: That's one possible approach. Ultimately, you will have to use the fact that $x\mapsto b^x$ is continuous, strictly increasing, and the intermediate value theorem.
Comment: Don't have IVT available yet (or anything about continuity).
Comment: If you don't have continuity, how do you define $b^x$ for arbitrary real $x$? I often see it defined first for $x\in\mathbb{N}$, then for $b > 0$ and $x\in \mathbb{Q}$ by taking roots, and then assert that $b^x$ is defined for $x\in\mathbb{R}$ "by continuity"...
Comment: @Willie: You can define it as the supremum  of the set of $b^r$ where $r$ is rational and less than $x$.  @Trevor: Could you please cite the source of your problem if this comes from a textbook?  The context would make it clearer what sort of answer you're looking for.  If you don't have a source, then please elaborate in your question on how things are defined.
Comment: This is from Chapter 1 from Baby Rudin. He goes through an outline of the proof. But I am just trying to do it from scratch (what he does is tricky).
Answer: Actually, the proof is quite easy following his outline:
(a) Lemma: For any positive integer $n$, $b^n -1 \geq n(b-1)$
Proof: Suppose this holds for $n$. Then $b^n-1\geq n(b-1)\geq n/b(b-1)$, since $b>1$
Then $b^{n+1} \geq n(b-1)+b$, and so $b^{n+1}-1 \geq n(b-1)+(b-1)$, therefore $b^{n+1}-1\geq (n+1)(b-1)$. Since $b^n -1 \geq n(b-1)$ holds for $n=1$, by induction it holds for any $n$.
(b) Hence, $b-1 \geq n(b^{1/n}-1)$ if we apply the lemma setting $b' =b^n$ ($b'>1$ since $b>1$).
(c) If $t>1$ and $n>\frac{b-1}{t-1}$, then $b^{1/n} < t$.
Proof: Since $n>\frac{b-1}{t-1}$, then $n(t-1)>(b-1)\geq n(b^{1/n}-1)$. It follows that $b^{1/n} <t$.
(d) If $b^w<y$, then $b^{w+(1/n)}<y$ for sufficiently large $n$.
If we set $t=y/b^w$, we see that $t>1$ and we can choose a sufficiently large $n$ such that $n >\frac{b-1}{t-1}$. Because of (c) we know that $b^{1/n}<t$. Multiply both sides by $b^w$ to get $b^{w+1/n}<y$, which is what we wanted to prove.
(e) If $b^w>y$, then $b^{w-(1/n)}<y$ for sufficiently large $n$.
If we set $t=b^w/y$, we see that $t>1$ and we can choose a sufficiently large $n$ such that $n >\frac{b-1}{t-1}$. Because of (c) we know that $b^{1/n}<t$. Then $1<\frac{t}{b^{1/n}}$, so $1<\frac{b^w}{yb^{1/n}}$ and therefore $y<b^{w-(1/n)}$.
(f) Let $A = \{w : b^w<y\}$, then if $x=\sup A$, $b^x = y$.
Since $b>1, y>0$, choosing a sufficiently small $w$ will get us arbitrarily close to $0$, so $A$ is non-empty. Since $b^w>y$ for a sufficiently large $w$, $A$ is bounded above, and because of $A$ being a subset of $\mathbb{R}$ then $\exists\sup A$.
Fix $x = \sup A$. Suppose $b^x < y$, then because of (d), $b^{x+(1/n)}<y$ for some $n$. But then $x+1/n > x$ and $x+1/n \in A$, which is a contradiction.
Suppose $b^x > y$, then because of (e), $b^{x-(1/n)}>y$ for some $n$. But then $x-(1/n)$ is an upper bound of $A$ smaller than $x$, which is a contradiction.
Therefore if $x=\sup A$, then $b^x=y$
(g) The uniqueness of $x$ follows from the fact that there can't be two different least upper bounds for the same set $A$.
Feedback is appreciated, thanks.
${{}}$
Comment: Your proof of (g) is problematic. Though we know $x=\sup A$ leads to $b^x=y$, $b^z=y$  doesn't necessarily lead to $z=\sup A$
Comment: Second half of the first inequality, n/b(b-1), do you mean (n/b)*(b-1)  or. n/[b*(b-1)]?
Comment: I think it's the first of the two possibilities. It's still ambiguous.
Comment: @Hank not really.
Comment: Real exponentiation is injective. If $b^{\mathrm{sup} A} = y = b^z$, then $z=\mathrm{sup} A$.
Answer: Yes, if you prove that $x\mapsto b^x$ is strictly increasing, that will show that there is at most one solution.
However, your proposal with $S$ does not really work because what you are looking for is $x$; since you do not know ahead of time what $x$ is, you cannot define $S$ in the first place!
Instead, consider the set $S = \{ r\in\mathbb{Q} \mid b^r\leq y\}$ (or $\{r\in\mathbb{R}\mid b^r\leq y\}$).

Logarithm and Uniqueness


what should the ACL value be when limiting S3 object access to CloudFront only?

Question: I followed https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html
But I cannot figure out what should the ACL on AWS.S3.PutObjectRequest be when I upload to s3 bucket.
Possible values:
"private"|"public-read"|"public-read-write"|"authenticated-read"|"aws-exec-read"|"bucket-owner-read"|"bucket-owner-full-control"
Using JavaSript SDK Currently I have "public-read", I know I should change this, but I am not sure which is the best for this case. My initial thought is to "private".
Answer: private is correct, though not strictly necessary, since that's the default behavior.  Specifying no ACL or specifying the "private" canned ACL is exactly the same.

private | Bucket and object    | Owner gets FULL_CONTROL. No one else has access rights (default).
https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl

"No one else has access rights" actually means No one else has access rights granted by the ACL since the bucket owner can grant access to objects it owns using the bucket policy (or IAM user/role policies, though that isn't applicable to an Origin Access Identity, which is granted access via the bucket policy).


SNMP constructor takes several seconds to return

Question: I'm using Snmp4j 2.2.3 and I am observing a lag of up to 8 seconds when I construct a org.snmp4j.Snmp object via public Snmp(TransportMapping) I wonder if anyone knows where in Snmp I should focus my attention. I see this happening on Redhat Linux, but I don't see the lag when running from a Windows XP box.
In the following code, line 3 "Snmp snmp = new Snmp(transport);" is freezing for up to 8 seconds.
Address targetAddress = new UdpAddress(host + "/" + port);
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);

CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version2c);
target.setMaxSizeRequestPDU(65535);

snmp.listen();

Thanks
Answer: Turin correctly pointed to the problem.
If you are only using SNMPv2c, you can make a cleaner initialization that does not load cryptography related classes of v3.
TransportMapping transport = new DefaultUdpTransportMapping();
MessageDispatcher disp = new MessageDispatcherImpl();
disp.addMessageProcessingModel(new MPv2c());
snmp = new Snmp(disp, transport);
...
snmp.listen();

Answer: I found the same issue with snmp4j 1.11.2.
Adding -Djava.security.egd=file:/dev/./urandom to the jvm solved the problem.
The solution was found http://snmp4j.agentpp.narkive.com/xzGw7pL1/initialize-too-slow and How to solve performance problem with Java SecureRandom?
Answer: Most likely, this is a problem in the RedHat random seed initialization of the operating system. As far as I know, there is a fix available for the OS that ensures the entropy computation does not take too much time.
Answer: I've seen this issue occur on red hat flavors that are running as VMs due to lack of access to hardware to generate entropy for urandom. If this is the case, installing haveged fixes the issue. Its an alternate source for entropy generation.
How to setup haveged:
https://www.digitalocean.com/community/tutorials/how-to-setup-additional-entropy-for-cloud-servers-using-haveged
Security post related to haveged that mentions other methods of entropy generation: https://security.stackexchange.com/questions/34523/is-it-appropriate-to-use-haveged-as-a-source-of-entropy-on-virtual-machines


Views: adding "new" image when published date < 1 month

Question: In a table view of nodes i want to add a tiny "New" image only when a node is published < 1 month ago.
Is there a way to achieve this without using PHP? If not, is there an easy way and what PHP should i insert?
I was hoping for a little module to get the job done, but haven't found anything.
Thanx,
Cas
Answer: If the list is always going to be in date order, then it can be done without PHP by using a View with an attachment. See this answer for an explanation of how to do that.
If the list is not sorted in date order, PHP may be the way to go. (Though I'd be delighted to be contradicted.) You'll need the Views PHP module installed.

Add the Content: Post date to your list of fields. If you don't want it displayed set the 'Exclude from display' check box. Displayed or not, it's needed.
Add a 'Global: PHP' field to your list of fields. In the Value code box, insert the following snippet:
$interval = time()-  $data->node_created;
$days = round($interval/(60*60*24));
return $days < 30 ? $days : 0;

This snippet grabs the value of the Post date field from the database query that the view has executed. It then works out the number of seconds difference between the post date and the current time. It converts the seconds into days. If the post is less than 30 days old it returns the number of days as a field value, otherwise it returns 0. (It could just return 0 or 1, but returning the value could be useful in some cases.)

In the No Results Behaviour section check the boxes for 'Count the number 0 as empty', 'Hide if empty' and 'Hide rewriting if empty'. This means when the PHP returns zero, nothing will be displayed.
In the Rewrite Results section, insert whatever output you want when the node is less than 30 days old. In the question you talk about an image, so maybe put in something such as .

Additional Notes
If you want to use different date fields etc. you can work out what to put in the PHP by switching on the display of the SQL query in preview. (See the Views settings tab from the main Views page.)
If you want a bit more control over your output, you can use the Output code box. For example the following code will put a red 'new!' label against new fields. When doing this you don't want to also have Rewrite Results set.
<?php if ($value) echo '
new!
' ?>

This code checks to see if the result of the earlier PHP code is TRUE (and not zero is TRUE). If it is is displays the red 'new!'
Comment: Thanx again for your invaluable help! It all works perfectly and i chose to use the **new!** text instead of an image because it shows better in a table view. But somehow an image does not show anyway. I triple-checked the syntax, path and filename, but all i get is a little blue ? in a box telling me the image can't be found. I checked the element telling me the path/filename is right. The same happens with other fields in the same view i want to rewrite as an image. I use the same syntax in a Flag where it works OK. I wonder if this has something to do with Views settings?
Comment: Forget my last question, found the path-problem. It seems that Views needs the whole path (/mydir/sites/default/files/myimages/myimg.png) where the Flags module only needs a relative path (sites/default/files/myimages/myimg.png). Confusing.
Comment: Good to hear answer was helpful and you tracked down source of yr image path issue. To help other users do consider marking the answer as correct.


Is the upper limit on your ability to fret faster hereditary?

Question: I'm curious what are the other drawbacks to playing guitar faster other than "Practice more".
Here is the example: I can play Cliffs of Dover at about 55% speed on the fastest run's.
Physically, I'm pretty strong, I lift weights most days and heavy ones at that. But ever since I was a child I could not throw a baseball as far as other people. Which means, at least for my arm, I have strength, but not speed muscles. (The slow twitch, fast twitch ratio). Also since I'm older (60's), maybe that speed cant even be developed even in my fingers past a certain point. Players like Satriani have been doing this since they were children. And have put in much more time than me. I'm not interested in playing shred or even long fast runs, but it would be nice to get a 5 or 6 note fast phrase in once in a while.
Is there a genetic limit for some of us ?
Comment: "Practice more" is a drawback? :-)
Comment: Trivially,  if your inherited traits include not having fingers, it matters, but there is no evidence I'm aware of that the coordinated speed of many muscles in the arm/wrist/fingers is measurably different across 'normal' humans.  It's not like, e.g., runners who can sprint or run marathons better based on fast-twitch vs slow-twitch muscle cells in their legs
Comment: In comparison, how quickly can you play the piano? Can you play the "Cliffs of Dover" notes on piano faster than you can play them on guitar?
Comment: I don't play the piano. I don't have a keyboard to even try. But you do bring up a good point, maybe wrist position plays a part in it.
Comment: To answer this, there's a need to find fathers/sons etc., and check their playing. But I feel a wild goose chase coming.
Comment: I don't know if any study on this specific aspect of musculature, however, of you have already identified that you have strong but slow musculature then I think you have your own answer.
Comment: I can't tell from my experience as I'm the only one who plays music in the family. And I can tell that I see improvements when practising more. I know that something I physically can't achieve and so I would avoid doing so. For example, my hands are small, I know I can't play those chord shapes across 5 frets. My fingers need to move far if I shred, so I don't play those styles. Would you classify this as "genetic limit"? You are not Satriani and you have different background than him. Why bother playing just like him?
Answer:
Is the upper limit on your ability to fret faster hereditary?

No idea. Probably it is partially. But I guess the question you really want to ask is how to improve your speed.
Practicing more is an obvious direction, but you also need to focus on building speed. Effective practice strategies include:

Identifying difficult spots. What's easy at medium tempo may require you to change your technique at fast tempo.

Practicing very short fragments of music (even down to two notes), and extending them gradually.

Speeding up in bursts and slowing down.

Trying to playing at a very fast tempo, even faster than the "goal" tempo while ignoring mistakes.

Playing extremely slowly so that you can stay relaxed and focus on proper technique (of course first you need to figure out what is proper technique first).

You may look for more advice in instructional materials, video schools, especially from guitarists known for their prime playing technique.
Another good idea is to see a teacher. Perhaps your speed is limited by a very specific technical issue you need to work on, be it string skipping, fretting hand position or something else. You might be unaware of that.
Answer: Your physical limitations might be hereditary, but I don't think they're a good reason to give up on a goal.
If you want to play faster and feel like you've hit a wall, physically, then I think it best to stop, slow everything down, and focus on technique.
Lifting a weight requires a certain amount of strength, but use of proper technique will require less of it. Playing a fast run of notes requires speed, but use of proper technique requires less of it.
Finger positions, arm/wrist/hand angles, and the distance of movements and leverage of force they enable or impede are at least as big an influence on how fast you play as actual speed of your fingers and hand. Work on efficiencies rather than raw speed.
So yeah, you need to practice, but not necessarily more, just better.


Does probability threshold offset biases due to imbalanced classes in Logistic Regression?

Question: While building a logistic regression model, I have imbalanced binary classes in 80:20 ratio.

Does imbalance have any impact on the performance of a logistic model? If it depends on the severity, what's the criteria to consider a dataset as imbalanced?
Does it have anything to do with the fact that we are predicting probabilities and imbalance might just skew the probability distribution and the inaccuracies due to it can be controlled by choosing an appropriate threshold for cut-off?
Is there a function that can calculate the most optimum cut-off directly in R?

Thanks
Answer: The log-likelihood function of a binary classification model happends to be the same as KL divergence between your model and the real model. So if your model parameters are obtained by maximizing the log-likelihood (or minimizing the log-loss), the KL divergence will be minimized:
$$
\begin{align}{LL}_{LR} & = \frac{1}{N} \log \prod_i \pi^{y_i}(1-\pi)^{1-y_i} \\&= \frac{\sum_i y_i}{N} \log \pi + \frac{\sum_i 1-y_i}{N}\log (1-\pi) \\ &= KL(p||q) \end{align}
$$
Where $\frac{\sum_i y_i}{N}$ is the probability of observing $y_i$ in the "true model" $p$, $\pi$ is the probability of observing $y_i$ in the proposed model $q$.
In another word, the imbalance will not skew your estimation of the probability distribution.
But the number of samples will. If $\frac{\sum_i y_i}{N}$ can not capture well the proportion of positive samples in the real model, the so called "imbalance" may cause a porblem. For example if the positive rate of the population is 0.000001 (the "real model"), where you can easily get 100 samples with 0 positive case in it, so that your sample positive rate is $\frac{\sum_i y_i}{N}=0$, which is far from the real positive rate, and as a result your model will behave as if it's "skewed". But if you can increase your sample size to, say $1 \times 10^{20}$, then the sample postive rate will be much closer to the one of the population.
So to the question "how imbalance is my data?", the answers can be found by answering "how many samples do I need to make sure the sample positive rate can reflact the real positive rate?", or "With my current sample size $n$, what is the confidence interval of the sampled positive rate?". This are basic statistical problems where you can encounter a lot in hypothesis testing scenarios, I won't say much about it.
What if you find out that your sample size can not give you a significant estimation of the real positive rate, and you can't get more samples than you currently have? One way is to use resampling methods such as bootstrap to better capture the population distribution with limited sample size.
Another thing is, usually the model evaluation criteria is different from the model training criteria. For example your model may be trained by maximizing the log-likelihood, but it's evaluated by precision, recall, or f1-score. If you delibritely want to increase, for example recall rate, you should modify your machines understand of the "real model" by, say increasing the weights of the positive samples in the training set, and do a cross-validation on the weighting mechanisms to pick the best one.


Number of words- Adjacent letters unequal

Question: How many words of length $6$ are there when adjacent letters being equal is not allowed?
My try:
We have $26$ choices for the first position and $25$ for the remaining $5$ positions because if we choose any alphabet for the first position we have $25$ left for second and for the third we still have $25$ ($-1$ for the letter which is in $2$nd position) and so on.
So, is $26 \cdot 25^{5}$ the correct answer?
Comment: Yes, it is correct.
Comment: Yes, it is correct :-)
Answer: Yes the answer will be $$ 26 * 25^5 $$ and your method is absolutely correct.
Answer: Here is some additional information affirming your answer.

The words with no consecutive equal letters are so-called Smirnov words. If you are curious about them you might have a look at example III.24 in Analytic Combinatorics which explains some properties of them.

We count the number of Smirnov words of length $n$ with the help of formal power series. The coefficients of $z^n$ give the number of words of length $n$.

It turns out that the power series of Smirnov words with $26$ letters is
  \begin{align*}
\left(1-\frac{26z}{1+z}\right)^{-1}&=\frac{1+z}{1-25z}\\
&=1+26z+650z^2+16250z^3\\
&\qquad+406250z^4+10156250z^5+253906250z^6+\cdots
\end{align*}

The coefficients of $z^n$ were calculated with the help of Wolfram Alfa.

We observe, the number of Smirnov words of length $6$ is
  \begin{align*}
253906250=2\cdot5^{10}\cdot13=26\cdot25^5
\end{align*}
Comment: That's the reason I love Mathematics. An explanation for everything.
Thank you so much.
Comment: @max: You're welcome! I see, there are many good reasons to love mathematics. :-)


BeautifulSoup Returns vs View-Source from Chrome (Zillow)

Question: I have been trying to scrape the code from Zillow but beautifulsoup gives much less code than view-source from chrome. Here is my code:
<code>from bs4 import BeautifulSoup
import requests

from bs4 import BeautifulSoup
import requests
url='https://www.zillow.com/homedetails/49-Mountain-St-Hartford-CT-06106/58139903_zpid/'
html=requests.get(url)
bs = BeautifulSoup(html.text,"html.parser")
bs
</code>
Results show that contents in the body are so few. However, if you copy the url and view source code on chrome, you see a lot. Could someone show how to scrape the full contents in the body on Zillow? I saw "Please verify you're a human to continue" in the results, how to handle that?
Answer: I think your basic problem is that Zillow will load a lot of additional data after the first page request and use that data to populate the page.  Zillow may also do things to discourage web scraping (such as the captcha you're seeing).
How to do this well is a huge topic and not one easily answered in a Stack Overflow question.  You can look at this page for a list of resources that may be helpful to you as a scraper - https://github.com/niespodd/browser-fingerprinting
You can also open your network tab in your browser's developer tools (ctrl + F11 on Chrome).  In the network tab you can see the outgoing requests and the responses.  You can find the data you want in the responses and study the requests to find out how to get the data you are looking for.
Answer: As for the "verify you are a human", a good captcha today will not have the answer parsable on the client side and eliminate most efforts in modifying the request header. So you may want to try to use selenium browser and web-driver instead of only the requests library, that way you can manually beat the captcha and then let your scraper do its work.


Recording drum machine and electric guitar on the looper during live performance

Question: I want to record drum loops, and guitar loops, during the live performance. For example, I want to begin with guitar riff, loop it, and then overdub with sequence played on the drum machine. I wonder how to do it, and what gear should I use. The configuration should be something like this:

I've done some research, and I think that I could use Alesis SR-16 as drum machine, and Behringer MICROMIX MX400 as mixer, whose output signal will be an input for the looper. Will it be OK? I'm afraid of problems with the impedance, besides I don't want to destroy the amplifier. Do any of you use a similar gear configuration? Do you have any tips? I will be grateful for your help.
Comment: Can you go into a few more details as to how you are intending to use the drum machine? Usually a drum machine handles its own looping, so having it going into the looper perhaps isn't the most obvious configuration.
Comment: How are you going to be sure the guitar riff is exactly the same tempo as the tempo set on the drum machine if you loop the guitar riff first?  It seems to make more sense to loop the drum first and then play the guitar riff to the tempo established by the drum machine.  Or will you be monitoring the output from the drum machine with a headphone or have a click track set at the same tempo as the drum machine when you play the guitar riff?
Comment: If you're going to just play the drums into the looper in real time, I'd think an electronic drum kit with proper stick-playable pads (instead of the SR16, or controlling the SR16 via MIDI) would be better. As arek says, there are sync solutions if you want to sync a drum machine and a looper. I also wonder if you've considered using something like Ableton to deal with your drum and looping needs?
Comment: @topomorto I was thinking to record drum loops by hitting pads, but now I think to use drum machine sequencer synchronized with the looper.
Comment: @RockinCowboy Ditto Looper X4 can sync with external MIDI Clock, as you can see in this [example](https://www.youtube.com/watch?v=gc--XScZq7M).
Comment: @arek interesting. So will the drum machine send a signal to the looper to tell it to synchronize the guitar riff loop to the pre-set drum machine tempo?  Would you be recording the drum machine onto the looper or just plugging it in to the looper to set the tempo while the drum machine covers the drum part independent of the looper?  I'm just trying to learn what can be done.
Answer: Regarding destroying the amplifier, this is not going to be a problem with the Looper. It is designed to be in line with a guitar or a keyboard, and you can set the volume levels of your loops.
You shouldn't worry about or output impedance either. Input is 1MOhm, and output is 100Ohm - which are fine for this usage.
You may not need the mixer - the looper is stereo, so you could run the guitar on one channel and the drum machine on the other. This obviously won't work for stereo drum signal, and your guitar level would be much lower than the default drum level so this may not be the most useful configuration, but worth thinking about.
Comment: You may still need to run it through a mixer or a couple of volume pedals to control the different channels's volumes if you're performing live.  This is particularly true if you lay down a lot of layers. The overall volume gradually goes up as you add each layer so at some point you may need to lower the looper output volume and raise your input volume to compensate.
Comment: empty - pretty much all loopers give you really good control of levels so this shouldn't be an issue. It is good to have gain controls or EQ anyway after the looper though.
Answer: I think I am getting a better idea of what you want to do following your comments!
It would be a good idea to make sure that the drum machine that you choose has good playable pads - a lot of people only use the pads on drum machines to sequence things in step time or play simple parts that are then quantised later, so the pads aren't always that good.
You might want to make sure that you are happy with the sound of your drums through the guitar amplifier - drums often sound terrible through guitar amplifiers, as the amplifiers are often very midrangey.
Also bear in mind that you won't be able to use distortion or any effects on the guitar amp without also affecting the drums. You might consider using a guitar effect pedal after the guitar but before the looper. In fact I am assuming that you'll be using something between the guitar and the mixer - the MX400 is a 'line mixer' and only has an input impedance of 4.7kOhm, so might not work well with a guitar plugged straight in.
Comment: Acoustic pickups are often 'piezo' pickups and need an especially high input impedance - i.e. they are even *more* 'fussy' than normal magnetic pickups. However, many acoustic guitars with such pickups have a small preamp built in, making the output signal much more like a 'line' level signal. It's not clear from those comments whether those acoustics had onboard preamps or not.
Comment: Thanks for great tips! I wonder about your comment on MX400. From the [comments](http://www.musiciansfriend.com/pro-audio/behringer-micromix-mx400-4-channel-line-mixer) I've read, that people use this to mix acoustic guitars, and amplify them on guitar amp. Do acoustic pickups have different impedance from those used in electric guitars?


Cross-platform RPC with large messages

Question: I have an application where I need to issue commands from a .NET application running on Windows to a C++ application running on Linux over a dedicated Ethernet connection between the two machines.
Rather than rolling my own protocol, I'd prefer to use some standard form of RPC.  Previously I've used XML RPC for cross-platform applications, but these particular commands need to contain a lot of numeric data (several thousand double floating-point values per command), with commands sent frequently, so I'm thinking some sort of binary serialization is a better fit.  As such, I've started looking into Protocol Buffers.
So, a few questions:

I know that Protocol Buffers define a serialization format, but is there any accepted industry standard for how to perform cross-platform RPC using them?
Are Protocol Buffers well-suited to representing nested data structures with variable-sized arrays?  The number of points per command is variable and the most natural representation of part of the data is an array of structures that each contain an array of points.  All of these arrays will have variable sizes for any given command.
Are there any gotchas you've run into when using Protocol Buffers for cross-platform communication?
Answer:
No, there is no generally accepted standard. Some libraries come with their own RPC implementations, but none of them seems to be particularly popular. (Edit: As of 2019, gRPC has become quite popular.)
Pretty good in my opinion. Some libraries even allow for lazy decoding, so that you do not need to decode all of the nested structures if you only need a part of the data.
In addition to the RPC format not being defined, the framing of the messages is not defined. So you have to do some custom method such as adding a length field in the beginning. Another undefined part is how to identify the type of the message being transmitted. Make sure to clearly define these for your own project.

Cross-platform RPC with large messages


What if domains and codomains in categories were not unique?

Question: I were updating my knowledge of category theory, which were generally obtained from the books treating categories not as their primary subject. So, I decided to read books on the subject.
By comparing these texts I discovered that there are several different approaches regarding definition of category:
$\textrm{(CD.a)}$ For category $\mathcal{C}$  with objects $A,B,C,D \in \mathcal{O}_{\mathcal{C}}$ its hom-classes are $\mathcal{M}_{\mathcal{C}}(A,B)$ and $\mathcal{M}_{\mathcal{C}}(C,D)$ are disjoint whenever $A \neq C$ or $B \neq D$.
$\textrm{(CD.b)}$ Each hom-class $\mathcal{M}_{\mathcal{C}}(A,B)$ consists of triples $(A,B,f)$ with only last item $f$ bearing new intrinsic information.
Note that $\textrm{(CD.b)} \Rightarrow \textrm{(CD.a)}$. And it seems that the role of this assertion is to define $\mathrm{dom}$ and $\mathrm{codom}$ as viable maps from  class of all the morphisms of $\mathcal{C}$ to the $\mathcal{O}_{\mathcal{C}}$. For example, In case $\textrm(CD.a)$ one can define
$$
\mathrm{dom}  (A,B,f) = A \kern 1pc \mathrm{codom}(A,B,f) = B.
$$
In my fairly limited practice I always selected objects first and morphisms later as elements of corresponding hom-sets, so I rarely addressed $\mathrm{dom}$ and $\mathrm{codom}$ as maps directly. This raised some question for me:

Can  property $\mathrm{CD}$ (in every form)  be painlessly dropped from definition of category?
Is it useful to have $\mathrm{dom}$ and $\mathrm{codom}$ to be well-defined as maps to develop any useful theorems and tools in category theory? Or фre they just common parts of mathematical lingo?
Have anyone studied objects which are like categories but have $\mathrm{CD}$ dropped from the definition?

If property $\mathrm(CD)$ is dropped then $\mathrm{dom} $ and $\mathrm{codom}$ can be defined at least for small categories as sets:
$$ \mathrm{dom}(f) = \{ A \in \mathcal{O}_{\mathcal{C}} : \exists B \in \mathcal{O}_{\mathcal{C}}  : f \in \mathcal{M}_{\mathcal{C}}(A,B)   \}, $$
$$ \mathrm{codom}(f) = \{ A \in \mathcal{O}_{\mathcal{C}} : \exists B \in \mathcal{O}_{\mathcal{C}}  : f \in \mathcal{M}_{\mathcal{C}}(B,A)   \}. $$
I can present examples where this notion is not redundant:
(1)
Consider category $\mathsf{TOP}$ with topological spaces as objects and continuous maps as morphisms. Then $\mathbb{R}$ has multiple corresponding objects in this category, say $(\mathbb{R},a)$ and $(\mathbb{R},b)$ being real numbers with normal ans discrete topologies $a$ and $b$ respectively. And Let $\mathbf{1} = \{1\}$ be a one-point set. Then the constant map  $1 : \mathbb{R} \to \{1\}$ belongs both to $\mathcal{M}_{\mathsf{TOP}}((\mathbb{R},a),\mathbf{1})$ and $\mathcal{M}_{\mathsf{TOP}}((\mathbb{R},b),\mathbf{1})$.
(2)
Consider category $\mathsf{SET}$ with objects are sets and morphisms are maps defined along with ZF; I. e. $f : A \to B$  is a subset of $f \subset A \times B $ with the property that $$\forall a \in A \; . \; \exists b \in B : (a,b) \in f \quad \& \quad \forall b,c \in B \; . \; (a,b),(a,c) \in f \Rightarrow a = b.$$
Let $A,B$ are sets and $\emptyset \neq S \subsetneq B$. Then, if $f \in \mathcal{M}_{\mathsf{SET}}(A,S)$ it must also  be present in $\mathcal{M}_{\mathsf{SET}}(A,B)$. So $f$ has nonsingular codomain.
Comment: We can consider the constant map $\mathbb R\to\{1\}$ as $Gu=Gv:\mathbb R\to\{1\}$ in category $\mathbf{Set}$ where $G$ denotes the forgetful functor $\mathbf{Top}\to\mathbf{Set}$ and $u$ is the arrow $(\mathbb R,a)\to\mathbf1$ and $v$ is the arrow $(\mathbb R,b)\to\mathbf1$ both in $\mathbf{Top}$, and distinct. So your example does not convince me that the notion is not redundant.
Comment: @drhab , of course,  but this depends on the definition of redundant.
Comment: @drhab ; additional example was added. It still weak as it relies on underlying  set theoretic formalism.
Comment: If you forget about codomains in $\mathsf{SET}$, all morphisms are now epimorphisms, i.e., all maps of sets are surjective now. You probably don't want that. You also need a notion of codomain to define things like cokernels in abelian categories etc.
Comment: Here is a [related question](https://math.stackexchange.com/questions/651464/is-it-necessary-for-the-homsets-to-be-disjoint-in-a-category).
Comment: @Christoph , thanks for the comment. I think, that in this case property of being epimorphism or cokernels can be defined with respect to a pair of objects $(A,B)$ such that $f : A \to B$. For example, $f$ is an epimorphism of $A$ and $S$, if $S = \mathrm{Im}
 \; f$, but $f$ is not an epimorphism of $A$ and $B$. simmilirarly, you can define cokernel of $f$ with respect to domain $A$ and codomain $B$.
Comment: @drhab , thanks, this is the same question indeed.
Comment: Here's another related question: https://math.stackexchange.com/q/2462477/19542 (I remembered answering something like this a while ago)
Comment: @CliveNewstead ; Thanks this is indeed related.
Comment: A relevant fact is that if $S$ is a set, also viewed as a discrete category, then there is an equivalence $\mathbf{Set}^S \equiv \mathbf{Set}/S$. In the case of considering the definition of a small category, this relates the notion of an arbitrary function $\hom : \mathbf{Ob}(C) \times \mathbf{Ob}(C) \to \mathbf{Set}$ (i.e. where the images aren't required to be disjoint) to the notion of a family $\mathbf{Ar}(C) \xrightarrow{(\mathrm{dom}, \mathrm{codom})} \mathbf{Ob}(C) \times \mathbf{Ob}(C)$. The two approaches are indistinguishable if you respect equivalences!
Answer: You can define the notion of category in any of the language of First-Order Logic with Dependent Sorts (FOLDS) or dependent FOL (DFOL) or as a generalized algebraic theory or in a dependent type theory in such a way that there are no $\mathsf{dom}$/$\mathsf{codom}$ operations and asking whether $\mathsf{Hom}(A,B)$ is or is not disjoint from $\mathsf{Hom}(C,D)$ is a  meaningless question. In particular, in these formalizations there is no notion of equality of objects. (There is still a notion of equality of arrows, but we can only ask about it for arrows that are declared to be of the same hom-sort/hom-type.)
This isn't just a neat trick. FOLDS, in particular, was designed to achieve this. Or rather, FOLDS was designed to be a formal language in which one could do category theory and the principle of equivalence (well, the principle of isomorphism) would automatically hold. That is, every property you can state in FOLDS, say, is isomorphism invariant: if the property holds for one object, it holds for all isomorphic objects. Equality of objects is clearly not isomorphism invariant, and so it is not a predicate you can formulate in FOLDS.
To answer your question, yes we can drop CD and the notion of $\mathsf{dom}$ and $\mathsf{codom}$ operations entirely, but we need to restrict ourselves to a language where they are meaningless. But restricting ourselves to such a language is a good thing because properties outside this language do not satisfy the principle of isomorphism (and such properties are often referred to as "evil"). Since strict categories appear to be a thing, I assume they are sometimes useful/necessary. (Normal) FOL and set theory don't really provide a way to formalize the notion of category without including this extraneous structure either explicitly or implicitly, hence the existence of FOLDS and co. In practice, we just informally restrict ourselves (for the most part) to isomorphism invariant properties, so the fact that we are allowed in usual formalizations to test equality of objects and that $\mathsf{dom}$/$\mathsf{codom}$ exist are usually ignored. This is similar to how we simply don't ask questions like is $\mathbb Q\subseteq \arcsin(1)$ even though they are technically legitimate questions in a set-theoretic context.
Comment: This is exactly what I wanted to get. IMHO it is natural to see $\mathrm{Hom}(A,B)$ as types. However, I don't know if this approach works well for establishing basic categories of topology and algebra which are generally presented in set-theoretic context.


Differences between "if in" and "if or if in"; looking for explanation

Question: I get different results if I write "if X or y in var" than if I write "if x in var or if y in var."  Why is that?  I cannot find any documentation on this anywhere.
If, using the following Python3 code, I enter "rrrr" I get "whoohoo" not "WTF."  Only if I remove the code "elif "read" or "road" in choice:    print("whoohoo")," do I get "WTF."  Can anyone enlighten me on what I'm missing about the difference in the two?  As I say, I've searched broadly on the net and can't find anything on this.  I'm expecting them both to return the same thing but they do not.
var = "read", "road"
print(var)
print("what is your choice?")

choice = input("> ")

if "raed"  in choice or "raad" in choice:
    print('Not Good')

elif "read" or "road" in choice:
    print("whoohoo")

elif "read" in choice or "road" in choice:
    print("excellent")

else:
    print("WTF")

Comment: The first is equivalent to `if (x) or (y in var)`: it checks if `x` is a truthy value.
Answer: This will check if x has a truthy value assigned to it (i.e. not empty), or else, if var contains the value for y
if x or y in var

This will check if var contains the value for x, or else, if var contains the value for y
if x in var or if y in var

Comment: @ShadowRanger updated


Como declarar valores nulos em C

Question: Meu problema é o seguinte estou criando um loop while que não pode receber valores menores ou iguais a zero, e gostaria de declarar também que não pode receber valores vazios para o programa forçar o usuário a digitar um número e não o enter sem nenhum campo no scanf().
  printf("Digite o valor da posicao X:");
    scanf("%d",&x);
    //faz a verificação se o numero é 0 ou < 0
  while (x <= 0){
    printf("0 ou < 0 nao forma um triangulo por favor digite novamente a medida X\n");
    scanf("%d",&x);
  }

Quando o usuário apenas digita enter ele aceita sem dado nenhum no console, no caso queria que o sistema aceitasse apenas se um numero estivesse digitado no console.
Comment: Precisa explicar melhor, de preferência com que código está tendo problema. Nulo é uma coisa, vazio é outra, depende do tipo de dado que está lidando. Nulo é 0, mas o `scanf()` não lida com nada que possa ser nulo. Então a pergunta tem premissas erradas e está confusa, precisa especificar melhor pra podermos ajudar.
Comment: Fiz a alteração.
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo
Answer: Acredito que seja isto que deseja. Você verifica se a entrada foi válida, a função scanf() provê isto como retorno, é só ler a documentação. E também pode validar a entrada do dado com o valor que desejar. Tudo isso em um simples laço.
#include <stdio.h>

int main(void) {
    int x;
    while (scanf("%d", &x) != 0 && x <= 0) printf("0 ou < 0 nao forma um triangulo por favor digite novamente a medida X\n");
    printf("%d", x);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

Como declarar valores nulos em C


Show that $Z(v,f) \oplus Z(w,f) = Z(v+w, f)$ if minimal polynomials are coprime.

Question: I am currently learning Linear Algebra and just can't finish this one exercise, at least partially...
We are given some field $F$ and the normal vector space $V = K^n$. By $Z(A,v)$ we denote $\left\langle v, Av, A^2v, A^3v,\dots\right\rangle$ where $A$ is just some $n \times n$ matrix. As an added condition we are given that $m_v$ and $m_w$ are coprime with $m_v$ being the normalised polynomial of lowest possible degree such that $m_v(A)v = 0$.
Now the actual task is to show that $Z(A,v) \oplus Z(A, w) = Z(A, v+w)$.
I was already able to show the inclusion $Z(A,v) + Z(A, w) \supseteq Z(A, v+w)$, which was pretty easy and to show that $Z(A, v) \cap Z(A,w) = \{0\}$ I used that $m_v$ and $m_w$ are coprime.
I tried approaching the other inclusion of $Z(A,v) \oplus Z(A, w) \subseteq Z(A, v+w)$ similary by choosing some $x \in Z(A,v) \oplus Z(A, w)$. Then we know that there is a single and clear way to write that as $$x = \sum_{n \in \mathbb{N}} A^n(\lambda_nv+\mu_nv).$$
And at this point I dont see how I could show $\sum_{n \in \mathbb{N}} A^n(\lambda_nv+\mu_nv) \in Z(A, v+w) = \left\langle v+w, A(v+w), A^2(v+w), A^3v,\dots\right\rangle$ as the left hand side seems way more general than the right hand one. I guess I have to use that $m_v$ and $m_w$ are coprime somewhere here maybe, but I lack a concrete idea...
Already thanks for any help in advance! :)
Answer: The general element of $Z(A, v) + Z(A, w)$ is of the form $p(A)v + q(A)w$, where $p$ and $q$ are polynomials which matter up to multiples of $m_v$ and $m_w$ respectively. We wish to show that this is of the form $r(A)(v+w)$ for some polynomial $r$. Observe that $r(A)(v+w) = r(A)v + r(A)w$. Thus, we wish to find some polynomial $r$ such that $r \equiv p \bmod{m_v}$ and $r \equiv q \bmod{m_w}$. Do you see how to proceed?
Comment: Firstly thanks already! Sorry I am already quite tired, so sorry if I am writing nonsense... As we know that $m_v$ and $m_w$ are coprime we can(?) conclude that $r = p \cdot q$, at least it should be true that $pq \equiv p \bmod m_v$ and $pq \equiv q \bmod m_w$. Is that true or at least the right direction? Haha... But it certainly isn't true that $p(A)q(A)v + p(A)q(A)w = p(A)v + q(A)w$, so I don't think my "idea" is right...
Comment: That's not quite right, but here's a concrete example. Let's say that $m_v = x - 3$ and $m_w = x - 4$. Let's also say that $p = x^2 - 2$ and $q = x^2 - 1$. Now, you wish to have $r(x) \equiv x^2 - 2 \pmod{x - 3}$ and $r(x) \equiv x^2 - 1 \pmod{x - 4}$. First, do you see why this is equivalent to $r(3) = 7$ and $r(4) = 15$? Do you see how to construct such a polynomial? In general, this phenomenon is called the Chinese Remainder Theorem: https://en.wikipedia.org/wiki/Chinese_remainder_theorem#:~:text=In%20mathematics%2C%20the%20Chinese%20remainder,are%20pairwise%20coprime%20(no%20two


Trying to Use AppleScript to Convert .xls and .xlsx to .txt (Tab Delimited), Needs Fixing

Question: I copied this from an answer I got from another thread. I am trying to convert ~300 .xls and .xlsx files to tab delimited. They are all in the same folder. If anyone knows a better way, please let me know.
property type_list : {"XLS6", "XLS7", "XLS8", "XLSX"}
property extension_list : {"xls", "xlsx"}

on open these_workbooks
repeat with k from 1 to the count of these_workbooks
    set this_item to item k of these_workbooks
    set the item_info to info for this_item

    --this if statement tests to make sure the items you're converting are Excel spreadsheets and not folders or aliases
    if (folder of the item_info is false) and (alias of the item_info is false) and ((the file type of the item_info is in the type_list) or the name extension of the item_info is in the extension_list) then

        tell application "Finder" to open this_item

        tell application "Microsoft Excel"
            --this just tacks on ".txt" to your file name
            set workbookName to (name of active workbook & ".txt")
            --save the current open workbook as a tab-delimited text file
            tell active workbook to save workbook as filename workbookName file format text Mac file format
            close active workbook saving no
        end tell
    end if
end repeat
end open

on run
    display dialog "Drop Excel files onto this icon."
end run

All this does is open a dialog box and does nothing. Even though it's meant to be a droplet, nothing happens when I drag a file to it.
Comment: This script is using `Droplets` (http://macscripter.net/viewtopic.php?id=24772). Save it as an executable application and then drop the files onto it (That's what that display dialog is trying to tell you)
Answer: In Applescript the run handler gets run when the script or application is run normally. Meanwhile, the open VarName handler gets run when some file or files are dropped onto the icon of the application and the files get set to the variable VarName. The script you posted cleverly places that display dialog in the on run handler to try to help you understand this usage. Instead, save the script as an application and then drop your files onto it.
EDIT:
After a quick test on a Mountain Lion machine that finally has Excel 2011 (I didn't realize how much I'd been overcomplicating):
property type_list : {"XLS6", "XLS7", "XLS8", "XLSX"}
property extension_list : {"xls", "xlsx"}

on open these_workbooks
    repeat with k from 1 to the count of these_workbooks
        set this_item to item k of these_workbooks
        set the item_info to info for this_item

        --this if statement tests to make sure the items you're converting are Excel spreadsheets and not folders or aliases
        if (folder of the item_info is false) and (alias of the item_info is false) and ((the file type of the item_info is in the type_list) or the name extension of the item_info is in the extension_list) then

            tell application "Finder" to open this_item

            tell application "Microsoft Excel"
                --this just tacks on ".txt" to your file name
                set workbookName to (path to desktop as string) & "After:" & (name of active workbook & ".txt")
                display dialog workbookName
                --save the current open workbook as a tab-delimited text file
                tell active workbook to save workbook as filename workbookName file format text Mac file format
                close active workbook saving no
            end tell
        end if
    end repeat
end open

on run
    display dialog "Drop Excel files onto this icon."
end run

Comment: Awesome! Thanks! Is there anything I can add to the script to export to a different folder? Also, how do I change the filename to get rid of the .xls.txt extension and just change it to .txt?
Comment: So this basically spewed everything all over my desktop with the filenames "Document 1", "Document 2", etc. Is there a way to specify the output destination for a whole bunch of files while still keeping their original names?
Comment: @Jart Sorry, I was trying to demonstrate that whatever path you set `workbookName` to will be where it will save it. If you want a different destination, just change that variable (You'll notice right now it just goes to the desktop and then names it "Doc k.txt" where k is the current iteration)
Comment: Err... can you clarify? I'm not good with VBA. Let's say I have a file called spreadsheet.xlsx in a folder on my desktop called "Before". I want it called spreadsheet.txt (as opposed to spreadsheet.xlsx.txt) in tab delimited form in a folder on my desktop called "After".
Comment: @Jart After a bit of finagling, I just updated my answer. This will work for `xls` only, not `xlsx`. For `xlsx` change `text 1 thru -4` to `text 1 thru -5`. I could add an if statement to check for that, but I figured all of your files would probably be the same format so there's no need to add the extra code
Comment: They aren't unfortunately, but that's okay. Now I'm getting a "File 1 Not Found" Error.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/35545/discussion-between-josh-and-jart)


Example of a certain vector space

Question: Let $k$ be a field. I am looking for an example of infinite dimensional $k$-vector space $V$ such that $V\cong V\oplus V$. Also kindly let me know in brief how you've thought about it . Thanks in advance!
Comment: Have you tried anything? Because if by "$\cong$" you just mean isomorphic as vector spaces then absolutely any infinite dimensional $k$-vector space works.
Answer: As Rhys Steele mentioned, two vector spaces over $k$ are isomorphic iff they have the same dimension. For an infinite dimensional $k$-vector space $V$, $\dim(V) + \dim(V)= \dim(V)$ holds (see this question). Therefore $V \cong V \oplus V$.
Let's pick our favourite infinite-dimensional vector space and do this. Mine is $k[X]$, the vector space of polynomials in one variable over $k$.
If you add it with itself, you obtain $k[X] \oplus k[Y] \cong k[X,Y]$, the vector space of polynomials in two variables. All those vector spaces have dimension $\mathbb N$, so they are abstractly isomorphic. But where is the isomorphism? $k[X]$ and $k[X,Y]$ look very different, don't they?
We can choose a basis of $k[X]$ (e.g. the monomial basis) and $k[X,Y]$ (e.g. the basis of all monomial products $1,X,Y,XY,X^2,Y^2,XY^2,X^2Y\dots$). Choosing any bijection between those two basis (which exists, since $\mathbb N \times \mathbb N$ and $\mathbb N$ have the same cardinality, i.e. are both countably infinite) provides a vector space isomorphism, by linear extension.
You might feel a bit cheated now. Aren't $k[X]$ and $k[X,Y]$ different things? They are the same as vector spaces though. The difference is the additional structure on those two vector spaces, since you can multiply polynomials. The multiplication turns $k[X]$ and $k[X,Y]$ into algebras (even graded algebras), and the isomorphism above won't preserve this structure. If you want to fix this, you obtain an example which feels more natural:
Let $V=k[X_1,\dots,X_n,\ldots] = \bigoplus_{i=1}^\infty k[X_i]$ the vector space of polynomials with coefficients in $k$ and countably infinitely many unknowns. Like before, if you take the direct sum of $V$ with itself, you just "double" the unknowns. So $V\oplus V$ is the vector space over twice as many unknowns (which could be called $X_1,X_2,X_3,\ldots$ and $Y_1,Y_2,Y_3,\ldots$). But that's still the same amount of unknowns. A bijection of the set $\{\,X_1,X_2,X_3,\ldots\}$ and $\{\,X_1,Y_1,X_2,Y_2,X_3,Y_3,\ldots\,\}$ gives rise to an algebra-isomorphism (which is in particular a linear isomorphism).

Example of a certain vector space


404 Not Found in API testing

Question: I did my API backend in Laravel
I tested Route::post('register', 'UserController@register');
using http://localhost/cloudengine-sandbox/cloudsandboxbackend/public/api/register
and it work fine.
I have issues when I wanted to test the shortcodes.
api.php
Route::post('register', 'UserController@register');
Route::post('login', 'UserController@login');
Route::get('profile', 'UserController@getAuthenticatedUser');

Route::get('/shortcodes', 'ShortcodeController@index')
    ->name('shortcodes.index');

Route::post('/shortcodes', 'ShortcodeController@store')
    ->name('shortcodes.store');

Route::get('/shortcodes/{shortcode}', 'ShortcodeController@show')
    ->name('shortcodes.show');

Route::put('/shortcodes/{shortcode}', 'ShortcodeController@update')
    ->name('shortcodes.update');

Route::delete('/shortcodes/{shortcode}', 'ShortcodeController@destroy')
    ->name('shortcodes.destroy');

What do I type in the POSTMAN to test each of the shortcodes.
I typed http://localhost/cloudengine-sandbox/cloudsandboxbackend/public/api/shortcodes/show
I expected OK, but gave 404 Not found
Comment: Are you passing the right parameters in your get request in postman? as in Key : shortcode, value : show?
Comment: post  your controller's show method
Comment: Controller show method:   '    public function show(Shortcode $shortcode)
    {
        return $shortcode;
    }'
Answer: if you are writing test cases for your application then
Set your app url in your .env .
APP_URL=http://web.local  //Any url that you  are using.

Because laravel creates a url using APP_URL from the .env.
if you are testing using POSTMAN
Also make sure you pass the header ACCEPT=application/json in the POSTMAN.
Answer: The names on the Routes are just shortcuts but when accessing them as urls, you still need to use the entire url as defined.
In your example, the url must be:
http://localhost/cloudengine-sandbox/cloudsandboxbackend/public/api/shortcodes/{shortcode}
Replace {shortcode} with a valid id of a shortcode in your database.
Make sure you bind shortcode to your model on the RouteServiceProvider.
Comment: How do I consume it on Angular 7

404 Not Found in API testing


What does this notation mean for the piano?

Question: I saw this in Chopin's Op.25 No.12 etude and was bemused. On the next line, the asterisk reappears on its own. What is this called and what does it mean?
Answer: There are two unrelated things going on here, and I'm not sure which you're asking about.
The small bit of staff with the tiny notes on it is called an ossia. It goes with the staff below it, and gives you an alternative way to play that passage. In this case, the difference looks to be the location of the accented notes (marked with the > symbol), although I can't see enough of the passage to tell if there are any other differences. (Note: I do not know the meaning of the notation "FA:" before the ossia.)
You also reference the "asterisk" symbol. However, this goes with the staff above it, and is a pedal release marking. You can see that it is followed by a cursive "P" at the beginning of the next measure, which indicates where the sustain pedal should be depressed. It is then held until the next asterisk.
Comment: You could have provided fuller information. Which edition is this? Which bar number (or "bottom of 1st page"). I guess the only difference is the different accent positioning; probably "FA" is the name of a particular edition, and this ought to be mentioned in a note somewhere. I have the Cortot edition, and in a different place (bars 76 and 78) he gives the same possibility with extra accent marks in parenthesis, but no comment explaining this. To a certain extent, you give your own interpretation...
Comment: Oh, of course it's a pedal release mark. I would have known that if I saw it on its own; I thought it was part of the ossia in this context. Thanks.


Setting up SFTP users that are jailed to their home directories with Chef

Question: I'm hoping someone can help me figure out how to chroot jail users to their home directories for SFTP with Chef. I've tried multiple SSH cookbooks and Googled for an answer for several days with no luck (though honestly it's possible I just don't know what to search for).
What I've done so far is setup a data bag for users that successfully creates the users, assigns them to an sftponly group, and creates their home directory in a domain.tld format.
My problem is that once I try to connect via SFTP I can successfully be placed in the user's home directory, but can simply move up to either the parent directory or the root directory of the server. I've setup SFTP before, it was full of problems but I finally got it to work. I'd like to be able to just have all of the setup handled by Chef though.
This is what I need to know:

Which Chef cookbook should I use?
What attributes / settings do I need to specifically set to Chroot jail a user in the sftponly group to their home directory while still allowing the root user SSH access?
Answer: The final step for SFTP chroot is after creating a sftponly group and configuring openssh is ensuring the user's $HOME is owned by root. If the user owns their home directory, the sftponly configurations will not be applied.
Next, you can sudo mkdir a directory within that user's $HOME and ensure the user owns that directory—this is where they can upload files. I typically add a public directory within the root-owned $HOME directory where other users and processes can drop files.


Logistic regression using rms: calculate odds ratio and p-value for specific unit of change

Question: I try to calculate the odds ratios and p-values for continuous and categorical predictors at a specific unit of change (e.g. odds ratio for a change of 10 years, not 1 year) of a multiple logistic regression model.
library:
library(tidyverse)
library(rms)

my test data:
data <- tibble(age=c(50,49,13,20,100,80,25,110,25,25,13,54,23,45,27,87,55,22),
        dose=c(400,800,800,200,100,450,400,432,543,3245,654,554,64,356,543,321,356,432),
        class=c(0,1,1,0,0,1,0,1,1,1,0,0,0,1,0,1,0,1))

my analysis:
dd <- datadist(data);  options(datadist='dd')
g <- lrm(class ~ age+dose, data=data)

What I tried:
From https://stackoverflow.com/questions/24627237/convert-odds-ratio-of-unit-change-to-whole-range I learned that I could calculate the odds ratio for a specific unit of change with:
#calculate odds ratio of age for a multiple of 10 years (10-units-change)
unit.change=c(10)
exp(coef(g)["age"]*unit.change)

I do not know how to calculate a p-value for this odds ratio now.
print(g)

gives me p-values for the beta coefficients, can I use these p-values?
From https://www.rdocumentation.org/packages/rms/versions/3.1-0/topics/summary.rms I learned that summary.rms calculates inter-quartile range effects. Can I somehow use summary.rms to calculate odds ratios at specific unit of change (and corresponding p-values) for every predictor? (my real data has multiple categorical and continuous predictors...).
Comment: (1) This is not multivariate regression: it's *multiple* regression.  (2) It's unclear what you mean by a "p-value for this odds ratio" (for a ten-year change): could you tell us what hypothesis you are testing and show us how it differs from the usual null hypothesis that the coefficient is zero?
Comment: Isn't that precisely the null hypothesis that is automatically tested by the software output?
Comment: Thank you for your comment. I corrected (1). Regarding (2) I would like to give a p-value for the odds ratio that I calculate from the coefficient, is it the same as for the underlying coefficient? I would like to calculate an odds ratio that reflects not an 1-unit-change but a 10-unit-change for years.
Comment: There's no such thing as a p-value for a parameter.  P-values relate to *hypothesis tests.*  In order to explain what you're looking for, you need to tell us what you are testing.
Comment: The null hypothesis is that the OR is 1
Comment: I think so. I wondered if the p-values of the b coefficient of a 1-unit change is also valid to the OR of a 10-unit change that is calculated from the b coefficient
Answer: Yes, the p-value for the effect of a 10-unit change in the covariate (years in this case) is the same as that for the effect of a 1-unit change.  Here's the demonstration: the p-value for the original question (effect of a 1-unit change) is $P(|Z|>\frac{\hat\beta}{\sigma_{\hat\beta}})$, i.e. the tail area of the Normal distribution beyond the ratio of (estimated change)/(standard error of estimated change).  The estimated effect of a 10-unit change in the covariate is $10\hat\beta$, but the standard error of this change is $10\sigma_{\hat\beta}$; the changes cancel out and we end up with the same p-value as before.
In the case of a logistic regression you will be doing tests on the log-odds ratio scale [or equivalently on the scale of additive changes in the log-odds], but the concept is the same.


Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'com.sportswin.soa.spark.controller.ISparkGameUserController' method

Question: Today when I start the spring boot project, shows error like this:
<code>2022-01-21 14:52:04.659 ERROR 1 --- [           main] o.s.boot.SpringApplication               : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webMvcRequestHandlerProvider' defined in URL [jar:file:/root/soa-spark-service-1.0.0-SNAPSHOT.jar!/BOOT-INF/lib/springfox-spring-webmvc-3.0.0.jar!/springfox/documentation/spring/web/plugins/WebMvcRequestHandlerProvider.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'com.sportswin.soa.spark.controller.ISparkGameUserController' method
public abstract com.sportswin.soa.misc.contract.response.Response com.sportswin.soa.spark.controller.ISparkGameUserController.sparkGameUserFirstVote(com.sportswin.soa.spark.contract.request.vote.SparkGameUserVoteRequest)
to {POST /spark/game/user/vote/first}: There is already 'sparkGameUserController' bean method
public com.sportswin.soa.misc.contract.response.Response com.sportswin.soa.spark.controller.impl.SparkGameUserController.sparkGameUserFirstVote(com.sportswin.soa.spark.contract.request.vote.SparkGameUserVoteRequest) mapped.
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769) ~[spring-beans-5.1.13.RELEASE.jar!/:5.1.13.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:218) ~[spring-beans-5.1.13.RELEASE.jar!/:5.1.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1340) ~[spring-beans-5.1.13.RELEASE.jar!/:5.1.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1186) ~[spring-beans-5.1.13.RELEASE.jar!/:5.1.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.13.RELEASE.jar!/:5.1.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.13.RELEASE.jar!/:5.1.13.RELEASE]
</code>
I check the code, and did not found the Controller two method define with the same path. this is the rest controller method define:
<code>    @GetMapping("/vote/first/{gameId}")
    Response<List<SparkGameUserVoteFirstResponse>> queryFirstVoteSparkGameUser(@PathVariable(value = "gameId") Long gameId);

    @PostMapping("/vote/first")
    Response sparkGameUserFirstVote(@RequestBody  @Valid SparkGameUserVoteRequest request);
</code>
why did this happen? what should I do to fix it?I feel like the controller initial twice.
Comment: You might try to add a debug or a logger to this controller constructor and verify that you are initializing it once. Secondly check for all RestMappings and verify there are no duplications. Could you also post controller class def with annotations?
Answer: Try running a global text searching on text "/vote/first"? (Based on error msg you may have an api prefix "/spark/game/user" on this controller. Maybe somewhere else also produce the contacted api "/spark/game/user/vote/first")


mytrack.duration retorna NaN

Question: Esta retornando NaN, alguém tem uma solução?
Segue o código:

    <title>teste</title>
    <meta charset="utf-8"/>

<audio id="mytrack" controls>
        <source src="Jinxed.mp3" type="audio/mp3">
</audio>

Answer: Tente adicionar o evento loadeddata, exemplo:
mytrack.addEventListener("loadeddata", function() {
    alert(this.duration);
});

Da forma que você está tentando fazer, o script executa antes do áudio ter carregado, por isso retorna NaN. Com o evento loadeddata ele executa quando os dados estiverem disponíveis.
HTML Audio/Video DOM loadeddata Event
Exemplo JSFiddle
Comment: Retornou NaN tanto aqui no meu código, quanto no seu no JSFiddle? Será que é o navegador?
Comment: @AsuraKhan testei novamente e esta retornando `NaN`, mais é porque por algum motivo o arquivo mp3 que coloquei como exemplo no fiddle não esta sendo localizado. :/
Comment: no meu caso ele localiza o audio, mas não funciona e os códigos estão idênticos. São 2 linhas afinal.
Comment: @AsuraKhan veja a edição, se dessa forma funciona para seu caso.
Comment: Agora funcionou, mas eu não entendi nada. Conheço o eventlistener e seu uso com callback, mas esse this aí..eu sou meio burro com "this" . Ficarei agradecido se me explicar. Inclusive do porquê não funcionar do outro método.
Comment: @AsuraKhan veja a edição com a explicação.
Comment: Valeu muito obrigado.

mytrack.duration retorna NaN


QPX Express API - Lista de voôs

Question: Estou tentando utilizar o QPX Express API para buscar lista de vôos, na documentação tem como passar os argumentos, mas não sei como usar, por exemplo:
Documentação:

The simplest way to try out this API is to send it a POST request with curl. For >example, create a file named request.json with the following content (replace each >instance of YYYY-MM-DD with a date, which can be up to a year in the future.):

JSON:
{
  "request": {
    "passengers": {
      "adultCount": 1
    },
    "slice": [
      {
        "origin": "BOS",
        "destination": "LAX",
        "date": "YYYY-MM-DD"
      },
      {
        "origin": "LAX",
        "destination": "BOS",
        "date": "YYYY-MM-DD"
      }
    ]
  }
}

A documentação diz isso:

Then execute the following command from within the same directory as the above >request.json file. (As explained in Prerequisites, you must first obtain an API key.)
curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=your_API_key_here

Onde executar este código?
Answer: SOLUÇÃO
consegui depois de muita pesquisa pegar a lista de voôs usando qpxExpress
<?php

$url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=SUA-API-KEY";
$data_string = '{
                  "request": {
                    "passengers": {
                      "adultCount": 1
                    },
                    "slice": [
                      {
                        "origin": "MCO",
                        "destination": "GRU",
                        "date": "2015-01-23"
                      }
                    ],
                    "solutions": 2
                  }
                }';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch); // resultado!!!!
?>

obrigado!
Answer: Basicamente pra testar o QPX Express API usando curl você deve seguir esses passos:

Criar um arquivo JSON chamado request.json com o conteúdo que você colocou na questão e salvar em um lugar que você lembre depois, lembrando que a documentação pede pra você alterar a data:

No meu caso eu coloquei a data de ida para (20 de Janeiro de 2015) e a data de volta para (27 de Janeiro de 2015)

Acessar via terminal/prompt o local onde você salvou o arquivo criado e executar o commando:

curl -d @request.json --header "Content-Type: application/json"
  https://www.googleapis.com/qpxExpress/v1/trips/search?key=sua-API-Key

Como resposta você verá no terminal um código JSON com bastante informação a respeito do voo, segue trecho da resposta da API:

Considerações:

Você consegue uma API Key seguindo este tutorial no próprio site da
API.
Outra maneira de testar a API (sem usar API Key e sem usar curl) é
acessando a DEMO que a API disponibiliza.
Comment: mas como posso pegar esses dados em json
Comment: tem como eu fazer usando PHP?

QPX Express API - Lista de voôs


Joint Markov Chain (Two Correlated Markov Processes)

Question: I have two Markov Chains, and they exhibit some correlation between them. For instance, when Chain A moves to state i, there is a high likelihood that Chain B moves to state j. How would I go about modeling this behavior?
Answer: Maybe you can try hidden Markov models: modeling two chains as two observation sequence, and there is a hidden state sequence such that at certain state, chain A has high probability to be i while chain B has high probability to be j.


Proving a certain topology to be non-Hausdorff

Question: I'm doing this exercise and I don't know how to attack the second part:

Let $\tau$ be a topology on $\mathbb{N}$, with $\tau=\{\emptyset\}\cup\{\{0,1,2,...,n\}|n\in\mathbb{N}\}\cup\{\mathbb{N}\}$.
$i$) Prove that $(\tau,\mathbb{N})$ is not Hausdorff.
$ii$) Prove that the sequence $\{1,2,1,2,1,2,1,...\}$ is not convergent to $0$ and $1$, but it does to any other natural number (it converges to $2$, to $3$, to $4$, ...)

I've tried to solve those 2 parts:
$i$) Let $m,n \in \mathbb{N}$, $n\neq m$. Suppose, wlog, that $n<m$. $n\in I_n=\{0,1,2,3,...,n\}$ and it's the smallest open set that contains $n$. $m\in I_m=\{0,1,2,3,...,m\}$ and it's the smallest open set that contains $m$. But $I_n\subset I_m$. So $(\tau,\mathbb{N})$ is not Hausdorff.
I don't know if that try is correct. And how we do attack the second part? I've been trying to find an effective methid to prove that but I'm not getting anywhere.
Thanks for your time.
Comment: Do you know the definition of "convergence" in a general topological space? You can work straight from the definition here.
Comment: @MeesdeVries that's what I don't know, the definition of convergence in a general topological space.
Comment: You can find a definition [here](https://proofwiki.org/wiki/Definition:Convergent_Sequence/Topology), but really the definition should also be somewhere in the material from which you got this question.
Answer: i) It is not Hausdorff because every open set that contains $1$ also contains $0$.
ii) The sequence does not converge to $0$ because $\{0\}$ is an open set that contains $0$ but no term of the sequence. It doesn't converge to $1$ because $\{0,1\}$ is an open set that contains $1$ for which it is not true that contains all but finitely many terms of the sequence. On the other hand, if $n\in\mathbb{N}\setminus\{0,1\}$ and if $A$ is an open set containing $n$, then $A\supset\{0,1,\ldots,n\}$ and therefore every term of the sequence belongs to $A$. So, the sequence converges to $n$.


Uploading an empty file to S3 with Java

Question: Getting error when I try to stream empty data into S3.
Below is the error:

java.lang.RuntimeException:
  java.lang.RuntimeException:
  java.lang.RuntimeException:
  shaded.com.amazonaws.services.s3.model.AmazonS3Exception:
  The XML you provided was not well-formed or did not validate against our published schema
  (Service: Amazon S3; Status Code: 400; Error Code: MalformedXML; Request ID: BC194D061F65DC3B), S3 Extended Request ID: RjC6LY05Gj93iQTWAdjL/JcQBrl/NzMt749DOwpVsTJ2YN63A0EQmFWaBXxwHzBo+/a8A3MoP70=

Is there a way to create an empty file in S3 via a Java SDK output stream?
Answer: Absolutely!  With the assumption that you're performing a multipart (per best practices), you'll want to carve out a special case for zero-byte files:
<code>AmazonS3 s3Client = /* your S3 client builder technique */
if ( contentLength == 0 ) {
  s3Client.putObject( bucketName, targetKeyName,
        new FileInputStream( file ), objectMetadata );
} else {
  // Do your multipart upload per usual
}
</code>
Multipart uploads throw an MalformedXML exception when zero parts are requested, but it doesn't explicitly call this out in the message.  It's also possible that another portion of your request is malformed as well, such as if the ObjectMetadata is corrupted, though usually you'll get a clearer exception message in those cases.

Uploading an empty file to S3 with Java


Command to start nodejs? Server.js and app.js missing

Question: The outdated documentation for drupal integration of nodejs using the nodejs module instructs me to start  nodejs with the command node server.js.
But neither server.js or app.js (replacement to server.js) exists
I can see a file called nodejs.js but running node nodejs.js produces this error;
ReferenceError: jQuery is not defined
    at Object.<anonymous> (/data/disk/o1/static/hood-7.43.1/sites/all/modules/nodejs/nodejs.js:132:4)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

What is the command for starting nodejs?
Comment: `What is the command for starting nodejs?` it's `node server.js`
Comment: Follow this [for Drupal 8](https://www.youtube.com/watch?v=znr0aFOlDnI) OR [for Drupal 7](https://www.youtube.com/watch?v=u1sxDaH3Z-U). They are different, so make sure you follow the correct version.
Answer: If you're downloading the app from github directly, follow these instructions:

Download the archive
Extract to a folder oustide of Drupal's root (this app is separate to your Drupal installation so shouldn't be within)
cd to the folder and run npm install
Run cp nodejs.config.js.example nodejs.config.js, edit the resulting file as required
Run node app.js

Voila, server up and running.
If you're using the npm install drupal-node.js approach, the instructions are a bit unclear. To clarify:

Create a folder outside of the Drupal root
cd to it and run npm install drupal-node.js
Run cp node_modules/drupal-node.js/nodejs.config.js.example nodejs.config.js, edit as required
Run node node_modules/drupal-node.js/app.js to start the server

You should see the same result as the first method.
Comment: app.js does not exist and neither does the node node_modules/drupal-node.js/app.js path
Comment: I tried both of those methods, they both work fine. You might need to start again from scratch
Comment: I'm using the "forever" keep  alive startup service. Would that change things at all?
Comment: Shouldn't do, but consult the docs just in case
Answer: Turns out I had incorrectly upgraded the 7.x-1.10 module incorrectly. From version 7.x-1.1 you can no longer merely overwrite the old module with the new module as the installation process is different.


Changing label on node edit form

Question: I want to change a label/string on a node edit form for a date field.
The label is, "Show end date" - I want to change this to, "Show end date (optional)", but I can't find where this is set anywhere. My guess is that it is some sort of theming change - I took a look at the node_form and saw nothing.
Answer: This code is compatible with Drupal 9. The label is translatable as well.
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function new_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_new_type_form') {
    $form['field_add_date']['widget'][0]['#title'] = t(' Show end date (optional)');
  }
}

Answer: Simply find the adequate form by calling hook_form_alter and letting Devel print out every possible form id:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  dpm($form_id);
}

When you found your edit form id (let's say it's 'xyz_edit') you might inspect the form like so:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id = 'xyz_edit') {
    dpm($form);
  }
}

Now find the label by doubleclicking through the dpm output and replace the label whith your desired text.
Answer: You can easily do this using hook_form_alter(&$form, &$form_state, $form_id) Alter
Hook_form_alter is working before your form shown
Use hook_form_alter in Your site theme template.php file.
Like your theme name is bartik,then use this function their
function bartik_form_alter(&$form, &$form_state, $form_id)
{
//Firstly get form id then use below code

if($form_id=='Your_edit_form_id'){
//here print $form and chek which field label you want to change and then alter that field //like

$form['date'][#label]='Date Field(optional)';
}

}

may this will help you.

Changing label on node edit form


Azure DevOps - two dependent YAML pipelines in one repository

Question: I have two .yml files in my repo. One for build, one for deployment. The main reason why I would like to keep build separate from the deployment is that I also would like to store variables for environments in my repo, e.i. in variables-dev.yml and variables-prod.yml files. So there is no need to create a new build every time (which includes running tests, docker image build etc.).
The file build.yml:
trigger:
  paths:
    exclude:
      - build.yml
      - deploy.yml

stages:
- stage: build
  jobs:
  ...

And the deploy.yml, which I want to be triggered only on the completion of the build pipeline. That's why I add the first exclusion of all paths, but add one on pipeline resource.
trigger:
  paths:
    exclude:
    - '*'

resources:
  pipelines:
    - pipeline: build
      source: build
      trigger:
        branches:
          include:
          - '*'

stages:
- stage: dev
  variables:
    - template: variables-dev.yml

  jobs:
  - deployment: deploy_dev
    environment: 'dev'
    strategy:
      runOnce:
        deploy:
          steps:
            ...

- stage: prod
  dependsOn: dev
  variables:
    - template: variables-prod.yml

  jobs:
  - deployment: deploy_prod
    environment: 'prod'
    strategy:
      runOnce:
        deploy:
          steps:
            ...

Unfortunately it does not seem to work. The top trigger blocks lower trigger. And if I remove the top trigger than the deploy pipeline is triggered at the same time with the build one.
Comment: Not get your latest information, is the workaround helpful for you? Or if you have any concern, feel free to share it here.
Answer: you have to start your deploy.yml with trigger: none
trigger: none

resources:
  pipelines:
  - pipeline: ci-pipeline
    source: my-build-pipeline
    trigger:
      enabled: true
      branches:
        include:
          - master

Comment: Should work... this repo also contains working sample yamls, where ci-xxx.yaml is the build, and cd-xxx.yaml would be your deploy.yaml: https://github.com/Azure/phippyandfriends
Comment: @AlexAIT my bad!! You were absolutely right. It did not work for me because it was not merged to master and therefore the modification to the trigger was not working.
Comment: Unfortunately does not work. Does this work for you?
Comment: Hm, alright.. I have a small difference - I do want to trigger the build on all branches. So I put `- "*"` under include :think:
Comment: Found the documentation for this. Check out  `pipeline triggers` here :https://learn.microsoft.com/en-us/azure/devops/pipelines/build/triggers?view=azure-devops&tabs=yaml#pipeline-triggers
Answer: Set your triggers for the second yml to none, then add this setting in the "Triggers" section of the UI. It will stage your builds as you describe
Comment: I would prefer not to use visual editing at all. But thanks!


Transcendental numbers in $\mathbb{Q}_p$

Question: I'm trying to prove that $K((x))/K(x)$ is not an algebraic extension, where $K$ is a field of characteristic $p>0$, and $K((x))$ is the field of fractions of $K[[x]]:=\{\sum_{i=0}^{\infty}a_ix^i\mid a_i\in K\}$.
To make it more concrete, I'm considering the case $K=\mathbb{Z}/p\mathbb{Z}$ and $x=p$, so that we need to find $\tau\in\mathbb{Q}_p$ transcendental in respect to the field extension $\mathbb{Q}_p|\mathbb{Q}$.
I thought about $\tau:=\sum_{i=0}^{\infty}\frac{p^n}{n!}$, which I've checked converges in the $p$-adic metric, but I'm not sure is transcendental or not. It's very tempting to say that $e^p=\sum_{i=0}^{\infty}\frac{p^n}{n!}$, and since $e$ is transcendental, we're done, but I know this probably doesn't make any formal sense. How do I resolve this?
Comment: I do know that the thesis of Bill Adams (Columbia 1964) is entitled "Transcendental Numbers in the p-Adic Domain". So there is research in this question. But is it obvious how to go from a transcendental element of $\Bbb Q_p$ to an element of $\Bbb F_p((x))$ that's transcendental over $\Bbb F_p(x)$?
Comment: Clearly $K((x))$ also has characteristic $p$ when $K$ does, how are you getting the connection to $\Bbb Q_p$ as Professor Lubin notes, this is not an obvious construction, and perhaps there is a mix-up in your terminology?
Answer: My only suggestion would be to try to imitate the ordinary proof of Liouville's Theorem, which can be used to show that $\sum_n10^{n!}$ is transcendental over $\Bbb Q$. This would mean showing that $\sum_n t^{n!}$ is transcendental over $\kappa(t)$, for (say) $\kappa$ a finite field.
Answer: Maybe showing that a certain element is transcendental is not easy. I think that about the same or more work is required as to prove that $e^p\in\mathbb{R}$ is transcendental.
One way to get around is to use the cardinality comparison. This way is not constructive, but we can prove that there is $\tau\in\mathbb{Q}_p$ which is transcendental over $\mathbb{Q}$.
Since $\mathbb{Q}$ is countable, the set of algebraic elements inside $\mathbb{Q}_p$ over $\mathbb{Q}$ is countable. However, the set $\mathbb{Q}_p$ is uncountable. Thus, there must be a transcendental element $\tau\in\mathbb{Q}_p$.
This argument is possible for any countably infinite field $K$.   Set-theoretically stating, the algebraic closure $\overline{K}$ over $K$ satisfies
$$
|\overline{K}|=|K| = \aleph_0 < 2^{\aleph_0} = |K^{\mathbb{N}}|=|K((x))|.
$$


Bootstrapping $R^2$ from a set of experimental data

Question: My question is probably best asked through an example.

Suppose we conduct some designed experiment measuring how three different fertilizers influence the stem lengths on sunflowers, and we repeat the experiment five times (i.e. treat five distinct sunflowers with fertilizer 1, then another five distinct sunflowers with fertilizer 2 and so on).

The best way to go about assessing the effect of fertilizer type is obviously through a general linear model, namely an ANOVA. Suppose we fit our model and obtain an $R^2$ value of $0.91$. Of course, this is quite a high value.
Lets pretend that obtaining those 5 samples was incredibly difficult - so we wanted to make the lives of future experimenters easier by coming up with a confidence interval for the true $R^2$ value.
Would it be appropriate to use bootstrapping techniques on the experimental data to generate a sampling distribution for the $R^2$ value?
Answer: That is essentially what the bootstrap is for: approximating the sampling distribution for a parameter when that is unknown or difficult to derive. Like all methods, it will have difficulties in small samples. There are also situations where the bootstrap principle does not work. But that is for rare cases like estimating extreme values (maxima or minima) or sample mean for distributions whose second moments. This is not likely to be a problem with $R^2$. For more about this including situations where the bootstrap fails see my book Bootstrap Methods: A Practitioner's Guide published by Wiley or Efron and Tibshirani (1993) An Introduction to the Bootstrap, Chapman and Hall.


NullPointerException when trying to getStringArray

Question: Here is the relevent code:
...
Resources res;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.variable);

    res = getResources();
    ...
}

protected void setup() {
    String text = res.getStringArray(R.array.categories)[4];
}

What could be causing this? Logcat:
07-01 13:37:01.988: E/AndroidRuntime(13905): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.centauri.equations/com.centauri.equations.activity.physics.WorkActivity}: java.lang.NullPointerException
07-01 13:37:01.988: E/AndroidRuntime(13905):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at android.app.ActivityThread.access$600(ActivityThread.java:123)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at android.os.Looper.loop(Looper.java:137)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at android.app.ActivityThread.main(ActivityThread.java:4424)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at java.lang.reflect.Method.invokeNative(Native Method)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at java.lang.reflect.Method.invoke(Method.java:511)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at dalvik.system.NativeStart.main(Native Method)
07-01 13:37:01.988: E/AndroidRuntime(13905): Caused by: java.lang.NullPointerException
07-01 13:37:01.988: E/AndroidRuntime(13905):    at com.centauri.equations.activity.physics.WorkActivity.setup(WorkActivity.java:119)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at com.centauri.equations.activity.Categories.onCreate(Categories.java:95)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at com.centauri.equations.activity.physics.WorkActivity.onCreate(WorkActivity.java:34)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at android.app.Activity.performCreate(Activity.java:4465)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
07-01 13:37:01.988: E/AndroidRuntime(13905):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
07-01 13:37:01.988: E/AndroidRuntime(13905):    ... 11 more

Comment: "it seems that res is null" Are you calling setup() before `res = getResources();`?
Comment: Try checking that res and the array aren't null in two if statements first.
Comment: What's WorkActivity line 119?
Comment: @Aidanc "String text = res.getStringArray(R.array.categories)[4];"
Comment: @RaghavSood it seems that res is null for some reason?
Comment: @Sam correct! I didn't realize that my superclass called setup before the onCreate of my child activities.
Answer:
it seems that res is null for some reason

From what you have posted I'll wager the you are calling setup() for you initialize res... Change your code around to this:
res = getResources();
setup();

Comment: Wow, you have lightning fast reflexes Mohit Deshpande!


Are SFP+ "Ethernet" direct attach cables compatible with Fibre Channel?

Question: I'm trying to find some short 8G SFP+ Fibre Channel direct attach cables but they're rare and expensive, can a passive 10G SFP+ direct attach cable marketed for Ethernet be used between two 8G SFP+ Fibre Channel ports?
The connection is between a Dell/EMC VNX5300 to an 8G FC port on a Cisco Nexus N55-M8P8FP Fibre Channel expansion module in a 5548UP Ethernet and FCoE switch.
The answer is yes on an electrical level but from what I can tell there's an EEPROM chip in each pluggable that has metadata in it that hardware uses to determine if the cable is compatible or not, I'm worried that might include some kind of distinction between cables designed for "Ethernet" and cables designed for stuff like Fibre Channel or InfiniBand that hardware from certain vendors will pick up and block me from using the cable.
Does anyone have any experience mixing direct attach cables like this on Dell/EMC and Cisco Nexus hardware?
If it's not possible then I'll just buy a real 8G Fibre Channel direct attach cable and dump the contents of it's EEPROM and flash that onto the EEPROM of an SFP+ Ethernet cable and that should fix it.
Comment: Clarify that. The answer would be no for a SP8 FIBER CHANNEL port - but I doubt you have one, I think you have a SFP8+ port, that is not locked to fiber channel. Not knowing your equipment, check that. Would be imho quite limiting to put up a SFP8+ port and limit it to fiber channel.
Answer: In theory, yes. The base standard SFF-8431 for SFP+ (up to 10 Gbit/s nominally and 11.1 GBd physically) is the same for Ethernet and Fibre Channel.
You could use any 10G SFP+ DAC with 8GFC as well - if you get the host node (switch/NIC/HBA) to accept it. (Q)SFP/+/28 modules identify to their node by contents of an EEPROM that also contains a compatibility matrix.
If that matrix doesn't explicitly list 8GFC, the module is likely rejected. On some devices you might be able to force acceptance by explicit configuration, but rarely so. Of course, reprogramming the EEPROM would solve the problem with most vendors - some vendors use additional identification to prevent simple circumvention of the lock-in mechanism.


$ \sum{ a_n x^n } $ & $ \sum{ b_n x^n } $ converge at radiuses $ R_a, R_b $. What can be told about radius of $ \sum{(a_n+b_n) x^n} $?

Question: Problem: Suppose the power series $ \sum^\infty_{n=0}{ a_n x^n }  $ converges at radius of convergence $ R_a $ and the power series $ \sum^\infty_{n=0}{ b_n x^n }  $ converges at radius of convergence $ R_b $.
What can be said about the radius of convergence of the power series $ \sum^\infty_{n=0}{ (a_n+b_n) x^n }  ~~ $ ?
Hint: Handle the case $ R_a = R_b $ and the case $ R_a \neq R_b $ separately.
Attempt- I didn't really know what to do but I still tried:
If $ R_a \neq R_b $ the sum $ \sum^\infty_{n=0}{ (a_n+b_n) x^n } $ converges iff $ \sum^\infty_{n=0}{ a_n x^n }  $ and $ \sum^\infty_{n=0}{ b_n x^n }  $ converge, hence $ R_{ab} = min\{ R_a , R_b \} $.
Let's now look at a case where we'd have $ R_a = R_b $; Define $ S^{a}_n = \sum^{n}_{k=1}(-1)^k x^k $ ,  $ S^{b}_n = \sum^{n}_{k=1}(-1)^{k+1} x^k $ note that $ R_a = R_b =1  $ . But $ S^{ab}_n = \sum^{n}_{k=1}( (-1)^k + (-1)^{k+1} ) x^k = 0 $ hence $ R_{ab} = +\infty $ .
Question: I feel very lost at this problem, can you please help me as to what explicitly I should do and what to show? how would you approach this problem?
Comment: I think you ought to write your argument for the first case out in a little more detail; that may point you in the right direction for the equality case.  Why does the sum converge only if $|x|\leq \min\{R_a,R_b\}$?
Comment: Can you write $\sum (a_n +b_n)x^n$ as $\sum a_n x^n +\sum b_n x^n $?
Comment: @Tavish Yes, If both power series converge at overlapping radii of convergence.
Comment: @saulspatz The $ \sum (a_n +b_n)x^n $ converges  for a radii smaller or equal to $ min \{ R_a, R_b \} $  since both $\sum a_n x^n $  ,$\sum b_n x^n$ converge for that radii
Comment: That's the if part, not the only if part.
Answer: The point I was trying to make in a comment is this.  Suppose $R_b>R_a$.  Then certainly $\sum (a_n+b_n)x^n$ converges in $|x|< R_a$.  Now suppose that $R_a<|x|<R_b$.  Then $\sum (a_n+b_n)x^n$ can be written as the sum of a convergent series and a divergent one, and hence diverges. Therefore, the radius of convergence can't be any bigger than $R_a$ and we see that $R_{ab}=\min\{R_a,R_b\}$.
When $R_a=R_b$ we still have $R_{ab}\geq R_a$, but we can't produce a point at which we know the sum diverges, as in the above argument.  Outside $|x|\leq R_a$, we have the sum of two divergent series, and we can't say anything definite.  If fact, let $R>R_a$ and let $\sum c_nx^n$ be  a power series with radius of convergence $R$.  Now define $b_n = c_n-a_n$.  By the first part, $R_b=\min\{A_a,R\}=R_a$, but $R_{ab}= R$.  The only thing we can say is that $R_{ab}\geq R_a$.
Answer: Generally you can only say that if $|x| < \min \{R_a, R_b\}$, then $\sum_n (a_n + b_n)x^n$ must converge. However, there are examples where it converges on a wider interval (example $a_n = -b_n$).
Comment: In the case $R_a \neq R_b$, you can say more: the radius of convergence is exactly $R_{ab} = \min\{R_a, R_b\}$, not just $\min\{R_a, R_b\} \leq R_{ab}$.
Comment: @0XLR, Indeed...


php smarty if else loops not working

Question: Basically i am putting some if elses for my array.
{if $array| count eq 0 || $array| count lt 10}

equal to 0, less than 10

{/if}
{if $array| count gte, ge 10}

greater than or equal to 10

{else}

blah

{/if}

Which is not working fine. So what could be the problem?
Comment: Tell us the problem. What do you mean by "not working fine"?
Answer: how about this. you can use gte or ge, but not both.
{if $array| count lt 10}

equal to 0, less than 10

{/if}
{if $array| count ge 10}

greater than or equal to 10

{else}

blah

{/if}

php smarty if else loops not working