Palindromic numbers whose squares are palindromic too

Question: In any base $b>2$, there are infinite palindromic numbers whose squares are palindromic too: for any $n\geq 0$, if $a_n:=1\underbrace{0\dots 0}_{\text{n}}1_b$ then
$a_n^2=1\underbrace{0\dots 0}_{\text{n}}2\underbrace{0\dots 0}_{\text{n}}1_b$.
Is this property true also in base $2$?
Comment: @barak manos Yes. Take $3=11_2$ then $3^2=1001_2$.
Comment: @barak manos Yes, take $4523^2$
Comment: The next values are $11991^2$, $18197^2$ and $141683^2$...
Comment: Have you found even **one** such value of $x>1$ such that both $x$ and $x^2$ are palindromic in base $2$?
Comment: OK, anything else besides that?
Comment: @barak manos Nothing else at the moment.
Comment: Forget $x$, have you found any $x^2$ larger than $1001$ which is palindromic (regardless of whether or not $x$ itself is palindromic)? You only need to check odd squares of course, because the even ones end with $0$. I'm pretty sure that there aren't any, hence the answer to your question is no, even without considering the first part of the statement.
Comment: Yeah, just found it using Python. Good question BTW (already up-voted).
Answer: There are only finitely many base-$2$ palindromes whose square is also a base-$2$ palindrome. Namely, the trivial $0$ (if one counts that as a palindrome), $1$, and the not-quite-trivial $3 = 11_2$.
To see that, let's first look at numbers with few bits set. There's only one number with no bits set, $0$. Whether that should count as a palindrome is left to the reader. There's only one base-$2$ palindrome with exactly one bit set, namely $1$. For base-$2$ palindromes with exactly two bits set, we easily see that $3$ is the only one whose square is also a base-$2$ palindrome. For if $x = 2^k + 1$ with $k \geqslant 2$, then $x^2 = 2^{2k} + 2^{k+1} + 1$, and there are only $k-2$ zeros between the first two ones, and $k$ zeros between the last two ones, hence $x^2$ is not a base-$2$ palindrome. Base-$2$ palindromes with exactly three bits set are of the form $x = 2^{2k} + 2^k + 1$, and then $x^2 = 2^{4k} + 2^{3k+1} + 2^{2k+1} + 2^{2k} + 2^{k+1} + 1$. For $k \geqslant 2$, we have $4k > 3k+1 > 2k+1 > 2k > k+1 > 0$, and we again have only $k-2$ zeros between the first two ones, and $k$ zeros between the last two ones in the binary representation of $x^2$. For $k = 1$ we have $x = 7$ and $x^2 = 49 = 110001_2$ which also isn't a base-$2$ palindrome.
So let's finally look at base-$2$ palindromes with at least four bits set. These are of the form $x = 2^k + 2^{k-a} + \dotsc + 2^a + 1$ with $1 \leqslant a < \frac{k}{2}$. Writing $x = 1 + 2^a\cdot u$ with $u$ odd, we see that $x^2 = 1 + 2^{a+1} u + 2^{2a}u^2$, so there are at least $a$ zeros between the last two ones in the binary representation of $x^2$ (exactly $a$ if $a \geqslant 2$, at least $2$ if $a = 1$). At the front, writing $x = 2^k + v$, with $2^{k-a} < v < 2^{k+1-a}$, we see that $x^2 = 2^{2k} + 2^{k+1}v + v^2$, and
$$2^{2k+1-a} < 2^{k+1}v + v^2 < 2^{2k+2-a} + 2^{2k+2-2a}, \tag{$\ast$}$$
so there are at most $a-2$ zeros between the first two ones in the binary representation of $x^2$ and hence $x^2$ is not a base-$2$ palindrome, unless we have carry at the front, i.e. $2^{k+1}v + v^2 \geqslant 2^{2k}$.
From $(\ast)$ it is readily seen that there is no carry at the front if $a \geqslant 3$, so we only need to look at the cases $a = 2$ and $a = 1$.
For $a = 2$, we have $x \equiv 5 \pmod{8}$ and therefore $x^2 \equiv 9 \pmod{16}$, so $x^2$ can only be a base-$2$ palindrome if $2^{2k+1} + 2^{2k-2} \leqslant x^2 < 2^{2k+1} + 2^{2k-1}$. But we have $x < 2^k + 2^{k-1}$ and hence
$$x^2 < (2^k + 2^{k-1})^2 = 2^{2k+1} + 2^{2k-2},$$
thus $x^2$ is never a base-$2$ palindrome when $a = 2$.
Last, we look at the case $a = 1$. If $x \equiv 7 \pmod{8}$, then $x^2 \equiv 1 \pmod{16}$, so there are at least three zeros between the last two ones in the binary representation of $x^2$, but then, since $x$ is a base-$2$ palindrome we have $2^k + 2^{k-1} + 2^{k-2} = 2^{k+1} - 2^{k-2} < x < 2^{k+1}$ and
$$(2^{k+1} - 2^{k-2})^2 = 2^{2k+2} - 2^{2k} + 2^{2k-4} = 2^{2k+1} + 2^{2k} + 2^{2k-4} < x^2 < 2^{2k+2},$$
so the binary representation of $x^2$ starts with two consecutive ones, and therefore $x^2$ is not a base-$2$ palindrome.
Thus we must have $x \equiv 3 \pmod{8}$ and consequently $x^2 \equiv 9 \pmod{16}$, so there are exactly two zeros between the last two ones in the binary representation of $x^2$, whence $x^2$ can only be a base-$2$ palindrome if $2^{2k+1} + 2^{2k-2} < x^2 < 2^{2k+1} + 2^{2k-1}$. This implies $x < 2^{k} + 2^{k-1} + 2^{k-3}$, so the binary representation of $x$ must be $1100\dotsc0011$ (leaving out the verification that $x = 51 = 110011_2$ and $x = 99 = 1100011_2$ don't have base-$2$ palindromic squares). But then $x \equiv 3 \pmod{16}$ and $x^2 \equiv 9 \pmod{32}$, so the binary expansion of $x^2$ ends with $01001$ and we must have $2^{2k+1} + 2^{2k-2} < x^2 < 2^{2k+1} + 2^{2k-2} + 2^{2k-3}$, which in turn implies $x < 2^k + 2^{k-1} + 2^{k-4}$, and thus, since $x$ shall be a base-$2$ palindrome, $x \equiv 3 \pmod{32}$. Now it is easily verified that for $x = 2^k + 2^{k-1} + 2 + 1$, the square is never a base-$2$ palindrome, and thus the last family of candidates is of the form
$$x = 2^k + 2^{k-1} + 2^{k-b} + \dotsc + 2^b + 2 + 1$$
with $b \geqslant 5$ (or in case $k = 2b$ of the form $2^{2b} + 2^{2b-1} + 2^b + 2 + 1$; the form is slightly different, the argument is the same). Writing $x = 1 + 2 + 2^b\cdot u$ with odd $u$, we find that
$$x^2 = 1 + 2^3 + 2^{b+1} + \dotsc,$$
so there are exactly $b-3$ zeros between the third-to-last and the penultimate one in the binary representation of $x^2$. On the other hand, from $2^k + 2^{k-1} + 2^{k-b} < x < 2^k + 2^{k-1} + 2^{k+1-b}$ we obtain
$$2^{2k+1} + 2^{2k-2} + 2^{2k+1-b} + 2^{2k-b} + 2^{2k-2b} < x^2 < 2^{2k+1} + 2^{2k-2} + 2^{2k+2-b} + 2^{2k+1-b} + 2^{2k+2-2b},$$
so there are at most $(2k-2) - (2k+1-b) - 1 = b-4$ zeros between the second and third one in the binary representation of $x^2$, which shows that $x^2$ isn't a base-$2$ palindrome for such $x$.


Trouble with generic function in Swift 3

Question: with the premise that it's the first time I try to understand generic functions, I was wondering what is wrong with the following code (Swift 3):
func isTgreatherthanU<T: Comparable, U: Comparable>(t: T, u: U) -> Bool {
    return t > u
}

(I know it's a stupid function, but it's only meant to understand how to write generic code.)
The compiler says:

Binary operator '>' cannot be applied to operands of type 'T' and 'U'

I thought that, by declaring T and U as conforming to the Comparable protocol, the code should have worked, but I'm obviously doing something wrong... Any idea?
Answer: A value of a Comparable type can be compared with another value
of the same type. In your case, T and U are unrelated
and possibly different types. For example, you cannot compare a String with an Int
even if both types are Comparable.
What you want is
func isTgreatherthanU<T: Comparable>(t: T, u: T) -> Bool {
    return t > u
}

i.e. both arguments are values of the same type T.
Answer: The Swift Standard Library only implements binary operators like > to compare two objects of the same type. T and U conform both to Comparable, but they might be of two different types. Swift considers T and U as different types, no matter which protocols they conform to.
Only something like that would work:
func isTgreatherthanU<T: Comparable>(t: T, u: T) -> Bool {
    return t > u
}


Buscar Cep em um outro banco no Laravel 5

Question: Estou fazendo um sistema de cadastro usando o Laravel 5, criei o esquema cliente, com algumas tabelas, como pessoa, endereco, e-mail, telefone.
acontece tenho um outro banco, chamado cep, onde tem algumas tabelas como rua,  us, bairro, cidade.
Eu sou bem iniciante nesse framework, tudo o que consegui fazer foi imitando outros modelos prontos.
O Cadastro está funcionando, tanto a busca no banco, como a inclusão.
Minha dúvida, como faço para digitar o cep em um html e através desse cep o input no form preencher os campos de rua, cidade, bairro, estado?
Obrigado.
Obs. eu fiz esse select no mysql, deu certo, agora nao sei como implementar no laravel
USE cep;
        SELECT e.endereco_logradouro, b.bairro_descricao, c.cidade_descricao, u.uf_sigla, u.uf_descricao
        FROM endereco e, bairro b, cidade c, uf u
        WHERE e.bairro_codigo = b.bairro_codigo AND
        b.cidade_codigo = c.cidade_codigo AND
        c.uf_codigo = u.uf_codigo AND e.endereco_cep = 'variável'

Comment: É melhor você configurar o banco de dados na sua aplicação e usá-lo em um model específico do  `Laravel`. Ele já tem a sua própria abstração, e isso vai economizar trabalho.
Answer: Você pode configurar mais de um banco de dados no Laravel.
Exemplo:
    'mysql' => array(
      'driver'    => 'mysql',
        'host'      => 'host',
        'database'  => 'database',
        'username'  => 'srvweb',
        'password'  => '...',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => ''
    ),

   'mysql_2' => array(
      'driver'    => 'mysql',
        'host'      => 'host',
        'database'  => 'database_2',
        'username'  => 'srvweb',
        'password'  => '...',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => ''
    ),

Observe que sempre você tem várias configurações no Laravel, para mais de um tipo de SGDB. Não há problemas em configurar mais de um banco para o mesmo SGDB.
Você também deve percebido outro parâmetro chamado default que você deve configurar:
  'default' => 'mysql',

Esse é o banco padrão usado em todos os seus Models.
A minha sugestão é você configurar outro banco e, no model referente ao Cep, você vai definir que ele usará a conexão com outro banco de dados.
    class Cep extends \Eloquent
    {
          protected $connection = 'mysql_2';

          // Outras definições
    }

Daí por diante, basta fazer as consultas com esse Model:
   $ceps = Cep::where('endereco', 'LIKE', 'valor%')->get();

É apenas uma "configurações ilustrativa". Você pode usar a sua criatividade para organizar melhor o seu projeto (e o seu tempo).


Hiding tab request new password

Question: I want to remove the option of request new password from admin section. I have Drupal 8.
Answer: <code>/**
 *Implements hook_form_FORM_ID_alter().
 */

function YOURMODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  unset($form['account']['pass']);
}
</code>
Hope it works.

Hiding tab request new password


How to get node url from Entity Reference field?

Question: We have an ECK Bundle that has an Entity Reference to Article and Basic Page content type. In the twig template we are using the following line below to get the node's nid value and then using that in the twig template to create a link to that node. However, we are getting the following error message while logged out (for logged in users it works fine).
How can we get the node's url for both anonymous and logged in users?
Twig template (eck-entity--component--eck-ref-node--default.html.twig where eck-ref-node is the eck bundle name):
{% set field = entity.field_eck_ref %}
{% set ref_node = field.0['#node'] %}
{% set nodeId = ref_node.nid.value %}
{% set nodeURL = path('entity.node.canonical', {'node': nodeId}) %}

...

Error:

Uncaught PHP Exception
  Symfony\Component\Routing\Exception\InvalidParameterException:
  "Parameter "node" for route "entity.node.canonical" must match "\d+"
  ("" given) to generate a corresponding URL."
Answer: #node is usually part of a render array. Don't know why you named this entity. If it were a real entity object, then you could get the node id directly with .target_id instead of ['#node'].
The problem with keys in render arrays like #node is, they are only included if needed for rendering, so it's not a good idea to write code which fails if it does not exist.
You have to look for the entity object. According to the template doc the entity is named eck_entity:
{#
/**
 * @file
 * Default theme implementation to display an ECK entity.
 *
 * Available variables:
 * - eck_entity: The full ECK entity with limited access to object properties
 *   and methods. Only "getter" methods (method names starting with "get",
 *   "has", or "is") and a few common methods such as "id" and "label" are
 *   available. Calling other methods (such as node.delete) will result in an
 *   exception.
 * - content: All ECK entity items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.
 * - attributes: HTML attributes for the containing element.
 *
 * @see template_preprocess_eck_entity()
 *
 * @ingroup themeable
 */
#}

If this is the template you use, then try something like this to access the field object and the target id of the node:
{% set field = eck_entity.field_eck_ref %}
{% set nodeId = field.0.target_id %}

This works independently of user permissions.
And only build the url when you are sure you have a node id, because otherwise your code still fails if the field is empty.
Comment: the reason i have entity is because when i used twig debug, it was teling me to use eck-entity.html.twig which only came with  {{entity}}

What is the name of the twig that you just added?
Comment: http://cgit.drupalcode.org/eck/tree/templates/eck-entity.html.twig?h=8.x-1.x
Comment: it appears I have another version of ECK because i don't see that in my eck-entity.html.twig file.

however, seeing template_preprocess_eck_entity, i was able to get the answer by using that hook to get the url. I was not able to get the target_id, but using preprocess helped. I shall post answer
Comment: You can do this both in PHP or Twig the same way. This is a question in which language you feel comfortable. But I wouldn't base my code on a template structure which is outdated since a year now, see the commit http://cgit.drupalcode.org/eck/commit/?h=8.x-1.x&id=10bd61eafbc0a1e65c424a512d600384e7b6004a
Comment: Rather than running the risk of #node not displaying, I will do this through the preprocess (see answer below)
Answer: I ended up using template_preprocess_eck_entity() with the following lines of code to get the node URL and passed it into the Twig template. I ended up calling Entity::url to get the canonical URL.
template_preprocess_eck_entity(&$vars) {
$eck = $vars['entity']['#component'];
if($eck->bundle() == 'eck_bundle_name') {
    if($eck->hasField('field_eck_bundle')) {
         $ref = $eck->get('fiedl_eck_bundle'));
         $entRef = $ref->offsetGet(0)->get('entity');
         $node = $entRef->getTarget()->getValue();
         $node_url = $node->url();
         $vars['field_eck_bundle']['node_url'] = $node_url;
    }
}

}//end template_preprocess_eck_entity()

eck-entity--component--eck-ref-node--default.html.twig
{{ field_eck_bundle.node_url }} {# this works #}

Comment: This code is outdated since a year, the eck templates are using the D8 standard pattern now.


Getting fingers to land in the same place

Question: So, I can't seem to get my fingers to land in the same place when changing chords no matter how many times try. As an example, I can play a two-chord change if I practice it for 10 minutes. But I'll come back later or tomorrow and I feel I'm at step one. And this goes on day after day. I can't seem to maintain perfection in the simplest things.
I had a teacher a while ago who said his fingers land in the exact same place every time he plays a C chord.
I'm mostly concerned about playing clean, but I can't even do that slowly much of the time.
Am I just a slow learner or have years of bad practice screwed me up permanently?
Answer: Chords will often have an "anchor note" or a note that is fingered the same between both chords. For example Am and C (open) have a c (second string, first fret) and the e (third string, second fret) in common. Start by switching between two chords such as this that only have 1 finger that moves. Focus on not moving the two fingers that are anchored. This will help. Look for other chord changes that have anchors and practice those.
There will be some chords that you can't do this will but you'd be surprised how many you can. For the ones you can't it is all about repetition. Start slowly so you get the muscle memory correct. If you practice incorrectly it won't help. And practice regularly.
Practice with a metronome. If you are forced to be in time it will help. Go so slowly you can do it perfectly. Then slowly speed up.
Comment: Another pair of chords you could work with are E and Am. They don't share any notes, but they have the same shape. Shifting your hand up or down while maintaining that shape seems like it will be good practice for you.
Answer: I consider myself an intermediate player and I have trouble with this, I think all guitarists do.
First -- you must practice regular. The ease of switching comes with a LOT of work. In time you develop an instinctive muscle memory and you don't have to think about it -- just like learning writing by hand.
Practice going from the E chord to the A chord.
Watch how your fingers move to do this. Practice each finger in the movement separately, then 2 together, then all three. (I assume you are playing the E chord with 3 fingers and the A chord with 3 fingers). Do this whenever you feel frustrated with the whole chords and keep at it.  Try to keep the whole chord clean, all notes sounding --but don't fuss about that too much.
Otherwise just keep going back and forth from E to A.Just getting down these two chords is it for this exercise.
You don't want to be thinking : put your finger here, here and here. At first you do that but in time it becomes automatic, like writing. Until that point just work and stay at it.
BTW these two chords are very common in rock music. Try writing your own "songs" to these two chords  "Play an E, Play an E again, then I go to A". That will help you get the rhythm side as well.
You should then start to add other chords as your skill improves.
It sounds like you have had some lessons. You are at the point where your muscle memory is not fully developed and your brain is thinking as opposed to your fingers.
I think the thing for you is to focus on steady practice, day by day. After ten days of ten minutes a day on this simple exercise I think you would see a big difference.
Comment: Practising each finger moving separately isn't so good. When they eventually get to move together, their movements will be subtly different from what they did separately.
Comment: This is a beginning player and just feeling the strings, and moving between them and seeing what is necessary (and what is not) gives an orientation and develops the physical co-ordination.  It also breaks up the sheer repetition of the two chords with a moment of reflection on how it is being done.
Comment: It may work, but with experience of hundreds of students in their first few lessons, I know my method works.
Answer: B3ko's idea of keeping common fingers in place is excellent. and one that works in many changes. A similar idea can be used with a change from E to A, open. leave the index finger on 3rd string, as it is for E, and move the middle and ring across, putting the pinky on the second string for A. This means little movement, anchored with the index.
Another idea which I use often with students is to practise hammering-on whole chords. In other words, hole down a chord, then lift fingers together about 5mm, then bang them all down onto the appropriate strings, holding then for a second to hear the chord. It'll take some practice, but it trains those fingers to get there all at once, which after all, is what they need to do. Not one at a time.
With regular practice, often (5 mins at a time will do it), then try to find chords without looking. Eventually this is the aim, as you don't want to spend all of your playing looking at your fingerboard !
Answer: What Tim and B3ko said is excellent - practising changing between chords which have common notes is a great place to start, and trying to hammer on a chord out of nowhere (without placing the fingers first and then strumming) will get you used to the shapes of chords and picturing their shapes will eventually be as simple as picturing a word in your head.
One thing I would like to warn about though in addition to these answers is a problem that a lot of beginner/inexperienced players suffer from - excess finger movement. Something I see time and time again is new players overly emphasising their finger movement every time they change shape; they lift their fingers far too far whenever they lift them and this makes their fingers more unstable/inaccurate when trying to find the next fret they want to play. It is something which you will definitely get over with practice - in the same way that when learning to type on a keyboard everyone goes through a phase of really over-emphasised movements but eventually improves - but it is definitely something to keep an eye on as it might hinder your progress.
One way to counter this is to play changes slowly but force yourself to change all fingers at the same time, so you are not awkwardly finding each fret at a time and slowing down the pace of whatever song you are playing. Obviously, start with chords which have common notes (as B3ko suggests, Am to C is a good place to start), but then move onto more "difficult" changes (such as D to Em or even open chords to barre chords).
This is probably more of a "next step" approach, but if you are at least aware of it from very early on it will help you in the long run. It is something which will develop naturally with time but trying to train the skill early on will definitely be a benefit to you.
Answer: There is already a lot of good advice here, but I don't see any talk of finger independence. When switching between chords, each finger may need to go on a little mission to its next destination, and you don't have time to guide each finger to that destination; each finger needs to be able to get to where it needs to be independently of the others.
One exercise I found long ago that was very helpful in this regard goes something like this:
$E.1.$D.2 $E.2.$D.1 | $E.2.$D.3 $E.3.$D.2 | $E.3.$D.4 $E.4.$D.3 | $E.4.$D.5 $E.5.$D.4 | $E.5.$D.6 $E.6.$D.5 | $E.6.$D.7 $E.7.$D.6 | $E.7.$D.8 $E.8.$D.7 | $E.8.$D.9 $E.9.$D.8 | $E.9.$D.10 $E.10.$D.9 | $E.10.$D.11 $E.11.$D.10 | $E.11.$D.12 $E.12.$D.11 ||

Play this exercise starting from the first fret, ascending and continuing past the 12th fret, then reverse direction and descend back to the first fret. Try it with different fingers: first and second finger, second and third finger, third and fourth finger, first and third finger, second and fourth finger, first finger and fourth finger. Try it with different string pairs: 6th string and 5th string, 5th string and 1st string, 4th string and 2nd string, etc. Try it with different fret spacings: both fingers on the same fret, fingers spaced two frets, three frets, etc.
The point of this exercise is to isolate the problem of sending your fingers independently to wherever they need to go. Often a chord change just involves sending one finger to a new location, and the others remain in place. Sometimes two fingers need to move independently to new locations, maybe one or two other fingers stay in place or slide along the strings they already occupy. Other times all fingers must shift position, scattering to their destinations and arriving at the same time. This exercise allows you focus on these problems in a controlled way, and will improve the speed and accuracy of your chord fingerings. It is also great for your playing stamina; you might need a drink after traversing the neck several times!


Swift: SegmentedControl in NavBar with Small TitleView

Question: I am attempting to include a segmentedControl on my navBar that looks like this:

The idea here is that the text "fetching..." is a small titleView. However, my current implementation would result in the text "fetching..." on the lower side like so:

I implement large titles so that I can get two "rows" on the navBar, else the word "fetching..." will be hidden behind the segmentedControl.
Code:
let segmentedControl: UISegmentedControl = {
    let items = ["Now","In 15 mins", "In 1 hour"]
    let sc = UISegmentedControl(items: items)
    sc.selectedSegmentIndex = 0
    return sc
}()

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.backBarButtonItem?.title = "Back"
    navigationItem.largeTitleDisplayMode = .automatic

    navigationItem.titleView = segmentedControl

}

Does anyone have any advice?
Answer: You can create a customView that holds all the views you want to show in the navigation bar and set that view as titleView like below,
let segmentedControl: UISegmentedControl = {
        let items = ["Now","In 15 mins", "In 1 hour"]
        let sc = UISegmentedControl(items: items)
        sc.selectedSegmentIndex = 0
        return sc
  }()

let fetchingLabel: UILabel = {
       let label = UILabel(frame: .zero)
       label.text = "Fetching..."
       return label
  }()

In viewDidLoad
    let customView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 250))
    customView.addSubview(segmentedControl)
    customView.addSubview(fetchingLabel)

    fetchingLabel.frame = CGRect(x: 150, y: 0, width: self.view.frame.width, height: 60)
    segmentedControl.frame = CGRect(x: 60, y: 50, width: self.view.frame.width * 0.75, height: 30)

    navigationController?.navigationBar.prefersLargeTitles = true
    navigationItem.largeTitleDisplayMode = .automatic

    navigationItem.titleView = customView

This should give you below result. You can play with the values to do what you want.


Como saber se uma string contém outra?

Question: Tenho uma List<string> com quatro itens:
C:\Users\Producao\OneDrive\VisualStudio2017\siteRelatorios\bpa\Content\Upload\LFCES004.txtb9109712-d3f2-4151-bbac-7fbc82ed99de
C:\Users\Producao\OneDrive\VisualStudio2017\siteRelatorios\bpa\Content\Upload\LFCES018.txteeba927c-47c9-41ff-9643-4a0556244b26
C:\Users\Producao\OneDrive\VisualStudio2017\siteRelatorios\bpa\Content\Upload\LFCES021.txt84a0effb-a3a3-4790-a8e4-62d80e23b0ad
C:\Users\Producao\OneDrive\VisualStudio2017\siteRelatorios\bpa\Content\Upload\LFCES037.txta1189537-b589-4161-9ce6-f62b2aecbab9

Cada linha dessa é um arquivo .txt
Quero saber deles, qual linha tem a palavra LFCES004, LFCES018, LFCES021 e LFCES037
Ex.: if (linha1 contém 'LFCES004')
Comment: Cara só usar  .Contains(valor)
Comment: Não entendi os votos negativos nem o voto para fechar pela pergunta "não estar clara o suficiente". Acho que uma prova de intepretação de texto deveria ser pré-requisito para se poder dar esse tipo de voto de fechamento ¬¬
Comment: Também não entendi @Renan, mas fazer o que né?
Comment: Era bastante óbvio que uma perguntas simples assim já teria várias respondidas, e tem mais ainda.
Comment: é que pesquisei por uma string dentro de outra, não pesquisei por comparação de strings, já que meu pensamento não era esse
Answer: A classe String possui um método de instância chamado Contains que atende a sua necessidade.
O método recebe uma string, e indica se a string informada é uma substring da instância na qual foi chamado.
i.e.:
string foo = "abc", bar = "ab", ni = "ad";

foo.Contains(bar); // o retorno será true
foo.Contains(ni); // o retorno será false

Note que uma string sempre é substring dela mesma.
Answer: Pra checar se uma string está contida na outra, basta usar o Contains:
if (linha1.Contains("LFCES004"))

Answer: Basta usares Contains
var Value1 = "ddabcgghh";

if (Value1.Contains("abc"))
{
    [..]
}

Para verificares com uma Lista tenta o seguinte:
foreach(string item in minhaLista)
{
  if(item.Contains("ABCABC"))
       return item;
}

Como saber se uma string contém outra?


Finding the maximum for this function.

Question: I am having difficulty finding a constant k such that k is larger than$ \frac{(logn)^b}{n} $ where b is a constant. Is there a way I can rewrite this?
Comment: Since $\,\frac{\log^bn}{n}\xrightarrow[n\to\infty]{}0\,$ for any $\,b\,$ , do you want a bound for all $\,n\,$?
Comment: Yes. I want a constant that is greater than the maximum of the function. For example for 1/n, the maximum is 1, so k would be 1
Comment: Is there an asymptotic maximum to this function?
Answer: noting the title and assuming that you want b>0 and n>1 and using ln instead of log
$$f'(n,b) = \frac{(b-ln(n))(ln ~n)^{(b-1)}}{n^2} = 0$$
$$b*(ln ~n)^{(b-1)} = (ln~ n)^b$$
$$n = e^b$$
$$ln(e^b)^b/(e^b) = b^b/(e^b)$$
$$k> \frac{b^b}{e^b}$$
does that work for you?
Answer: Let me see if I understand your question correctly.  You have $b$, a constant. You have the function $f(n) = \frac{\ln^b(n)}{n}$.
You wish you maximize the function $f(n)$ with respect to $n$, then find a $k$ that is larger than that maximum.

$f_n(n) = \frac{b\ln^{b-1}(n) - \ln^b(n)}{n^2} = 0$
$\therefore b = \ln(n) $
And so we know $n = e^b$ is the value that optimizes the function.  Since there is only the one optimization point Im going to assume, based on the question, that this is a maximum.  At the optimization point we have a value, a maximum, of $f(e^b) = (\frac{b}{e})^b$.
And value $k\gt (\frac{b}{e})^b$ will produce your result.

Finding the maximum for this function.


How can I force LilyPond to repeat a clef on every line of the score?

Question: I'd like LilyPond to print the clef not only at the beginning of the score, but whenever the line breaks, at the beginning of the new line. Is this possible at all, and, how so?
Answer: Mine prints the clef automatically on every line:

I simply used the <code>\break</code> command for a new line:
<code>\relative c' {
  c d e f | \break
  g a b c |
}
</code>
Another example:
Comment: Okay, found the problem. Actually, I didn't realize that removing the barline_engraver also removed the clef symbols.


DBSCAN: What is a Core Point?

Question: I have a question about DBSCAN.
The points here are classified as core points, border points or noise.

A point p is a core point if at least minPts points are within distance ε of it, and those points are said to be directly reachable from p. No points are directly reachable from a non-core point.
A point q is reachable from p if there is a path p1, ..., pn with p1 = p and pn = q, where each pi+1 is directly reachable from pi (so all the points on the path must be core points, with the possible exception of q).
All points not reachable from any other point are outlier

Consider the following image:

I don't understand, if there must be 4 points within a radius or a point needs to reach 4 another points, in order to be classified as a core point.
So consider the far right red point (just under the letter "e"). This is a core point. But within its radius are just 3 other points, not 4. So there should be 4 points within a radius including the one point itself?
There are just 3 other points reachable from that point.
Comment: The picture is the same as on [Wikipedia](https://en.wikipedia.org/wiki/DBSCAN). There, the figure caption says that MinPts = 3. Could your MinPts = 4 simply be an error?
Comment: @StephanKolassa The figure caption on the Wiki page says minPts = 4. They might have updated it.
Answer: In a database, all points are equal.

The blue point has 1 point in its neighborhood - itself.
The yellow points have 2 points in their neighborhood each.
The red points have 4-5 points in their neighborhood each.

Note that the definitions don't say "minPts other points"; but "minPts points". You can't ignore the one point you already know (what if it has duplicates?)

DBSCAN: What is a Core Point?


Como gerar JLabel ou JTextField no clique do mouse?

Question: Gostaria de saber se existe um meio de gerar um JLabel ou JTextField na posição onde clicares, em um JPanel ou um JFrame.
É possivel?
Answer: Sim, é possível:

Define o layout com posicionamento absoluto com setLayout(null) no componente alvo.
Adicione um MouseListener no componente.
Implemente o evento mouseClicked:

Crie o componente desejado.
Adicione-o no componente alvo com o método add.
Define o posicionamento e tamanho com setBounds.

Veja um exemplo simples que fiz:
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class TextFieldGeneratorTest {

    private static int contador = 0;

    public static void main(String[] args) {

        //janela
        final JFrame janela = new JFrame("Test JTextField Generation");

        //posicionamento sem nenhum layout, isto é, absoluto
        janela.getContentPane().setLayout(null);

        //adiciona listener do mouse
        janela.getContentPane().addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent event) {

                //adiciona dinamicamente no clique
                final JTextField textField = new JTextField("Caixa " + ++contador);
                textField.setBounds(event.getX(), event.getY(), 200, 30);
                janela.getContentPane().add(textField);

            }
        });

        //exibe a janela
        janela.setSize(600,  600);
        janela.setVisible(true);

    }

}


Waiting times at a bank - probability

Question: Suppose there are 3 bank tellers, all currently occupied with a customer. You are waiting in line (and there are no other customers that will come in after you). All service times are iid exponential random variables with parameter $\lambda$. You must find the probability that you are the last to leave.
I have set up this problem as follows:

Denote $X_a, X_b, X_c$ as the service times for the currently served customers.
Denote $X_d$ as your service time (i.e. the time you will spend at the counter with a teller).
Denote $X_- = min\{X_a , X_b, X_c\}$ as the shortest service time of the currently served customers.
Denote $X_+ = max\{X_a, X_b, X_c\}$ as the longest service time of the currently served customers.

With this setup, we must computer $P[X_d + X_- > X_+]$. So far, I have established the following:

$P[X_- > x] = e^{-3\lambda x}$
$P[X_+ > x] = 1 - (1 - e^{-\lambda x})^3$

I'm a bit stuck on how to move on from here. Any guidance would be awesome. Thanks.
Answer: Part I: Intuitive answer.
This was already describe by @BruceET. I'll just say it again with some different words...
The answer is $1/3$.
The  exponential distribution is "memoryless". From the time you begin being serviced, think of the two others exponential clocks as being "reset":  the additional time required for service by the each of the other two is still  $\mbox{Exp}(\lambda)$, and all three times are independent. Therefore you'll as equally likely to finish last as any of the two others, and since the probability that any two finish at the same time is zero, the probability you finish last is $1/3$. This generalizes to any number of tellers.
Part II. Proof.
Here's a detailed analysis, which could be made shorter (and closer in spirit to Part I), but I decided to expand on the joint distributions because it is very informative and useful for other problems.
$X_1,X_2,X_3$ are times until tellers finish with current customers.
You'll begin at time $Y_1=\min(X_1,X_2,X_3)$. Let $Y_3=\max (X_1,X_2,X_3)$, and let $Y_2$ be the remaining variable (since all three are distinct with probability $1$, $Y_2$ is defined except on an event of probability $0$).
Your service time is $T\sim \mbox{Exp}(\lambda)$, independently of all the rest. You'll be last if and only if $Y_1+T > Y_3$. Denote this event by $A$.
Consider the joint distribution of $X_1,X_2,X_3$ conditioned on $Y_1=X_1<X_2<X_3=Y_3$. The latter event has probability $1/6$, and therefore the joint density is
$$ 6  \lambda^3 e^{-\lambda x_1} e^{-\lambda x_2} e^{-\lambda x_3} {\bf 1}_{\{x_1 < x_2\}}{\bf 1}_{\{x_2<x_3}\}.$$
The can be written as
$$ 6 \lambda^3 e^{-3\lambda x_1} e^{-2\lambda (x_2-x_1) } e^{-\lambda (x_3-x_2)}{\bf 1}_{\{x_2-x_1 >0\}} {\bf 1}_{\{x_3-x_2>0\}}.$$
By considering all $6$ permutations, we conclude  from the formula above that

$Y_1 \sim \mbox{Exp}(3\lambda)$;

$Y_2-Y_1\sim \mbox{Exp}(2\lambda)$; and

$Y_3-Y_2\sim \mbox{Exp}(\lambda)$; with

$Y_1,Y_2-Y_1,Y_3-Y_2$ independent.

Therefore, the event $A$,  $Y_1 + T > Y_3$, can be rewritten as
$Y_1 +T > Y_1 + (Y_2-Y_1) + (Y_3-Y_2)$ or $T> (Y_2 -Y_1) + (Y_3-Y_2)$.
Since $T\sim \mbox{Exp}(\lambda)$ and is independent of $Y_1,Y_2,Y_3$, we conclude that
$$P(A) = E[e^{-\lambda [(Y_2-Y_1) + (Y_3-Y_2)]}]=E[e^{-\lambda (Y_2-Y_1)}] E[e^{-\lambda(Y_3-Y_2)}].$$
Recall that the MGF of $\mbox{Exp}(\rho)$ at $t$ is equal to $ \frac{\rho}{\rho -t}$, and therefore the righthand side is
$$ \frac{2\lambda}{2\lambda +\lambda}\frac{\lambda}{\lambda + \lambda}=\frac 13 $$
Answer: By the no memory property, it makes no difference how long
each of the customers ahead of you have been 'in service' with
their tellers.
As soon as you start with one of the tellers, by the no-memory property, all three waiting times to finish have the same distribution. So you have one chance in three of being last to leave.
The simulation below is not a proof, but it gives an idea
of how long the waiting times are.
In the simulation, $\lambda=0.1$ per min. for all tellers and you have just
started with teller #1.
There are 10 million iterations;
x1,x2,x3 are waiting times at each teller, w is
the maximum waiting time among the three, mean(x1==w) is
the proportion of instances in which you finish last.
(With 10 million iterations, one can expect about two place
accuracy in service times.)
set.seed(2021)
x1 = rexp(10^7, .1)
x2 = rexp(10^7, .1)
x3 = rexp(10^7, .1)
w = pmax(x1,x2,x3)
mean(w)
[1] 18.33176

After you begin service (in about $\frac{1}{3\lambda}=3.33$ minutes), you can
expect to finish after about $18.33$ additional minutes.
Comment: I believe you can formalize an answer using the memoryless property. This is very interesting - thanks for the insight.
Comment: Glad you like the idea of doing it in terms of the no memory property.// Total average time for 'max' after beginning service: Wait for minimum of 3, wait for min of remaining 2, wait for last: 3.33 + 5 + 10 = 18.33. (Works easily only if all three servers have same rate.)

Waiting times at a bank - probability


Plugin para barra de progresso com etapas

Question: Alguém sabe de algum plugin Javascript ou CSS que pode gerar esse tipo de barra de progresso?
Comment: Pode ser em vue.js?
Comment: Preferenciamente em javascript puro ou jquery, são as dependências do projeto.
Comment: Tranquilo, mas para referências futuras vou deixar uma que já usei em vue http://element.eleme.io/#/en-US/component/steps
Comment: Postei uma resposta, deu bastante trabalho. Espero que goste.
Comment: @VictorStafusa ficou muito bom valew!
Answer: Deu um trabalhão fazer, mas aqui está. Clique no botão azul Executar lá em baixo para ver funcionando.

/* JavaScript para incluir. */

jQuery.fn.extend({
    stepProgressBar: function(currentStep) {
        currentStep = currentStep || this.currentStep() || 1;
        let childs = this
                .addClass("step-progress-bar")
                .find("li")
                .removeClass("step-past step-present step-future");

        childs.find(".content-stick").removeClass("step-past step-future");

        let size = childs.length < 1 ? 100 : 100 / childs.length;
        childs.css("width", size + "%");

        for (let i = 0; i < childs.length; i++) {
            let child = $(childs[i]);
            if (child.find("span.content-wrapper").length === 0) {
                child.wrapInner("");
                if (i > 0) child.append("");
                child.prepend("" + (i + 1) + "");
            }
            let stepName = i < currentStep - 1 ? "step-past"
                    : i === currentStep - 1 ? "step-present"
                    : "step-future";
            child.addClass(stepName);
            if (i > 0) {
                let stickName = stepName === "step-present" ? "step-past" : stepName;
                child.find(".content-stick").addClass(stickName);
            }
            child.css("z-index", childs.length - i);
            child.find(":before").css("z-index", childs.length - i + 2);
        }
        return this;
    },

    currentStep: function() {
        var childs = this.find("li");
        for (let i = 0; i < childs.length; i++) {
            if ($(childs[i]).is(".step-present")) return i + 1;
        }
        return 1;
    },

    countSteps: function() {
        return this.find("li").length;
    },

    isFirstStep: function() {
        return this.countSteps() === 1;
    },

    isLastStep: function() {
        return this.countSteps() === this.currentStep();
    },

    previousStep: function() {
        if (!this.isFirstStep()) this.stepProgressBar(this.currentStep() - 1);
    },

    nextStep: function() {
        if (!this.isLastStep()) this.stepProgressBar(this.currentStep() + 1);
    },

    rewind: function() {
        this.stepProgressBar(1);
    },

    fastForward: function() {
        this.stepProgressBar(this.countSteps());
    },

    controlProgressBar: function(progressBar) {
        let rewind = function() { progressBar.rewind(); };
        let next = function() { progressBar.nextStep(); };
        let previous = function() { progressBar.previousStep(); };
        let fastForward = function() { progressBar.fastForward(); };
        this.empty();
        $("<input type='button' class='step-progress-bar-button rewind' value='⏪' />").on('click', rewind).appendTo(this);
        $("<input type='button' class='step-progress-bar-button previous' value='◀' />").on('click', previous).appendTo(this);
        $("<input type='button' class='step-progress-bar-button next' value='▶' />").on('click', next).appendTo(this);
        $("<input type='button' class='step-progress-bar-button fast-forward' value='⏩' />").on('click', fastForward).appendTo(this);
        return this;
    }
});

/* JavaScript na página. */

$("#barra-simples-1").stepProgressBar();
$("#barra-simples-2").stepProgressBar();
$("#barra-simples-3").stepProgressBar(3);

let pb = $("#barra-controle-basico").stepProgressBar(2);
$("#controle-basico").controlProgressBar(pb);

$("#controle-macarrao").controlProgressBar($("#barra-macarrao").stepProgressBar(4));

let ca = $("#barra-controle-personalizado").stepProgressBar(1);
let cb = $("#controle-personalizado").controlProgressBar(ca);
cb.find(".rewind, .fast-forward").remove();

$("#cores-personalizadas").stepProgressBar(4);

let temp = $("#cores-temperatura").stepProgressBar(3);
$("#controle-temperatura").controlProgressBar(temp);
/* CSS principal da barra de progresso. Não deve ser alterado. */

ol.step-progress-bar {
    list-style: none;
    padding: 0;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
}

ol.step-progress-bar li {
    display: inline-block;
    vertical-align: top;
    text-align: center;
    flex: 1 1;
    position: relative;
    margin: 0 5px 0;
}

ol.step-progress-bar li span.content-bullet {
    border-radius: 100%;
    display: block;
    text-align: center;
    transform: translateX(-50%);
    margin-left: 50%;
}

ol.step-progress-bar li span.content-wrapper {
    display: inline-block;
    overflow: visible;
    width: 100%;
    padding: 0;
}

ol.step-progress-bar li span.content-stick {
    position: absolute;
    display: block;
    width: 100%;
    height: 8px;
    z-index: -1;
    transform: translate(-50%, -50%);
}

/* Cores. Sinta-se livre para alterar. */

/* Cor padrão.
   Passado: #2dcd73 (verde) e branco.
   Presente: #4c92d9 (azul) e branco.
   Futuro: #dde2e3 (cinza claro) e #869398 (cinza escuro).
*/

ol.step-progress-bar li.step-past *,
ol.step-progress-bar li.step-present .content-stick {
    color: #2dcd73;
    background: #2dcd73;
}

ol.step-progress-bar li.step-present * {
    color: #4c92d9;
    background: #4c92d9;
}

ol.step-progress-bar li .content-bullet {
    color: white;
}

ol.step-progress-bar li.step-future * {
    color: #869398;
    background: #dde2e3;
}

ol.step-progress-bar li .content-wrapper {
    background: transparent;
}

/* Cor especial 1.
   Passado: vemelho
   Presente: laranja
   Futuro: amarelo
   Cor dos números: azul
*/

ol.step-progress-bar.cor-especial li.step-past *,
ol.step-progress-bar.cor-especial li.step-present .content-stick {
    color: red;
    background: red;
}

ol.step-progress-bar.cor-especial li.step-present * {
    color: orange;
    background: orange;
}

ol.step-progress-bar.cor-especial li.step-future * {
    color: yellow;
    background: yellow;
}

ol.step-progress-bar.cor-especial li .content-bullet {
    color: blue;
}

ol.step-progress-bar.cor-especial li .content-wrapper {
    background: transparent;
}

/* Cor especial 2. */

#gelado * {
    color: blue;
    background: blue;
}

#frio * {
    color: cyan;
    background: cyan;
}

#morno * {
    color: lime;
    background: lime;
}

#quente * {
    color: yellow;
    background: yellow;
}

#fervendo * {
    color: red;
    background: red;
}

#cores-temperatura .content-wrapper {
    background: transparent;
}

#cores-temperatura .content-bullet {
    color: black;
}

#cores-temperatura .content-wrapper {
    text-shadow: 0 0 1px black, 0 0 8px purple;
}

#cores-temperatura li.step-present {
    font-weight: bold;
    font-size: 120%;
}

#cores-temperatura li.step-present .content-bullet {
    width: 55px;
    line-height: 55px;
    transform: translate(-27px, -9px);
    font-size: 200%;
    color: pink;
    text-shadow: 0 1px black, 1px 0 black, -1px 0 black, 0 -1px black;
}

#cores-temperatura li .content-stick {
    background: purple;
}

/* Tamanhos. */

/* Tamanho pequeno:
   Bolinha de 25px de diâmetro.
   Fonte 75%.
   Conector 4px de altura.
*/

ol.step-progress-bar.small li .content-bullet {
    width: 25px;
    line-height: 25px;
}

ol.step-progress-bar.small li {
    font-size: 75%;
}

ol.step-progress-bar.small li .content-stick {
    top: 12.5px; /* Metade do diâmetro. */
    height: 4px;
}

/* Tamanho médio:
   Bolinha de 37px de diâmetro.
   Fonte 100%.
   Conector 6px de altura.
*/

ol.step-progress-bar.mid li .content-bullet {
    width: 37px;
    line-height: 37px;
}

ol.step-progress-bar.mid li {
    font-size: 100%;
}

ol.step-progress-bar.mid li .content-stick {
    top: 18.5px; /* Metade do diâmetro. */
    height: 6px;
}

/* Tamanho grande:
   Bolinha de 49px de diâmetro.
   Fonte 120%.
   Conector 8px de altura.
*/

ol.step-progress-bar.large li .content-bullet {
    width: 49px;
    line-height: 49px;
}

ol.step-progress-bar.large li {
    font-size: 125%;
}

ol.step-progress-bar.large li .content-stick {
    top: 24.5px; /* Metade do diâmetro. */
    height: 8px;
}

Exemplo 1, uma barra simples

Passo 1

Passo 2

Passo 3

Exemplo 2, uma barra simples com progresso definido no HTML

A

B

C

Exemplo 3, uma barra simples com progresso definido no JS

Cadastrar os dados

Confirmar o e-mail

Efetuar a compra

Realizar o pagamento

Exemplo 4: Com botões de controle

Preparar

Apontar

Fogo

Exemplo 5: Com botões de controle personalizados

Nova

Crescente

Cheia

Minguante

Exemplo 6: Fazendo um macarrão instantâneo

Colocar água na panela

Ligar o fogo

Ferver

Acrescentar o macarrão

Cozinhar por 3 minutos

Desligar o fogo

Acrescentar o tempero

Servir

Exemplo 7: Cores personalizadas 1

Juntar dinheiro

Construir robôs

Declarar guerra

Atacar os inimigos

Dominar o mundo

Exemplo 8: Cores personalizadas 2

Gelado

Frio

Morno

Quente

Fervendo

Answer: Bootsnipp
Você pode utilizar esse código que eu achei no bootsnipp.

https://bootsnipp.com/snippets/featured/form-process-steps

Observe você terá que fazer apenas um script em javascript para alterar as classes.
Existem outros similares no mesmo site: https://bootsnipp.com/similar/O4O8

Exemplo
Fiz um exemplo de uma possível aplicação utilizando o link que informei. Peço desculpa pelo tamanho do código.

/*
  Exemplo de possível funcionalidade
  O código abaixo desativa a "Etapa" que já foi completada
*/

// Funções utilitárias
function active(div) {
    div.classList.remove('disabled');
    div.classList.remove('complete');
    div.classList.add('active');
}

function complete(div) {
    div.classList.remove('disabled');
    div.classList.remove('active');
    div.classList.add('complete');
}

function disabled(div) {
    div.classList.remove('active');
    div.classList.remove('complete');
    div.classList.add('disabled');
}

// Desativando as etapas
function desativaEtapa1() {
    var etapa1 = document.getElementById("etapa1");
    var etapa2 = document.getElementById("etapa2");
    var etapa3 = document.getElementById("etapa3");

    disabled(etapa3)
    disabled(etapa2);
    disabled(etapa1);
}

function desativaEtapa2() {
    var etapa1 = document.getElementById("etapa1");
    var etapa2 = document.getElementById("etapa2");
    var etapa3 = document.getElementById("etapa3");

    complete(etapa1);
    disabled(etapa2);
    disabled(etapa3);
}

function desativaEtapa3() {
    var etapa1 = document.getElementById("etapa1");
    var etapa2 = document.getElementById("etapa2");
    var etapa3 = document.getElementById("etapa3");

    complete(etapa1);
    complete(etapa2);
    disabled(etapa3);
}
/*
  Código retirado do site https://bootsnipp.com/
  Creditos totais para o usuário alilishan
  Link do código:
  https://bootsnipp.com/snippets/featured/form-process-steps
*/

.bs-wizard {margin-top: 40px;}

/*Form Wizard*/
.bs-wizard {border-bottom: solid 1px #e0e0e0; padding: 0 0 10px 0;}
.bs-wizard > .bs-wizard-step {padding: 0; position: relative;}
.bs-wizard > .bs-wizard-step + .bs-wizard-step {}
.bs-wizard > .bs-wizard-step .bs-wizard-stepnum {color: #595959; font-size: 16px; margin-bottom: 5px;}
.bs-wizard > .bs-wizard-step .bs-wizard-info {color: #999; font-size: 14px;}
.bs-wizard > .bs-wizard-step > .bs-wizard-dot {position: absolute; width: 30px; height: 30px; display: block; background: #fbe8aa; top: 45px; left: 50%; margin-top: -15px; margin-left: -15px; border-radius: 50%;}
.bs-wizard > .bs-wizard-step > .bs-wizard-dot:after {content: ' '; width: 14px; height: 14px; background: #fbbd19; border-radius: 50px; position: absolute; top: 8px; left: 8px; }
.bs-wizard > .bs-wizard-step > .progress {position: relative; border-radius: 0px; height: 8px; box-shadow: none; margin: 20px 0;}
.bs-wizard > .bs-wizard-step > .progress > .progress-bar {width:0px; box-shadow: none; background: #fbe8aa;}
.bs-wizard > .bs-wizard-step.complete > .progress > .progress-bar {width:100%;}
.bs-wizard > .bs-wizard-step.active > .progress > .progress-bar {width:50%;}
.bs-wizard > .bs-wizard-step:first-child.active > .progress > .progress-bar {width:0%;}
.bs-wizard > .bs-wizard-step:last-child.active > .progress > .progress-bar {width: 100%;}
.bs-wizard > .bs-wizard-step.disabled > .bs-wizard-dot {background-color: #f5f5f5;}
.bs-wizard > .bs-wizard-step.disabled > .bs-wizard-dot:after {opacity: 0;}
.bs-wizard > .bs-wizard-step:first-child  > .progress {left: 50%; width: 50%;}
.bs-wizard > .bs-wizard-step:last-child  > .progress {width: 50%;}
.bs-wizard > .bs-wizard-step.disabled a.bs-wizard-dot{ pointer-events: none; }
/*END Form Wizard*/
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

                Etapa 1

                Texto 1.

                Etapa 2

                Texto 2.

                Etapa 3

                Texto 3.

                Etapa 4

                Texto 4.

Comment: Embora este link possa responder à pergunta, é melhor incluir as partes essenciais da resposta aqui e fornecer o link para referência.  As respostas apenas por link podem ser invalidadas se a página com o link for alterada. - [Da Revisão](/review/low-quality-posts/139525)
Comment: Tem como adicionar um exemplo do código na sua resposta? assim ela fica mais completa.
Comment: @DvD Realmente, vou incluir o código aqui na resposta.
Comment: @rray Vou preparar um exemplo e edito aqui novamente.


Unit vector notation - both line and hat?

Question: I know that unit vectors are usually written in bold with a hat for example: $$\hat{\mathbf{i}}$$
But if you use vector notation with arrows (as I do when I write with pen and papper), should you both have an arrow above the vector and a hat, or just the hat?
Thanks!
Comment: You can write $$\frac{\vec{a}}{|\vec{a}|}$$ or $$\hat{i}$$
Comment: "Usually written with a hat..."  I think that is physics notation, not used much at all in mathematics.
Comment: Thanks for the input! Yes, I know of that notation, but it feels a bit cumbersome. But maybe that is the best notation to avoid confusion
Answer: In general, what indicates whether a vector is unit vector or not is the letter used rather than the hat ($\hat{}$). So, as long as you prevent confusion by not giving name $i,j,k,e_1,e_2$ etc. to some other vectors, $\vec{i}$ still is a unit vector. But I should also note that this also depends on the context in which you are using this notation. I don't know whether there is a context where $\hat{i}$ or $\vec{i}$ is a different vector from $[1\ 0\ 0]^T$ but I am sure that in some contexts, someone can name a vector $i$ even if it is not a unit vector (for instance where $e_1,e_2,e_3,$ etc. are used for unit vectors). But as long as you clarify your notation beforehand, I don't think there will be any problems when you use $\vec{i}, \vec{j}, \vec{k}$
Comment: Thanks. Yeah, the problem so like you stated not that often with i,j,k etc. Most often I have found that the position vector can be a bit difficult to interpret whether it is of unit lenght or not


Definition of integral on open set.

Question: I am learning about integration on manifolds. Suppose we have a $k$-form $\omega = a dx_1 \wedge \ldots \wedge dx_k$ where $a$ is some $0$-form on $U,$ an arbitrary real valued function. Then we define $\int_U \omega = \int_U a dx_1 \ldots dx_k.$ How is $\int_U a dx_1 \ldots dx_k$ defined?
Answer: It is defined as a regular $k-$variable function : $U$ is an open set in $\Bbb{R}^{k}$, and $a:\Bbb{R}^{k} \rightarrow \Bbb{R}$ so integration is well-defined here.

Definition of integral on open set.


Unable to ssh to GCE: "Permission denied (publickey)"

Question: I created a VM via Bitnami in Google Compute Engine. Previously, I was able to ssh via the Bitnami web interface. I tried to ssh via terminal on my Mac but kept getting the Permission denied (publickey) error. I then deleted all keys on the server and my Mac and downloaded the pem file form bitnami and used -i option to connect but still the problem persists.
ssh -i bitnami-gce.pem firstname.lastname@example.com -v

Complete debug info:
OpenSSH_6.2p2, OSSLShim 0.9.8r 8 Dec 2011
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 20: Applying options for *
debug1: Connecting to 1xx.1xx.5x.1xx [1xx.1xx.5x.1xx] port 22.
debug1: Connection established.
debug1: identity file bitnami-gce.pem type -1
debug1: identity file bitnami-gce.pem-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1p1 Debian-4~bpo70+1
debug1: match: OpenSSH_6.6.1p1 Debian-4~bpo70+1 pat OpenSSH*
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr email@example.com none
debug1: kex: client->server aes128-ctr firstname.lastname@example.com none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA <RSA KEY>
debug1: Host '1xx.1xx.5x.1xx' is known and matches the RSA host key.
debug1: Found key in /Users/xxx/.ssh/known_hosts:1
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: bitnami-gce.pem
debug1: read PEM private key done: type RSA
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
Permission denied (publickey).

I am unable to ssh to the host. So can't send any keys to server now. How to resolve this?
Edit: I tried to ssh via Google web console and I could do it. Can anyone tell me the exact steps to ssh from anywhere? I prefer the simple username and password way, how to configure it that way?
Comment: 1. After create new ssh key
2. adding project public ssh key
https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys
Comment: If you are facing this issue after upgrading to Ubuntu 22.04, see this:
https://stackoverflow.com/a/74273581/11823331
Answer: After I was able to ssh via Google web console, I did the following steps to resolve this:

Generate ssh key using
ssh-keygen
Copy the key.pub file contents
Append the contents to ~/.ssh/authorized_keys file
sudo nano ~/.ssh/authorized_keys
Answer: I faced the same situation because of the user. On google web shh my user name was showing something first part of my email. So, I was trying ssh like this
ssh <first_part_of_gmail>@google_vm_external_ip

Later, I discover that, google creates a user based on the ssh key that you put on the google vm setting. So, first check the user at the end of the public key, and try following
ssh <user_name_at_the_end_of_public_key>@google_vm_external_ip

Comment: you are a true mvp ... after 5 minutes I still hadn't notice that weird usename thing they had going
Answer: Make sure you don't have OS Login enabled. Docs read:

If you manage your SSH keys by using OS Login on instances, metadata-based SSH key configurations on those instances are disabled

and

Caution: Enabling OS Login on instances disables metadata-based SSH key configurations on those instances. Disabling OS Login restores SSH keys that you have configured in project or instance metadata.

To verify, go to project-level metadata (Compute Engine -> Metadata) and ensure that you have either no enable-oslogin key or that it is set to FALSE
Comment: Indeed @PromisePreston I wasted 3 days and some 2 hours on live chat to figure this one out. Glad it helps!
Comment: This saved me tons of frustration. Thank you.
Comment: There is also the option to disable oslogin only for a particular instance:
1. On the instance details page, click Edit.
2. Under Custom metadata, add a metadata entry, setting the key to enable-oslogin and the value to TRUE. Alternatively, set the value to FALSE to disable OS Login on the instance.

source: https://cloud.google.com/compute/docs/instances/managing-instance-access
Comment: Thanks @Voy! This saved the day for me too!
Answer: When your instance is first created, it will not have any SSH keys in it by default, so you have to transfer them there, e.g., by using gcloud to connect to it the first time as described in this SO answer or by manually creating SSH keys and manually adding them to your instance as described in another SO answer.
Answer: I had the same issue, and used gcloud command to login for the first time and added to /etc/ssh/sshd_config.
PubkeyAcceptedKeyTypes  +ssh-dss

After I restarted the service:
systemctl restart sshd

Answer: you need to make sure that you file bitnami-gce.pem permission is 600
try chmod 600 bitnami-gce.pem
regards
Ahmed
Answer: It's an old question, but I had this issue today too and fixed it by following these steps:

generate the ssh public key from your local computer
copy the public key to gcc virtual machine settings

and then connect.
These steps will guide you to connecting to your gcc vm instance on mac os terminal using ssh: https://nabtron.com/gcc-mac-terminal/ and will fix the issue of permission denied (pubilckey) too.
I hope it helps.


How does a transitive extension differ from a transitive closure?

Question: Quoting an example from C.L Liu's Discrete Mathematics: Let R be a binary relation on A. The transitive extension of R (let's denote it as $R_1$) is a binary relation on A such that $R_1$ contains R. Doesn't that make $R_1$ the transitive closure to R or is a transitive extension different from a closure?
Also, in the following two matrices, how is the second one the transitive extension to the first one?
$$
\begin{matrix}
\verb|bmatrix| & \begin{bmatrix}
                    0 & 1 & 0 & 0 \\
                    0 & 0 & 1 & 0 \\
                    0 & 1 & 0 & 1 \\
                    0 & 0 & 0 & 0
                  \end{bmatrix} \\[15pt]
\end{matrix}
$$
$$
\begin{matrix}
\verb|bmatrix| & \begin{bmatrix}
                    0 & 1 & 1 & 0 \\
                    0 & 1 & 1 & 1 \\
                    0 & 1 & 1 & 1 \\
                    0 & 0 & 0 & 0
                  \end{bmatrix} \\[15pt]
\end{matrix}
$$
Answer: Yes, transitive extension and transitive closure are different notions. If you start from a relation $R$ on some set, then the transitive extension $R_1$ of $R$ is obtained by adding to $R$ a pair $(a,c)$ whenever $(a,b)$ and $(b,c)$ are in $R$ for some $b$. Note that the transitive extension is in general not-transitive, while transitive closures are. For example, consider the two matrices of your question, and let $(i,j)$ denote the place corresponding to row $i$ and column $j$. Let $R$ be the relation represented by the first matrix, $R_1$ the relation represented by the second one. Then we say that $i$ is related to $j$ under $R$ if there is $1$ in place $(i,j)$ of the matrix representing $R$, we say they are not related if there is $0$. The same for $R_1$. In the first matrix, you have $1$ at place $(1,2)$, and $1$ in place $(2,3)$, meaning that $1$ is related to $2$ and $2$ to $3$. In the matrix, you have $0$ at place $(1,3)$, meaning that $R$ is not transitive, but you have $1$ in matrix $R_1$, which represents the transitive extension of $R$. Still $R_1$ is not transitive, because for example, using the same notation, $(1,2)$ and $(2, 4)$ are in $R_1$, but $(1,4)$ is not.
To obtain a transitive relation starting from a general relation $R$, you have to build its transitive closure, which is the least relation containing $R$ which is transitive, or equivalently, the set intersection of all transitive relations containing $R$.
You can relate the two notions by observing that, if you denote by $R_1$ the transitive extension of $R$, by $R_2$ the transitive extension of $R_1,\ldots,$ by $R_{i+1}$ the transitive extension of $R_i\ldots$, then the transitive closure of $R$ is the set union of all $R_i$'s.


How to get client Ip Address without using header in Java

Question: I am using apache-tomcat for app server and web server.
I want to keep track of the IP addresses of the systems that access my app server. But unfortunately the only way to get the IP address of the client systems and not the IP of web server we have to use Header X-Forwarded-For'. But I do not use X-Forwarded-For header, as it might expose the IP and cause security threat.
Is there any other way to accomplish this without 'X-Forwarded-For' header or Will it be secure to use this without any security compromises. Thanks in advance!
Ref: http://www.mkyong.com/java/how-to-get-client-ip-address-in-java/
Answer: There is no de facto standard for this.
Either X-Forwarded-For is used or getRemoteAddress is used.
Hope this link is helpful.
what is the right way to get request's ip
As far as security is concerned, I think this is the normal convention so it would be fine.


I am getting error Input Tensor is not an XLA tensor

Question: I am trying to run Pytorch lightning code on Google colab with TPU. I am implementing the Seq2Seq and in the encoder part:
 ### Enocder class of the transformer.

class Encoder (pl.LightningModule):
  def __init__(self, input_dim, hid_dim, n_layers, n_heads, pf_dim, dropout, device, max_len=10000):
    super().__init__()

    #self.device = device
    ## Token embedding table.
    self.tok_embedding = nn.Embedding(input_dim, hid_dim)
    print (self.tok_embedding)

    ### positional embedding table.
    self.pos_embedding  = nn.Embedding(max_len, hid_dim)

    ### define layers for multiple loop iteration.
    self.layers = nn.ModuleList([EncoderLayer(hid_dim, n_heads, pf_dim, dropout, device) for _ in range (n_layers)])
    self.ffwd = FeedForward(n_embed)
    self.ln1 = nn.Linear (n_embed, n_embed)
    self.relu = nn.ReLU()
    self.dropout = nn.Dropout(dropout)
    self.scale = torch.sqrt (torch.FloatTensor([hid_dim]))

  def forward(self, src, src_mask):

    #src = [batch size, src len]
        #src_mask = [batch size, 1, 1, src len]
    print ("encoder device ", self.device)
    batch_size = src.shape[0]
    print ("encoder batch_size", batch_size)
    src_len = src.shape[1]
    print ("encoder src_len", src_len)

    pos = torch.arange (0, src_len ).unsqueeze (0).repeat (batch_size, 1)
    pos = pos

    #pos = [batch_size, src_len]
    #print ("tok embedd device", self.tok_embedding.device)
    print ("src in encoder device", src.device)
    print ("pos embedding device", pos.device)
    out1 = self.tok_embedding(src)
    out2 = self.pos_embedding(pos)
    src = self.dropout(( out1 * self.scale ) + out2)
    src = src

The line where I am defining the pos variable. That variable device is coming as cpu but everything else is on tpu device. So, I am getting the error that tensor is not on TPU. WHy that variable is on cpu? What is the workaround to prevent that?
Answer: You need to create torch.arange tensor on TPU with something like this -
import torch_xla.core.xla_model as xm

device = xm.xla_device()
torch.arange(0, 100, device=self.device)


Prove that area of $ABC$ is $\frac{1}{4}|BC|^2\cdot \cot \frac{\theta}{2}$ where $\theta=\angle BAD$

Question: Let $ABC$ be a triangle such that $\angle B=2\angle C$. We extend the side $BC$ by a segment $CD$ equal to $\frac{1}{3}BC$.
Prove that area of $ABC$ is $$\frac{1}{4}|BC|^2\cdot \cot \frac{\theta}{2}$$ where $\theta=\angle BAD$
My attempt,
Let $a,b,c,d$ be the respective lengths of $BC, CA, AB, AD$ and suppose that the bisector of angle $ABC$ intersects $AC$ at $E$. So we can see that $BE=EC=\frac{ab}{(a+c)}$. We also know that $AC:AB=BC:BE$. Hence, $b^2=c(a+c)$. By applting the Cosine Law to the triangles $ABC$ and $ACD$, we can get $ad^2+(\frac{a}{3})c^2=(b^2+\frac{a^2}{3})(\frac{4a}{3})$. By using the equation of $b^2$, we get $9d=4a^2+12b^2-3c^2=(3c+2a)^2 $and $d=\frac{1}{3}(3c+2a)$. Applying the Cosine Law again to triangle $ABD$ and using the previous result to get $$16a^2=9(c^2+d^2-2cd\cos \theta)=(18c^2+12ac+4a^2)-6c(3c+2a)\cos \theta$$
so that $$6(3c^2+2ac)\cos \theta=6(3c^2+2ac-2a^2)$$
Hence, $$\cos \theta=1-\frac{2a^2}{3c^2+2ac}$$
We can get $1+\cos \theta=\frac{6c^2+4ac-2a^2}{3c^3+2ac}$ and $\cot^2 \frac{\theta}{2}=\frac{1+\cos \theta}{1-\cos \theta}=\frac{(c+a)(3c-a)}{a^2}$
By using Heron's area formula,
$16[ABC]^2=a^4 \cot^2 \frac{\theta}{2}$
$[ABC]=\frac{1}{4}a^2 \cot \frac{\theta}{2}$
Is there any other way/method to solve this question? Thanks in advance.
Answer: In the picture we have as a model the triangle $\Delta ABC$ with sides $a,b,c$ equal to respectively $15,18,12$. OP also mentions the formula for $b^2$, here is an "other way" to obtain it.

After construction, geogebra confirms optically that the angle bisector in $B$, the perpendicular bisector of $BC$ and the side $AC$ are concurrent, this means that $\hat B=2\hat C$. (I will no longer use the hats, this should be clear in the given context.)
Lemma: $$\bbox[yellow]{\qquad AD = c+\frac{2a}3\ .\qquad}$$
Proof:
Let $R$ be the circumradius, then:
$$
\begin{aligned}
b&=2R\sin B=2R\sin 2C=2R\cdot 2\sin C\cos C=2c\cos C
=2c\cdot\frac{a^2+b^2-c^2}{2ab}\ ,\text{ so}
\\
ab^2 &=c(a^2+b^2-c^2)\ ,\\
b^2(a-c)&=c(a^2-c^2)=c(a+c)(a-c)\ ,\text{ thus giving a formula for $b^2$,}\\
b^2&=c(a+c)\ .\\[3mm]
&\qquad\text{ From here we compute $AD^2$ in $\Delta ABD$:}\\[3mm]
\cos B&=\frac{a^2+c^2-b^2}{2ac}=\frac{a^2-ac}{2ac}=\frac{a-c}{2c}\ ,\\
AD^2
&=BA^2+BD^2-2BA\cdot BD\cdot \cos B
\\
&=c^2+\frac {16}9a^2-2 c\cdot\frac {4a}3\cdot\frac{a-c}{2c}
=c^2+\frac 43ac+\frac 49a^2
=\bbox[yellow]{\left(c+\frac{2a}3\right)}^2\ .
\end{aligned}
$$
$\square$
Note: The values $15,18,12$ in the picture are so that $b^2=18^2=12(15+12)=c(a+c)$. The converse is with the same argument true,
if we have the relation $b^2=c(a+c)$, then $B=2C$.

We can start now the final computation. Recall a formula in "some other triangle" $A'B'C'$ with usual notations enlarged with the prime decorator. The sides are for instance $a',b',c'$, the semiperimeter is $s'=\frac 12(a'+b'+c')$ and so on. Then as for instance mentioned here, we have:
$$
\cot\frac {A'}2
=\sqrt{\frac{s'(s'-a')}{(s'-b')(s'-c')}}
=\frac{\sqrt{s'(s'-a')(s'-b')(s'-c')}}{(s'-b')(s'-c')}
\overset{\text{Heron}}=
\frac{\operatorname{Area}[A'B'C']}{(s'-b')(s'-c')}\ .
$$
We apply this formula in the triangle $\Delta A'B'C'=\Delta ABD$, its angle in $A'$ is with the OP notations $\theta$, so we have step by step:
$$
\begin{aligned}
a'&=\frac{4a}3\ ,\qquad b'=\bbox[yellow]{c+\frac{2a}3}\ ,\qquad c'=c\ ,\\
s'&=\frac 12(a'+b'+c')=a+c\ ,
\qquad s'-b'=\frac a3\ ,\qquad s'-c'=a\ ,\\[4mm]
\operatorname{Area}[ABC]
&=\frac 34\operatorname{Area}[ABD]
=\frac 34(s'-b')(s'-c')\cot\frac \theta 2
=\frac 34\cdot\frac a3\cdot a\cdot\cot\frac \theta 2
\\
&=\frac 14a^2\cot\frac \theta 2\ .
\end{aligned}
$$
$\square$
Comment: This is really a good answer!
Answer: Since $\angle ABC \cong 2\angle ACB$ we can "carve out" triangle $ABC$ from an isosceles trapezoid $ABCE$, with $AB \cong AE \cong CE$, as in the Figure below, where, in addition, $M$ is the midpoint of $AE$, $N = AD \cap CM$, and $H$ is the projection of $A$ on the trapezoid base $BC$. Observe that
$$[ABC] = [BMC] = \frac14 \overline{BC}^2 \cot \left(\frac{\measuredangle BMC}2\right),$$so that the assertion is proved once we show that
$$\angle BAD \cong \angle BMC\tag{1}\label{1}.$$
We will prove that $$ABN \sim BMC,$$ which in particular implies \eqref{1}.

For simplicity let $\overline{BC} = 1$ and $\overline{AB} = x$.
Applying twice Pythagorean Theorem we can first determine the altitude of the trapezoid $$\overline{AH} = \frac{\sqrt{3x^2+2x-1}}2,$$
and then
$$\overline{AD} = x+\frac23.\tag{2}\label{2}$$Incidentally, observe that \eqref{2} is the expression mentioned in dan_fulea's answer, and that this expression shows $A$ lies on a hyperbola with focii in $B$ and $D$.
Similarity $AMN \sim CDN$ (AAA criterion), with similarity ratio $\frac{3x}2$, leads to $\overline{AN} = x$ and $\overline{DN} = \frac23$. As a result we have, by SAS criterion, $BND \sim CND$, yielding $\angle BND \cong \angle NCD$, and, by supplementarity, $$\angle ANB \cong\angle BCM.\tag{3}\label{3}$$Having already proved that $ABN$ is isosceles, \eqref{3} is enough to conclude that $ABN \sim BMC$ (AAA criterion), as desired.
$\blacksquare$


Correct way to start a BackgroundService in ASP.NET Core

Question: I have implemented a BackgroundService in an ASP.NET Core 2.1 application:
public class MyBackgroundService : BackgroundService
{
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (true)
        {
            await DoSomethingAsync();
            await Task.Delay(10 * 1000);
        }
        return Task.CompletedTask;
    }
}

I have registered it in my ConfigureServices() method:
services.AddSingleton<MyBackgroundService>();

I am currently (reluctantly) starting it by calling (and not awaiting) the StartAsync() method from within the Configure() method:
app.ApplicationServices.GetService<SummaryCache>().StartAsync(new CancellationToken());

What is the best practice method for starting the long running service?
Comment: Is there any way to stop the background service starting automatically and instead start on demand?
Comment: Check out Steve Gordon's blog: https://www.stevejgordon.co.uk/asp-net-core-2-ihostedservice
Comment: By default, after registering `services.AddSingleton();`, it will start when application start, there is no need to call `StartAsync()` expecitly from your own code.
Comment: @junnas This unfortunately appears out of date (ASP.NET 2.0 preview before BackgroundService was made available) and it doesn't explain how to make a service start without explicitly invoking StartAsync()
Comment: Would hangfire be an option? https://www.hangfire.io/
Comment: I implemented a background service using Steve Gordon's approach that runs on 2.2 preview 2 though?
Comment: Possible duplicate of [Proper way to register HostedService in ASP.NET Core. AddHostedService vs AddSingleton](https://stackoverflow.com/questions/51480324/proper-way-to-register-hostedservice-in-asp-net-core-addhostedservice-vs-addsin)
Answer: Explicitly calling StartAsync is not needed.
Calling
services.AddSingleton<MyBackgroundService>();

won't work since all service implementations are resolved via DI through IHostedService interface.
edit:
e.g.
    svcProvider.GetServices<IHostedService>() -> IEnumerable<IHostedService>
You need to call either:
services.AddSingleton<IHostedService, MyBackgroundService>();

or
services.AddHostedService<MyBackgroundService>();

edit:
AddHostedService also registers an IHostedService: https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicecollectionhostedserviceextensions.addhostedservice?view=aspnetcore-2.2
Comment: * to discover all background services to be run, the framework relies on DI and would call servcies.GetServcies() which yields IEnumerable. This resolves your service if you register via the Interface. .AddHostedService() does exactly that (https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicecollectionhostedserviceextensions.addhostedservice?view=aspnetcore-2.2)
Comment: what if for test purposes I want to create multiple instances of background services dynamically based on web API call? then can I call StartAsync?


Cookie authentication when reguistering users through REST API

Question: I am running Drupal 9 commerce 2.0 as headless CMS, and I am trying to integrate the user registration/user login part of my frontend application. I was able to use the user/register REST API to create users. The default (only option without other modules) authentication was cookie authentication. What I am trying to understand is how the cookie authentication works. When running curl -d @data.json http://example.com/user/register?_format=hal_json --header "Content-Type:application/hal+json" for example, everything works perfectly fine, and the user is created. But don't I need to add a Set-Cookie header for this to work since the REST API has cookie authentication checked? How does this cookie authentication work?
Comment: The cookie header should be in the response, correct? Is this just registering, or are you authenticating that new user somewhere?
Comment: Set-Cookie is a response header not a request header.
Comment: Right, the client would then have it. With Curl, there is additional handling needed - see https://www.drupal.org/node/1795770
Comment: This site is set up to answer one question at a time.
Comment: Thanks, edited.
Answer: When you perform a login using the login endpoint you'll get a cookie back (as well as a CSRF token) which you can then use for subsequent requests instead of doing a fresh login every time.
So with curl something like this:
curl --header "Content-type: application/json"
  --request POST \
  -s -c cookie.txt \
  --data-binary '{"name": "user1", "pass": "pass1"}' \
  https://.../user/login

Would get you back a cookie in cookie.txt and the json response will contain your CSRF token.


Back button on pages with tabs

Question: I'm doing a system where the pages are displayed by tabs (easytabs Plugin http://os.alfajango.com/easytabs/#tabs1-js)
At one point in the process it performs a query in the database, where we
see all the details of each item that appears. I'd like to go into the details of the item, click back to the (on broswer or a button) the page to return to the list displayed by the SQL query, just as with any single page, but currently it only displays a blank page.
I wonder how can I do to implement this solution using the layout tabs.
Thank you.
Comment: We're going to need some code.
Answer: There are various ways to maintain UI state. One of them is using a "url hash". For example, you click tab 2, change the url hash to:
mypage.php#tab=2
Then if someone presses BACK and goes FORWARD, you use JavaScript to look at the URL has and determine that the user had previously pressed tab 2, so you run your own bit of code that triggers the same event.
I'm unfamiliar with "easytabs" so I'm sorry I can't help with the specific implementation details, but that's the gist of the technique.
Comment: Tks. Change the tab I can do, I do not know when it is back showing the same query the database that had been displayed (without having to redo the select). There needs to be with this plugin.

Back button on pages with tabs


Can Latent Class Analysis entropy be infinity? And what does it mean?

Question: I recently ran a latent class analysis with polytomous outcome variables with the poLCA R package.
The model ran fine converged from 2 to 6 classes (the model converged with more classes but fit indices suggested that fit got worse so I stopped at 6 classes.
While the models converged correctly, it's not able to get the entropy statistic. I normally try to get relative entropy (similar to what MPLus gives) using the code provided in an answer of another question here. It's worked well for me in the past and I was able to get the relative entropy for the models of 2 and 3 classes but gives me a
>NaN

value when I attempt to run it for 4 classes and above. I found this to be odd so I attempted to just get the entropy statistic poLCA gives me with the command
polca.entropy(model)

and that causes Rstudio to just run forever and crash even for 2 and 3 class models that previously got me the relative entropy. What does this mean for the models and is it anything to be concerned about?
I had previously read that BIC is a better measure of model fit for ordered or polytomous outcome variables so I usually never use entropy for anything other than to just report it for the sake of reviewers who are more accustomed to seeing the relative entropy.
Answer: Addressing your last paragraph first: Kathryn Masyn, who wrote [a chapter][1] about latent class and latent profile models in the Oxford Handbook of quant methods (2013), described entropy as a characteristic, not a model selection criterion. On page 570 of the PDF, she says (emphasis mine):

Because even when $E_K$ is close to 1.00 there can be a high degree of latent class assignment error for particular individuals, and because posterior classification uncertainty may increase simply by chance for models with more latent classes, $E_K$ was never intended for, nor should it be used for, model selection during the class enumeration process. However, $E_K$ values near 0 may indicate that the latent classes are not sufficiently well separated for the $K$ classes that have been estimated (Ramaswamy et al., 1993).

Masyn is talking about normalized entropy above, which ranges from 0 to 1. I'm not sure if poLCA gives normalized or non-normalized entropy. Regardless, entropy should not be able to equal infinity.
Normalized entropy is defined in Masyn as:
$E_K = 1 - \frac{\sum_{i = 1}^n\sum_{k = 1}^K[-\hat p_{ik}ln(\hat p_{ik})]}{n * ln(K)}$
Where $n$ indexes individual observations, $K$ indexes all the latent class you identified (e.g. say your final model is 4-classes, $K=4$), and $\hat p_{ik}$ is the model-estimated probability that the $i$-th person belongs to the $k$-th latent class (i.e. there are $K$ such probabilities for each person).
If entropy is displaying as NaN, I'd suspect some sort of error, and it's not saying the entropy is actually infinity. Maybe it's a programming error (unlikely?). Maybe this is what happens if some observations have some missing data (also unlikely, I think?), or maybe some observations have all indicators missing and this is causing their probabilities to be missing? I'd email the author. No way to provide insight from this end, especially considering that I don't use this package.
A later update: the R package referenced in the question defines entropy differently
I've been using the R package poLCA, written by Drew Linzer. He calculates entropy quite differently. I haven't verified if this produces equivalent or comparable results to the formula I gave above. If I read the manual correctly, he sums up:
$E_L = -\sum_c p_c * ln(p_c) $
Where the subscript L is for Drew Linzer, the package author, $p_c$ is the probability in each cell of the cross-classification table generated by the model, and $c$ indexes cells. By cross-classification table, he means the probability of each response pattern. With $i$ indicators, each of which has $j$ levels, there are $j^i$ total response patterns. This doesn't change the statement that entropy can't be infinity, even if it's not normalized. However, in this formulation, the maximum value of $E_L$ is the natural log of the total number of cells in the cross-classification table. Thus, if you normalized entropy using the denominator I provided above, that was wrong. I apologize if this has led anyone astray; I was only familiar with the formulation I originally quoted (which I believe MPlus uses).
You can verify this yourself by reading the manual entry for the poLCA.entropy function itself. Linzer gives an example of using the carcinoma dataset provided by the package, and fitting a 2-class LCA model with 7 binary indicators (A thru G, coded as 1s and 2s) to the data.
f <- cbind(A,B,C,D,E,F,G)~1
lca2 <- poLCA(f,carcinoma,nclass=2)

# Maximum entropy (if all cases equally dispersed)
log(prod(sapply(lca2$probs,ncol)))
poLCA.entropy(lca2)
````
If you run that code, you will find that the stated max entropy is 4.85203, the exponent of which is 128. That is $2^7$.

  [1]: https://www.statmodel.com/download/Masyn_2013.pdf

Comment: Thank you for your answer! The source you provided was easy to follow. poLCA gives non-normalized entropy, which is the reason why I had to use a separate set of codes to get the relative one that ranges from 0-1.0. It shouldn't be a programming error since it's the same code I used before (and worked) nor should it be due to missing data. I think part of it was that poLCA doesn't handle ordinal variables, only polytomous categorical variables, but my DVs were all ordinal. I ran LPA instead and that gave me the entropy!
Answer: I had a similar problem when computing normalized entropy based on the Mplus formula (https://www.statmodel.com/download/UnivariateEntropy.pdf).
#formula Mplus
#z: the matrix of the posterior probabilities for each subject for each class
nume.E<- sum(z * log(z))
##Denominator (nlog(K)): ## n is a sample size, and K is a number of class
deno.E <- nlog(K)
##Relative Entropy
E <- 1+(nume.E/deno.E)
E
The reason for getting NaN was that some values of the posterior probabilities were = 0, the derived ln was -Inf, and the sum returned NaN. I solved by specifying na.rm=T to the sum formula.
I'm not sure if the E values is biased or if it is ok to have 0 as a posterior probability.


How can I print the country value from my JSON file in Swift?

Question: I know that this could be an easy answer, but for me is difficult.  I have a Swift JSON file that loads successfully into my UserData variable.  But I want to get a value from that data set.  I get the error:  Value of type '[UserData]' has no member 'state'
[
  {
    "state":"Alaska",
    "latitude":61.3850,
    "longitude":-152.2683,
    "stateTax":"7%"
  },
  {
    "state":"Alabama",
    "latitude":32.7990,
    "longitude":-86.8073,
    "stateTax":"13.5%"
  },
  {
    "state":"Arkansas",
    "latitude":34.9513,
    "longitude":-92.3809,
    "stateTax":"11.625%"
  }
]

My data set UserData:
[LoadFromJSON.UserData(state: "Alaska", latitude: 61.385, longitude: -152.2683, stateTax: "7%"), LoadFromJSON.UserData(state: "Alabama", latitude: 32.799, longitude: -86.8073, stateTax: "13.5%"), LoadFromJSON.UserData(state: "Arkansas", latitude: 34.9513, longitude: -92.3809, stateTax: "11.625%")]

My code and the error line:
 do {
                let data =  try Data(contentsOf: fileLocation)
                let jsonDecoder = JSONDecoder()
                let dataFromJson = try jsonDecoder.decode([UserData].self, from: data)

                self.userData = dataFromJson

                print(userData)
                print(dataFromJson.state)  // Value of type '[UserData]' has no member 'state'

            } catch {
                print(error)
            }

Comment: `dataFromJson` is an array of `UserData`, if you want to print out the `state` you need to get a specific instance from the array (e.g. `dataFromJson.first?.state`)
Comment: @shim it will only print for first user.
Comment: That is just an example, OP gave no indication of what he was trying to do
Comment: You are right, indeed.
Answer: dataFromJson is array of UserData, so you need to iterate like this.

do {
                let data =  try Data(contentsOf: fileLocation)
                let jsonDecoder = JSONDecoder()
                let dataFromJson = try jsonDecoder.decode([UserData].self, from: data)

                self.userData = dataFromJson
                dataFromJson.forEach{ user in

                    print(user.state)

                }

                print(userData)

            } catch {
                print(error)
            }


How to connect to a Firestore database with Ruby

Question: I'm trying to write and read to and from my Firestore database from a Ruby script, eventually from a Rails application.
It seems like a trivial task but when I run a test script inside IRB it won't let me write or read data.
I tried:

successfully installed google-cloud-firestore gem
downloaded JSON keyfile from within the Firestore console.
security rules are set to public (read and write)

require 'google/cloud/firestore' # => true

# credentials
cred = Google::Cloud::Firestore::Credentials.new('<path/to/my/keyfile/key-projectname-etc.json>')
# => #<Google::Cloud::Firestore::Credentials:...>

# initialize firestore connection
db = Google::Cloud::Firestore.new(
  project_id: '<MY-PROJECT-ID>',
  credentials: cred
) # => #<Google::Cloud::Firestore::Client:...>

# write a document inside the users collection
db.doc("users/helloFromRuby").set({ name: "yay it worked!"})

This is the error message I get:
Google::Cloud::UnavailableError (14:failed to connect to all addresses)

Comment: Failure to connect doesn't have to be a Ruby problem. Have you checked to see if you have connectivity and it's pingable as it might be a network error.
Comment: Yeah you were right, it was an issue that i had an environmental variable (`GOOGLE_APPLICATION_CREDENTIALS`) that was set, which probably interfered with my keyfile. Anyways deleting this env variable resolved the issue. Thanks for your comment and input.
Comment: Please don't use "EDIT" or "UPDATED" tags in questions or answers. SO already has revision control and we can see what's changed if necessary. Instead add your change where you would have put it if you'd said it originally. Also, since that was the solution, create an answer, writing that as if you were instructing yourself. After a timeout period SO will let you select the answer as the appropriate solution. Congratulations on your first self-answered question!
Answer: I could resolve my issue: I had an environmental variable GOOGLE_APPLICATION_CREDENTIALS initialized that was somehow interfereing with my json keyfile. Deleting that variable solved my issue.


Looking for a JavaScript library for displaying calendar data

Question: I'm looking for a JavaScript calendar which can be used for displaying data in a nice calendar view. I would need to provide the calendar with a list of established events which have dates and other information, such as a URL to link to and text to be displayed on the calendar. I would also need to tell the calendar which view to render, whether it be a year, month, or even week.
Unfortunately my Google-Fu is failing me as every calendar I find is used for selecting a date as an input. I'd be willing to pay money, but even CodeCanyon doesn't have anything decent.
Answer: If you are willing to use something based on jQuery, a number of folks appear to be happy with FullCalendar.
I haven't used it myself, but it has day/week/month support out of the box, and hooks to let you populate, retrieve/store, change look and feel, etc.
P.S. The Google search that I used was intitle:calendar jquery day month week


Expression With and Union All to EF Core

Question: I want to convert this SQL query to EF Core code.
I don't want to use LINQ, any possibility?
<code>with cat (id, id_parent, name) as
(
    select id, id_parent, name
    from categories
    where categories.id = 9

    union all

    select e.id, e.id_parent, e.name
    from dbo.categories e
    inner join brands b on b.id_parent = e.id
);
select * from cat;
</code>
Comment: Why are you using EF if you don't want to use LINQ? LINQ to Entities is how you do queries in EF, unless you want to write your own Entity SQL, which should only be done if you can't achieve what you want using LINQ. Do you actually mean that you don't want to use LINQ to Objects?
Comment: It looks like you're trying to build a recursive query. Note that if you cause EF Core to load the records you are interested in, the framework will link navigations together to build the hierarchy for you.
Comment: what have you tried so far?
Comment: Do you mean that you want to use Linq method syntax? (https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq)
Comment: There are multiple methods that you can use: ``Union``, ``Concat``
Answer: If I get your question correctly this would work for you:
<code> var result = await _dbContext.Categories
                .Where(x => x.Id == 9)
                .Select(x => new { Id = x.Id, Parent = x.IdParent, Name = x.Name})
                .Concat(
                    _dbContext.Categories.Join(_dbContext.Brands, cat=> cat.Id, brand=> brand.IdParent, (cat,brand)=>cat)
                    .Select(x => new { Id = x.Id, Parent = x.IdParent, Name = x.Name }))
                .ToListAsync();
</code>


Fastest SVM implementation

Question: More of a general question. I'm running an rbf SVM for predictive modeling. I think my current program definitely needs a bit of a speed up. I use scikit learn with a coarse to fine grid search + cross validation.
Each SVM run takes around a minute, but with all the iterations, I'm still finding it too slow. Assuming I eventually multi thread the cross validation part over multiple cores, any recommendations on speeding up my program? Any faster implementations of SVMs? I've heard of some GPU SVMs, but haven't digged into it much. Any users and is it faster?
Comment: SGDClassifier in scikit-learn is *very* fast, but for linear SVMs. You might ask the scikit-learn guys, also add tag scikit-learn.
Comment: You can speed up by using specialized tuning libraries for hyperparameter search, which are way more efficient than grid search (ie. require testing far less sets of hyperparameters). Examples of tuning libraries include [Optunity](http://www.optunity.net) and Hyperopt.
Comment: Non-linear kernel SVM are doomed to be slow. Perhaps you should start playing with linear models (check out Vowpal Wabbit) and then go to non-linear. You can even get some non-linearity by creating more complicated features with linear models. Quite often non-linear models result in some incremental performance increase at big computational expense. Nothing against non-linear kernel SVM but just to keep in mind, from practical point of view.
Answer: Google's Sofia algorithm contains an extremely fast implementation of a linear SVM.  It's one of the fastest SVMs out there, but I think it only supports classification, and only supports linear SVMs.
There's even an R package!
Comment: Your link now says "package 'RSofia' was removed from the CRAN repository." Any idea why?
Comment: @JamesHirschorn The developer probably stopped maintaining it. You can install it from the CRAN archive.
Answer: The easiest speedup you're going to get is running the cross-validation in parallel.  Personally, I like the caret package in R, which uses foreach as a backend.  It makes it very easy to farm the cross-validation and grid search out to multiple cores or multiple machines.
Caret can handle many different models, including rbf SVMs:
<code>library(caret)
library(doMC)
registerDoMC()
model <-  train(Species ~ ., data = iris, method="svmRadial",
    trControl=trainControl(method='cv', number=10))
> confusionMatrix(model)
Cross-Validated (10 fold) Confusion Matrix

(entries are percentages of table totals)

            Reference
Prediction   setosa versicolor virginica
  setosa       32.4        0.0       0.0
  versicolor    0.0       30.9       2.0
  virginica     0.9        2.4      31.3
</code>
Note that the doMC() library is only available on mac and linux, it should be run from the command line, not from a GUI, and it breaks any models from RWeka.  It's also easy to use MPI or SNOW clusters as parallel backend, which don't have these issues.
Comment: Thanks Zach. I believe scikits also has a way of running cross validation in parallel which is what I plan to do. Excluding that, any other suggestions on speedup? Thanks.
Comment: @danjeharry: parallel cross-validation is really the low hanging fruit here, and I strongly suggest you explore that first.  Beyond that, I don't know a lot about speeding up SVMs specifically.  If you can find a parallel SVM algorithm, that might be a good idea too.  How many rows/columns is the data set you're using to train?
Comment: Thanks Zach I will look into parallel cv. I'm doing about 650 attributes and 5000 examples.
Answer: I realize this is a quite old question, but it's also possible (depending on the size of your dataset it can be more or less effective) to use low-dimensional approximations of the kernel feature map and then use that in a linear-SVM. See http://scikit-learn.org/stable/modules/kernel_approximation.html
Answer: Have a look at Python's multiprocessing module. It makes parallelizing things really easy and is perfect for cross validation.
Answer: R has a great GPU-accelerated svm package rpusvm, it takes ~20 seconds to train on 20K samples*100 dimensions, and I found that the CPU is never overloaded by it, so it uses the GPU efficiently. However, it requires a NVIDIA GPU.
Comment: It also requires purchasing an `rpudplus` license.
Answer: Alert: This is a shameless plug.
Consider DynaML a Scala based ML library I am working on. I have implemented Kernel based LS-SVM (Least Squares Support Vector Machines) along with automated Kernel tuning, using grid search or Coupled Simulated Annealing.
http://mandar2812.github.io/DynaML/

Fastest SVM implementation