Integrate JQuery with HTML

Question: Problem :

How can I integrate my jQuery code with HTML?
The code is working in Chrome console but I have to integrate it with HTML
How should i call the below jQuery code in HTML?

Code:
$(function () {
    $('.ibody tr').each(function (a, b) {
        var count=0;
        var name = $('.cl', b).text();
        if(name.indexOf(".CSV")!==-1 && name.indexOf("TAS")!==-1){
            var d= a-9;
            var hiddenIFrameID = 'hiddenDownloader' + count++;
            var iframe = document.createElement('iframe');
            iframe.id = hiddenIFrameID;
            iframe.style.display = 'none';
            document.body.appendChild(iframe);
            iframe.src = `https://www.shipper-ml.com/viewReports.do?
ctrl=reportListForDownload&action=DownloadReport&param=${d}`;
        }
    });
});

Comment: place it inside a  tag after importing Jquery.
Comment: import your jQuery: ``, then add your script inside script tags: ``. If this "doesn't work", try to debug using the console (ctrl+shift+i in Chrome, or f12). If it doesn't work, then it's not related to *"How can I integrate my Jquery code with HTML."* and you should ask a different question.
Comment: Hi Martin, I tried but still it's not working. My JQuery code is wroking properly in chrome console but i want to integrate it with HTML and I am not able to do that. Can you please help ?
Comment: Hi Martin, I am getting below errors :
Failed to load resource: net::ERR_FILE_NOT_FOUND
Uncaught ReferenceError: $ is not defined at test.html:7
Answer: Your Script

and if you wanted to call the function either on a button click you could do like this for example
 <!DOCTYPE html>

// let us say this is your jquery function

This is a heading

This is a paragraph.

This is another paragraph.

    <button>Click me</button>

Comment: Hi Jelord, Thanks for such a quick response. I have tried it but it's not working :(
Comment: just include you're script on you're html
Answer: JQuery is nothing but a javascript helper library. So to use any library, first you need to tell HTML that you are writing some functions from that library.
To do that , we need to include the library before you write any code that uses that library. In your case Jquery.
So 1st add the library using

Then you can use any functions from that library.. in the same HTML file or in a different js file.
To use it in the same HTML file, write your code in the   tags.

To use it in a different file,
add your code in a new file (mycode.js), and use the relative path to it in the html file

Integrate JQuery with HTML


a basic doubt about definition in graph theory

Question: Friends, I have a very basic doubt about neighborhood of a vertex. I was going through some pdf and their it was written about i-th neighbor of v, $v \in V(G)$.  Can anybody explain me the term i-th neighbor. Thanks a lot.
Comment: I think that we'll need a bit more context; do you have a link to the PDF?
Comment: @BrianM.Scott Sir, here is the link www.cs.huji.ac.il/~advtheory/lect07.pdf
Comment: Thanks; that makes it possible to answer the question.
Answer: Notice this statement in Definition $\bf1$: for each vertex $v\in G$ fix an ordering of $v$'s neighbors.
Here that means that if $v\in G$ and $N$ is the set of vertices adjacent to $v$, we number the vertices in $N$, so that $N=\{v_1,v_2,\dots,v_m\}$, where $m=|N|$. The $i$-th neighbor of $v$ is then the vertex $v_i\in N$. If $v$ has $3$ neighbors, say $a,b$, and $c$, we could order them in any of $3!=6$ different ways, and each of those ways would produce a slightly different zig-zag product. This blog post about the zig-zag graph product may be helpful: it has some diagrams as well as some discussion.
Answer: I think it is the set of vertices with the distance $\le i$ from $v$.
Comment: That was my first thought, too, but it turns out to be wrong in this case.


Is Beethoven's title "Sonata quasi una Fantasia" an oxymoron, and does the title instruct how to perform it?

Question: Beethoven's so-called "Moonlight" Sonata is fully titled "Sonata quasi una Fantasia".
Google translates this literally to "Sonata almost a Fantasy", but I'll assume it means more like "Sonata in the style/manner of a Fantasy".
As a Sonata is a specific musical form - albeit one which evolved through the eras - and a Fantasy is a free, improvised piece which doesn't follow any form, is this title not an oxymoron?
How can something written with a defined form be "like" something without one - aren't they mutually exclusive?
To my mind, it's a bit like saying "Counterpoint in the style of homophony".
Contradictions aside, does this title offer any hints as to how it is to be performed; would it be any different were it simply "Sonata"?
Comment: It certainly sounds like an oxymoron to me. From what little I've read about Beethoven, it seems in keeping with his unique character.
Comment: @luserdroog The music I have is marked *adagio sostenuto*, but it's notated as a quarter note equaling 50bpm, so I would say "super largo" is pretty accurate, actually =)
Comment: @JoshDarnell that metronome marking is not Beethoven's.
Comment: www.imslp.org/wiki/Piano_Sonata_No.14,_Op.27/2_(Beethoven,_Ludwig_van) -this link has the sheet music and multiple performances of the piece.
Comment: Another weirdness is that the tempo is, IIRC, Andante; but everybody plays it super largo.
Answer: The other one in the same opus is also a "Sonata quasi una Fantasia" and is more obviously one.  It doesn't break down cleanly into movements but appears to start a movement, suddenly go into another one, and then come back to the first one again.  A "Fantasia", for instance one of Mozart's, has a kind of "anything goes" improvisatory feel, where a "movement" doesn't really end but just before the final chord has a transition to a completely different idea.  Often the first idea comes back later in the piece.
The "Moonlight" is less of a "Fantasia"; maybe Beethoven just wanted to have two pieces named "Sonata quasi una Fantasia" in the same opus number.  There are two Fantasia-like things about the Moonlight:  1. The first movement really is an oddball piece.  Sonata first movements are usually fast, dramatic pieces.  This one is more-or-less in "Sonata Form" but not like any other sonata or symphony first movement. 2. Each movement is supposed to be played immediately after the previous one without pause (although there are no transitions as in a fantasia).
Now for performance practice:  Look up what Andras Schiff has to say about this piece, if you can find it.  He gave a series of lectures in London that were recorded and available online from The Guardian (newspaper in England) for a short time.  Most pianists play the first movement much too slowly.  Note that it is marked in 2/2 time (C with a line through it, sometimes called "cut time").  Adagio sostenuto, two beats per measure.  The figuration (triplet accompaniment, "dunt - da - Dah" in the treble) comes originally from a short passage in Mozart's "Don Giovanni".  (Schiff says that as a student Beethoven copied this passage by hand; the copy still exists in a museum.)  The piece is actually a funeral march, not four steps per measure but a very slow two steps per measure.  According to someone (Czerny?  I forget who), Beethoven himself played it at half-note = 60.
Beethoven tells you to keep the damper pedal down for the entire first movement, and he means it.  Should this be done on a modern piano?  Well, the typical good-quality grand pianos of Beethoven's day had the same sustain time as modern pianos.  I know because I've played some of them at the Frederick Collection.  (Schumann's "Papillons" shows that his pianos had long sustain times too.)  Beethoven uses the effect in another sonata as well.  He liked this effect:  it's like playing music or speaking in a vault or cave.  Perhaps this is a funeral march that marches right into a large mauseleum.  Remember that it also must be played very delicately and always pianissimo.  He says so right there in the first measure.
Comment: +1 "right there in the first measure." It's very easy to skip a marking you don't understand. . People are like cats; get away with it twice and it's a habit. Even coming back to the same old piece for the 1000th time, I frequently notice little markings I didn't even see the first 999 times. It's almost like a macro/micro-cosm thing. Can't even *really* play measure one without knowing how to play the whole thing.
Comment: Sustain time is not the only factor bearing on whether to hold the pedal down for the entire piece.
Answer: When you listen to it, does it feel like a sonata? Or does it feel a little bit looser, with a wee bit of unstructured-ness about it.
That's what I always read into it, anyway: a hint of the fantasy, as well as a hint of the fantastic.
Comment: A beautiful moody piece in any century and so very very Beethoven.


Can t-SNE help feature selection?

Question: I'm training a fully connected feed forward neural network for regression.
Given one training example $(x_i, y_i)$, I need to convert the raw representation $x_i$ into an invariant representation $x_i^{'}$ of higher dimensions by some non-linear transformation
$$x_i^{'} = f_{\theta}(x_i)$$
$\theta$ is the hyperparameter determines such a transformation, the dimensionalities of $x_i$ and $x_i^{'}$ are about $150$ and $4500$ respectively.
This transformation step cannot be accomplished by a neural network layer because the original representation is not invariant under translation. The original representation has to be transformed by some map controlled by $\theta$, and the map is constructed based on domain knowledge.
To choose a good hyperparameter $\theta$ is not easy, so I wonder whether dimensionality reduction can help me to make a good choice.
My idea is:
If a resulting representation $\{x_i^{'}\}_{i = 1}^N$ preserves much of the topological structures of the raw representation $\{x_i\}_{i = 1}^{N}$, then it is reasonable to believe it will be good for regression. The topological structure of the raw input can be probed by the domain knowledge, to probe the structure of the resulting representation, I decided to use t-SNE because of its non-linear nature.
However, by playing with t-SNE on this beautiful site, I found the result given by t-SNE is quite sensitive to the choice of perplexity, iterations and learning rate, and it seems only qualitative conclusions can be made by plotting the result.
Is my idea reasonable? Is there a better choice for a quick dimensionality reduction?
Comment: Could you clarify your "need" to convert the raw representation into something lower dimensional? A neural network will do exactly that, and likely better than tSNE as the training is supervised. If you're trying to cheaply and significantly widen your feature space, try a gradient-boosted-random-forest instead.
Comment: @Alex R I have explained why I need to convert the representation in the post, the reason is the representation has to be made invariant under translation, then the converted representation is taken to be the neural network input.
Comment: Why can't the neural network use convoultional layers, which absolutely would be translation invariant.
Comment: @Alex R. I don't know too much about CNN, but I guess those are two different kinds of translation. The original data vectors here are Cartesian coordinates of the $n$ bodies consists of some system, so the translation I'm referring to is to translate the center of mass of the system.
Comment: Can you say more about what it means to 'probe the topological structure'? How exactly do you want to use the t-SNE outputs?
Comment: I think the question: *[Why is t-SNE not used as a dimensionality reduction technique for clustering or classification?](https://stats.stackexchange.com/questions/340175)* is very relevant to this question.
Answer: No, I'm afraid your idea is not reasonable, for two reasons. Firstly, t-sne is a nice tool for decorative pictures, but it doesn't give you any reliable information to base decisions on. As you already noticed, it is very sensitive to the choice of parameters. Different parameters lead to different images which in turn lead to different conclusions regarding virtually all properties you might want to read off such a plot, and you have no way of knowing which of these parameter choices is the one leading to a correct conclusion (if any). You don't have to take my word for it; you can find a sufficient number of very simple examples here.
If you'd like a better alternative, you may want to think about why you need to evaluate the choice of $\theta$ at all. Your mapping goes from a lower-dimensional space into a higher-dimensional one. So it is plausible to assume that you're not loosing information, i.e., different choices for $x_i$ lead to different choices for $x_i'$ (of course, you have to check that with your concrete mapping).
This means that you might even be able to choose an arbitrary value for $\theta$ and just trust that your feedforward network will figure out the meaning of the resulting representation. So, in all likelihood we're not talking about a situation where you have to find one of very few values for $\theta$ to make your regression work at all. It is much more likely that the choice of $\theta$ has more of a gradual influence on the outcome: With some choices, the neural network will perform better than with others.
Of course choosing just one arbitrary value is just a thought experiment. In practice, I would recommend not to try and choose $\theta$ in a separate step before fitting the neural network, but rather treat it as an additional hyperparameter which has to be optimized along with the neural network parameters (such as number of layers etc.).

Can t-SNE help feature selection?


Migrate asterisk config files to database configuration

Question: Does anyone have documentation or tooling to help migrate from a config file based asterisk deployment to a database deployment?
Answer: I don't have an automated migration script, but the gist is that you make with an extconfig.conf file that maps a traditional config file name to a table name (and set of MySQL or ODBC/DB credentials), and then a set of tables with slightly normalized (but nearly line-for-line) equivalents to what would be in a local config file.  http://www.voip-info.org/wiki/view/Asterisk+RealTime has more.
Another way to do realtime database-backed call routing is using AGI or Fast AGI.  We recommend AGI to our Asterisk hosting customers because it decouples call routing logic from phone/PBX functionality, something that's not at all true with an Asterisk dialplan (Asterisk RealTime or not).  Your dialplan then uses the AGI command (with an agi:// URL) instead of calling embedded dialplan commands.
That also lets you write the call logic/routing in whatever programming language does the job best, which is rarely AEL.  help.cloudvox.com has a bunch more AGI docs.
Troy
Answer: I was looking for the same thing and ended up writing my own quick and dirty script using Asterisk::config modules from CPAN, hope it saves sometime of somebody else:
<code>#!/usr/bin/perl
use Asterisk::config;

my $rc = new Asterisk::config(file=>$ARGV[0]);
my $cols="";
my $vals="";

$parsed = $rc->fetch_sections_hashref();

foreach my $sec (sort keys %{$parsed})
{
    $cols="name";
    $vals="'$sec'";
    while ( my ($c, $v) = each(%{$parsed->{$sec}}) )
    {
        $cols.= ",$c";
        $vals.= ",'".join(',',@{$v})."'";
    }
    print "insert into mytable($cols) values($vals);\n";
}
print "\n\n";
</code>


Set BorderPane components size

Question: I want to set the size of the Center, Top, Left, Right and Bottom components of a BorderPane.

So far I found this:
BorderPane() mainpane = new BorderPane();
mainPane.getBottom().prefWidth(sizeX);

For example how I can you get the size of a Left side of a BorderPane and set the size?
Answer: the "Left" of a BorderPane is whatever you set it to and it's size is whatever you set it to.
example:
BorderPane mainpane = new BorderPane();
StackPane left = new StackPane();
left.setPrefWidth(100);
mainPane.setLeft(left);

Set BorderPane components size


Special characters in form element #title

Question: I am trying to write a custom form for my own search facet. In the form, the labels of the elements are dinamically generated based on the indexed values, and they can contain special Hungarian characters, which are not displayed correctly. This is my code:
  $form['facets'][$current_property] = array(
    '#type' => 'select',
    '#title' => $current_property,
    '#multiple' => TRUE,
    '#options' => $myoptions,
    '#default_value' => $widget->buildDefaultValue($element),
    '#attributes' => array('class' => array('facetapi-multiselect', $form_state['facetapi_multiselect']['facet_class'])),
    '#post_render' => array('_facetapi_multiselect_modified_disable_options'),
    );

So, for example, if $current_property is Belső memória/tárhely, then Bels? memória/tárhely is displayed in the search facet.
Can you suggest any ways how to do this correctly?
Thank you very much in advance.
Answer: Based on the version of drupal you are using, you can use one of functions below :
decode_entities($text) for Drupal 7

or
Html::decodeEntities($text) for Drupal 8

so in case of using drupal 7, Your code will looks like this:
$form['facets'][$current_property] = array(
  '#type' => 'select',
  '#title' => decode_entities($current_property),
  '#multiple' => TRUE,
  '#options' => $myoptions,
  '#default_value' => $widget->buildDefaultValue($element),
  '#attributes' => array('class' => array('facetapi-multiselect',
    $form_state['facetapi_multiselect']['facet_class'])),
  '#post_render' => array('_facetapi_multiselect_modified_disable_options'),
);

Comment: Unfortunately, it did not help, I still see question mark (?) instead of ő.
Comment: Maybe you can use  iconv('ISO-8859-1', 'UTF-8', $current_property);
Answer: Maybe there is a problem in collation settings when you want to get data from database

Try to use another collation like utf8mb4_bin or utf8_bin.
Try to debug the value of $current_property and see what you have there.
Maybe your font doesn't support special symbols.

Good luck!


Is the alternating series $\sum_{n=1}^{\infty }(-1)^n \frac {n^2 - 1}{2n^2 + 3}$ divergent?

Question: I tried every test for convergence and really came up with nothing. Without answering the problem directly, is it possible to determine the divergence or convergence for this series?
$$\sum_{n=1}^{\infty }(-1)^n \frac {n^2 - 1}{2n^2 + 3}$$
If it can be determined could someone give a little hint as to what direction to take? Thank you!
Comment: The terms do not approach to $0$.
Comment: ... [and thus it diverges.](https://en.wikipedia.org/wiki/Convergence_tests#Limit_of_the_summand)
Comment: No, it means much more than that. It means divergence. That the sequence of summands converge to zero is a necessary condition (not sufficient) for convergence of the series.
Comment: A place to start for MathJax formatting is [here](http://math.stackexchange.com/help/notation)
Comment: @Crostul I know, but that just means the alternating series test cant show convergence. Is that the only way to determine it?
Comment: @chris360 The point you may be missing here is that in order to find out whether or not a particular series is convergent, you FIRST must find out what the sequence does, more specific, when $n$ goes to infinity, what does the infinite term do? This is always the first and very foremost step, no matter what. The outcome of the limit of the sequence is of very much importance as laid out by DonAntonio. Please read his answer. Good luck!
Comment: @imranfat Okay, it appears I have a misconception, I learned that if the alternating sequence (-1)^n * A, only converges if the limit as n goes to infinity of A approaches zero... That being said in this case it doesn't, it approaches a finite value, all other tests I applied failed, and nowhere does it say that if it approaches a value greater than zero then it is divergent, intuitively that makes sense but analytically I am missing proof. I don't agree with the limit does not exist argument because the same could be said for a similar problem that does converge. So am I correct?
Comment: The alternating series test in this case is conclusive. You're not looking at radii of convergence or whether a ratio is less than or greater than 1, you're looking directly at the terms and seeing that they don't converge.
Answer: A necessary condition for any convergent series is that its terms sequence converges to zero... This must be true for all convergent series : positive, alternating, whatever.
In your case, we have
$$\lim_{n\to\infty}\frac{(-1)^n(n^2-1)}{2n^2+3}=\lim_{n\to\infty}\frac{(-1)^n\left(1-\frac1{n^2}\right)}{2+\frac3{n^2}}\ldots\text{doesn't exist at all}$$
Comment: @chris360 Really? Fiuuu! Was I worried... :)
Comment: +1) Your first sentence should become a bumper sticker on every car :) I couldn't word it with more conviction.
Comment: Okay I have found exactly what you said in a math text! Thank you for your answer!
Answer: Let
$$a_n=(-1)^n\frac{n^2-1}{2n^2+3}$$
we have $$\forall n\in \mathbb N^* \;\;
|a_n|=\frac{1-\frac{1}{n^2}}{2+\frac{3}{n^2}}$$
which yields to
$$\lim_{n\to +\infty}|a_n|=\frac{1}{2}$$
and
$$\lim_{n\to+\infty} a_n \neq 0$$
thus, the series $\sum a_n$ is divergent.


Download de arquivos da WebView em pasta personalizada

Question: Eu quero que os arquivos que são baixados por meu app que usa WebView fiquem em uma pasta personalizada.
Atualmente está indo para a pasta "Downloads" e queria que fosse para uma pasta com o nome do app e que essa pasta seja criada automaticamente.
wb.setDownloadListener(new DownloadListener() {

            @SuppressLint("InlinedApi") public void onDownloadStart(String url, String userAgent,
                                                                    String contentDisposition, String mimetype,
                                                                    long contentLength) {
                DownloadManager.Request request = new DownloadManager.Request(
                        Uri.parse(url));

                request.allowScanningByMediaScanner();
                final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                dm.enqueue(request);
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); //This is important!
                intent.addCategory(Intent.CATEGORY_OPENABLE); //CATEGORY.OPENABLE
                intent.setType("*/*");//any application,any extension
                Toast.makeText(getApplicationContext(), "Baixando!", //To notify the Client that the file is being downloaded
                        Toast.LENGTH_LONG).show();

            }
        });

Como faço isso nesse código ai?
Answer: Acho que é assim:
mude isso:
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);para
request.setDestinationInExternalPublicDir(path,filename);
add:
File path = new File(Environment.getExternalStorageDirectory()+"/NomeDaPasta");
    ou
if(!path.exists()) path.mkdir();
algo assim, procure pela biblioteca io.FIle e sobre os métodosmkdir, exist() e isDirectory().
Comment: deu certo! Obrigado!
Comment: uma boa é dar uma estudada nas bibliotecas de `IO`
Comment: deu certinho, fico muito grato.


$P(S_n) \to 0$ as $n \to \infty$ and $\sum_{i=1}^{\infty} P(S_i \cap (\Omega - S_{i+1}) < \infty$. To prove that $P(\lim \sup S_n) = 0.$

Question: Let $(\Omega, \mathcal A, P)$ be a probability space and let $(S_n) \subset \mathcal A$ be such that $P(S_n) \to 0$ as $n \to \infty$ and $\sum_{i=1}^{\infty} P(S_i \cap (\Omega - S_{i+1}) < \infty$. To prove that $P(\lim \sup S_n) = 0.$
I think we should need Borel Cantelli Lemma to prove this but unable to do the proof. Need Help!
Answer: Notice that
$$P(\limsup S_n) = P\left(\bigcap_{N=1}^\infty \left(\bigcup_{n=N}^\infty S_n\right)\right)\leq P\left(\bigcup_{n=N}^\infty S_n\right) \quad \text{ for all }N.$$
Now write $\bigcup_{n=N}^\infty S_n$ as a countable union (hint: start with $S_N -S_{N+1}$, and go from there).
Finally, the fact that $\sum_{i=1}^\infty P(S_i - S_{i+1})$ converges implies that for any $\epsilon>0$, there exists $N$ such that $\sum_{i=N}^\infty P(S_i-S_{i+1})<\epsilon$. Use that to show $P(\limsup S_n)<\epsilon$ for all $\epsilon>0$.


Is this interpretation of sparsity accurate?

Question: According the documentation of the removeSparseTerms function from the tm package, this is what sparsity entails:
A term-document matrix where those terms from x are removed which have at least a sparse percentage of empty (i.e., terms occurring 0 times in a document) elements. I.e., the resulting matrix contains only terms with a sparse factor of less than sparse.
So, is a correct interpretation of this to say if sparse is equal to .99, then we are removing terms that only appear in at most 1% of the data?
Comment: This question is more appropriate for Stackoverflow, where there are tags for tm and text-mining.
Answer: Yes, although your confusion here is understandable, since the term "sparsity" is hard to define clearly in this context.
In the sense of the sparse argument to removeSparseTerms(), sparsity refers to the threshold of relative document frequency for a term, above which the term will be removed.  Relative document frequency here means a proportion.  As the help page for the command states (although not very clearly), sparsity is smaller as it approaches 1.0.  (Note that sparsity cannot take values of 0 or 1.0, only values in between.)
So your interpretation is correct in that sparse = 0.99 will remove only terms that are more sparse than 0.99.
The exact interpretation for sparse = 0.99 is that for term $j$, you will retain all terms for which
$df_j > N * (1 - 0.99)$, where $N$ is the number of documents -- in this case probably all terms will be retained (see example below).
Near the other extreme, if sparse = .01, then only terms that appear in (nearly) every document will be retained.  (Of course this depends on the number of terms and the number of documents, and in natural language, common words like "the" are likely to occur in every document and hence never be "sparse".)
An example of the sparsity threshold of 0.99, where a term that occurs at most in (first example) less than 0.01 documents, and (second example) just over 0.01 documents:
> # second term occurs in just 1 of 101 documents
> myTdm1 <- as.DocumentTermMatrix(slam::as.simple_triplet_matrix(matrix(c(rep(1, 101), rep(1,1), rep(0, 100)), ncol=2)),
+                                weighting = weightTf)
> removeSparseTerms(myTdm1, .99)
<<DocumentTermMatrix (documents: 101, terms: 1)>>
Non-/sparse entries: 101/0
Sparsity           : 0%
Maximal term length: 2
Weighting          : term frequency (tf)
>
> # second term occurs in 2 of 101 documents
> myTdm2 <- as.DocumentTermMatrix(slam::as.simple_triplet_matrix(matrix(c(rep(1, 101), rep(1,2), rep(0, 99)), ncol=2)),
+                                weighting = weightTf)
> removeSparseTerms(myTdm2, .99)
<<DocumentTermMatrix (documents: 101, terms: 2)>>
Non-/sparse entries: 103/99
Sparsity           : 49%
Maximal term length: 2
Weighting          : term frequency (tf)

Here are a few additional examples with actual text and terms:
> myText <- c("the quick brown furry fox jumped over a second furry brown fox",
              "the sparse brown furry matrix",
              "the quick matrix")

> require(tm)
> myVCorpus <- VCorpus(VectorSource(myText))
> myTdm <- DocumentTermMatrix(myVCorpus)
> as.matrix(myTdm)
    Terms
Docs brown fox furry jumped matrix over quick second sparse the
   1     2   2     2      1      0    1     1      1      0   1
   2     1   0     1      0      1    0     0      0      1   1
   3     0   0     0      0      1    0     1      0      0   1
> as.matrix(removeSparseTerms(myTdm, .01))
    Terms
Docs the
   1   1
   2   1
   3   1
> as.matrix(removeSparseTerms(myTdm, .99))
    Terms
Docs brown fox furry jumped matrix over quick second sparse the
   1     2   2     2      1      0    1     1      1      0   1
   2     1   0     1      0      1    0     0      0      1   1
   3     0   0     0      0      1    0     1      0      0   1
> as.matrix(removeSparseTerms(myTdm, .5))
    Terms
Docs brown furry matrix quick the
   1     2     2      0     1   1
   2     1     1      1     0   1
   3     0     0      1     1   1

In the last example with sparse = 0.34, only terms occurring in two-thirds of the documents were retained.
An alternative approach for trimming terms from document-term matrixes based on a document frequency is the text analysis package quanteda.  The same functionality here refers not to sparsity but rather directly to the document frequency of terms (as in tf-idf).
> require(quanteda)
> myDfm <- dfm(myText, verbose = FALSE)
> docfreq(myDfm)
     a  brown    fox  furry jumped matrix   over  quick second sparse    the
     1      2      1      2      1      2      1      2      1      1      3
> trim(myDfm, minDoc = 2)
Features occurring in fewer than 2 documents: 6
Document-feature matrix of: 3 documents, 5 features.
3 x 5 sparse Matrix of class "dfmSparse"
       features
docs    brown furry the matrix quick
  text1     2     2   1      0     1
  text2     1     1   1      1     0
  text3     0     0   1      1     1

This usage seems much more straightforward to me.
Comment: Welcome to the site Ken. Thanks for your excellent answer. I hope we see more of you.


Rails article voting restriction in model

Question: I'm building a test application in rails, it's a news story voting system to teach myself rails and ruby.
I'm trying to restrict the voting so the user can 'vote up' an article only once on each article. After some research the best way I've found of getting this to work is adding a validation on a vote model which I've create that checks for a duplicate vote entry by that user.
I'm not really after a code example just some advice that this is the best way of breaking this problem down? The active record validates work perfectly but it doesn't feel like a good practice to put so much strain at the database level, but maybe this is completely fine?
Hope this makes sense, thanks for reading.
Answer: This is in fact the right design. In a relational setup, you'll have Stories, Users, and Votes, where Votes have both a user_id and story_id. Enforcing data integrity is ultimately a database constraint, and you can't really know if a user has voted on a story not without going to the database to check. You could keep some kind of higher-level cache to prevent quite as much database access if needed, but doing so now would be a premature optimization. Cross that bridge when you need to.
One thing to consider would be to create a compound unique index of (user_id, story_id) on your votes table. This would have the benefits of backstopping your validation and improving vote lookup speed to an O(log n) operation, which should eliminate much of the time burden. Something else you can do is disallow votes on old stories, and purge any votes records older than a certain age (corresponding to the time at which you disallow voting), which would keep your votes table at a relatively constant size over time, rather than just permitting it to grow forever.


KnockoutJS foreach binding add outline around selected items

Question: I have a knockout observable array of items displayed as buttons:

     <button data-bind="css: Sel == false ? 'btn btn-white' : 'btn btn-dark', click:$root.makeChange, text:$data.Id, attr:{'id':'h_'+$data.Id}"></button>

for which I need to add a outline as
for items that have Sel set to true.
I've tried using outline: 2px solid black; outline-offset: 1px; but it adds outline around each button, not for the group and the right line of the outline is drawn behind the next button.
I've also tried using borders, and adding them with JS, but I don't have the space between the button and border.
Comment: I've rolled back your question to the original. Sorry for the unnecessary confusion.
Answer: The outline property feels like the right approach to this issue, but it only allows outlining a single element, and it only allows complete outlines.
That means the active elements must be wrapped in a container, and that container must receive the outline.
This can be done with a computed observable that turns a flat list:
[
    {text: 'Mon', active: true},
    {text: 'Tue', active: true},
    {text: 'Wed', active: true},
    {text: 'Tue', active: false},
    {text: 'Fri', active: false},
    {text: 'Sat', active: true},
    {text: 'Sun', active: true}
]

into a nested one:
[
  [
    {text: 'Mon', active: true},
    {text: 'Tue', active: true},
    {text: 'Wed', active: true}
  ],
  [
    {text: 'Tue', active: false},
    {text: 'Fri', active: false},
  ],
  [
    {text: 'Sat', active: true},
    {text: 'Sun', active: true}
  ]
]

depending on which item is active.
Here is how I would implement that in knockout.

A Button viewmodel that tracks its own active state and allows to toggle it
A ButtonList viewmodel that contains the buttons and the dynamically calculated buttonGroups.
A view that creates .btn-group and .btn-group.active divs based on that.

Interactive sample below:

function Button(params) {
  this.text = params.text;
  this.active = ko.observable(params.active);
  this.toggle = () => this.active(!this.active());
}

function ButtonList(params) {
  this.buttons = ko.observableArray(params.buttons.map(b => new Button(b)));
  this.buttonGroups = ko.pureComputed(() => {
    const groups = [];
    let prev = null, group = null;
    this.buttons().forEach(b => {
      if (b.active() !== prev) {
        group = [];
        groups.push(group);
        prev = b.active();
      }
      group.push(b);
    });
    return groups;
  });
}

const vm = new ButtonList({
  buttons: [
    {text: 'Mon', active: true},
    {text: 'Tue', active: true},
    {text: 'Wed', active: true},
    {text: 'Tue', active: false},
    {text: 'Fri', active: false},
    {text: 'Sat', active: true},
    {text: 'Sun', active: true}
  ]
});
ko.applyBindings(vm);
.btns {
  display: flex;
}
.btn-group {
  display: flex;
  outline-offset: 2px;
}
.btn-group.active {
  outline: 2px solid black;
}
.btn-group > * {
  width: 50px;
  padding: 5px;
  margin: 0;
  text-align: center;
}
.btn-group > .active {
  background-color: black;
  color: white;
}


Combinations from two groups

Question: I am stumped on a problem with two parts. First part I think I might have done correctly, Second part im lost

From a group of 4 women and 6 men, In how many ways a committee consisting of 2 women and 3 men can be formed.
a) without any restrictions
b) if a one particular woman is not eligible to be on the committee

a) This one I think I understood. I had to find the possible combinations of the men and women and multiply them right? So $^4C_2.^6C_3$

b) I'm totally stuck on this one...
Comment: (a) is fine.  For (b), if one particular woman is not to be on the committee, how many women and how many men can you choose from?
Comment: @David well, 3 women and 6 men? so is it similar to part "A" but instead with one less woman?
Comment: That's how I see it.  Just had a thought though: what is meant by a committee?  Do the positions matter, e.g. is "Ann as president, Betty as secretary" counted the same as "Ann as secretary, Betty as president"?  If it's only the people that count and not the positions, then your answer is correct.  And what you just said for (b) is correct too.
Comment: @David You are thinking way out of the box !
Comment: Well, it is an important point.  But I should think that the simpler interpretation is what was intended.
Comment: @David thanks for the clarification! I just realized that its only the people who matter, not the positions. iv just been over complicating it...
Answer: For part $b$, if one particular woman is restricted or not eligible, then you have only $(4-1)=3$ women to choose from !
Now you have reduced the problem similar to that as part $a$, but with $3$ women and $6$ men.So isn't the answer just: $^3C_2.^6C_3$
Comment: @Krimson Never search for something that is not mentioned in the question. It will only complicate things.
Comment: thanks! its amazing how I over complicate even the most simplest thing...

Combinations from two groups


How to palm-mute bass notes only?

Question: I heard about a fingerstyle technique where you palm mute the bass line but not the melody line.
I've been trying to figure it out but have a couple of issues. I try to lay my palm so that it touches only the E A D strings, but this hand position makes it very difficult to play all the strings. Also, I'm having trouble muting all three strings equally, with E being more muted than D.
How does this technique work? I didn't manage to find anything with Google.
Comment: Not an answer, but a simple solution. Cut a piece of sponge, to go under the bottom three strings, close to the bridge. You'll have to experiment a bit, to find how much muting *you* need.
Comment: Wow, never even considered changing the instrument. Thank you for the suggestion!
Answer: The obvious answer is practice (as it usually is) but you can use various techniques to make things easier.
One useful trick to limiting muting to just the bass strings is to mute right at the bridge, and rest the side of your palm on the bridge itself. You can then place your hand in a way that moves the contact position on the top three strings behind the bridge while keeping the contact position for the bass strings in front of the bridge.
What this gives you is a relatively fixed position so you don't accidentally start to mute higher strings or release the damping on lower strings.

How to palm-mute bass notes only?


Context on simple query

Question: I'm making a simple database query on MongoDB, and I see 2 different ways to call Context.
First way with timeout:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
result := collection.FindOne(ctx, bson.M{"_id": userID})

Second way, calling directly with context.Background()
result := collection.FindOne(context.Background(), bson.M{"_id": userID})

If I use the second way and there is a long delay, would it wait forever or timeout at one point?
I find the second solution more elegant with less lines of code, but as I'm new in Go I may misunderstand the risks.
Answer: If you set socket timeout & connect timeout via URI options, the second option should time out when these timeouts are exceeded.
Comment: No, your server's timeout has no relation to the timeout used by MongoDB client.
Comment: So on my rest API I set a `&http.Server{WriteTimeout: 10 * time.Second}` so that means after 10 seconds it will timeout?
Comment: OK, so in my case the MongoDB never times out, so I better always use context with timeout. Thanks

Context on simple query


Moving from Ubuntu to CentOS

Question: Right now I have my own server (in my house actually) that hosts my website using Ubuntu. For obvious reasons I'm planning on switching to a VPS soon. I've read that CentOS is a better choice over Ubuntu for the VPS OS. So my question is, how difficult will it be to migrate over from one OS to the other? Here's a list of some of the packages I depend on:

Webmin
Gitolite
ZNC
ircd-hybrid and hybserv
awstats

Will all of these packages be compatible with CentOS? What about all my config files? Will I have to edit them from scratch, or can I simply transfer them from one server to another?
Thanks in advance for any help!
Answer: If you have installed them with apt/aptitude on Ubuntu you should check the config files in CentOS. everything else should work fine.
And if you have installed everything from source—there shouldn't be any problem at all.
Answer: Download the following two rpms into your CentOS, install it and then do a
<code>yum search package_name
</code>
http://download.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm
http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.i386.rpm

Moving from Ubuntu to CentOS


Make user logged in after created by rule

Question: I have an entityform on my Drupal website, which helps me to generate leads. I've configured a rule, creates a new user by that entityform's e-mail and name fields. (Similar scenario is told here.)
I need that user (created by rule) to be logged in, after creation. What should I do?
Answer: Have a look at the Logintoboggan module. This offers you to login new users immediately.
The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:
1.Allow users to login using either their username OR their e-mail address.
2.Allow users to login immediately.
3.Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
4.The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a
separate page, but returns the user to their original page upon login.
5.Customize the registration form with two e-mail fields to ensure accuracy.
6.Optionally redirect the user to a specific page when using the 'immediate login' feature.
7.Optionally redirect the user to a specific page upon validation of their e-mail address.
8.Optionally display a user message indicating a successful login.
9.Optionally combine both the login and registration form on one page.
10.Optionally have unvalidated users purged from the system at a pre-defined interval
(please read the CAVEATS section of INSTALL.txt for important information on 12.configuring this feature!).
11.Integrates with Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)
Comment: will this work with rules module ?
Comment: this is not an answer for what I asked.


What am I missing to setup sudo access with openldap?

Question: I'm using lxd/lxc containers (Oracle Linux 8) to rapidly deploy the environment (so if you have lxd setup, you can modify the ip scheme to match lxd's bridge subnet / DNS and then paste the code into separate lxc containers).
I can authenticate as my test user "adam", but when I attempt to setup sudo for adam it tells me
adam may not run sudo on <hostname>

As far as I can tell, I have everything configured correctly [for sudo].
LDAP: https://www.server-world.info/en/note?os=CentOS_7&p=openldap / https://kifarunix.com/install-and-setup-openldap-on-rocky-linux-8/
SSSD: https://kifarunix.com/configure-sssd-for-openldap-authentication-on-centos-8/
SUDO: https://kifarunix.com/how-to-configure-sudo-via-openldap-server/
LDAP Container
lxc stop ldapmaster --force; lxc delete ldapmaster; lxc launch images:oracle/8/amd64 ldapmaster; lxc exec ldapmaster passwd; lxc console ldapmaster

paste into LDAP container
ldaphostname="ldapmaster"
domain="example"
suffix="com"
olcRootPW=1234
userpw=1234
binddnpw=1234
mgrpw=1234
DNS1=192.168.3.1
DNS2=192.168.3.2
LDAPMASTERIP=10.175.235.220
SSSDIP=10.175.235.210
NETMASKIP=255.255.255.0
GATEWAYIP=10.175.235.1

cat  <<EOF > /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
BOOTPROTO=static
IPADDR=$LDAPMASTERIP
NETMASKIP=$NETMASKIP
GATEWAY=$GATEWAYIP
DNS1=$DNS1
DNS2=$DNS2
ONBOOT=yes
HOSTNAME=`cat /proc/sys/kernel/hostname`
TYPE=Ethernet
MTU=
DHCP_HOSTNAME=`cat /proc/sys/kernel/hostname`
IPV6INIT=yes
EOF

ifdown eth0

ifup eth0

cat  <<EOF > /etc/yum.repos.d/appstream.repo
[appstream]
name=Oracle Linux
baseurl=http://yum.oracle.com/repo/OracleLinux/OL8/appstream/x86_64/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle

EOF

cat  <<EOF > /etc/yum.repos.d/base.repo
[base]
name=Oracle Linux
baseurl=https://yum.oracle.com/repo/OracleLinux/OL8/3/baseos/base/x86_64/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle
proxy=http://www-proxy.web.boeing.com:31060
EOF

cat  <<EOF > /etc/yum.repos.d/powertools.repo
[powertools]
name=Oracle Linux
baseurl=http://public-yum.oracle.com/repo/OracleLinux/OL8/codeready/builder/x86_64/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle

EOF

echo "10.175.235.220 $ldaphostname $ldaphostname.$domain.$suffix" >> /etc/hosts

#https://www.server-world.info/en/note?os=CentOS_7&p=openldap
yum -y install openldap-servers openldap-clients firewalld mlocate man openssl hostname sssd-tools openssh-server nss-pam-ldapd nano --nobest

cat <<EOF > /etc/sudo-ldap.conf
binddn cn=Manager,dc=$domain,dc=$suffix
bindpw 1234
ssl start_tls
tls_cacertfile = /etc/pki/tls/cacert.crt
sudoers_base = ou=SUDOers,DC=$domain,DC=$suffix
tls_checkpeer yesuri ldaps://$ldaphostname:636
bind_timelimit 5
timelimit 15
EOF

updatedb
cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/DB_CONFIG
chown ldap. /var/lib/ldap/DB_CONFIG
systemctl enable --now sshd
systemctl enable --now slapd

cat <<EOF > chrootpw.ldif
# specify the password generated above for "olcRootPW" section
dn: olcDatabase={0}config,cn=config
changetype: modify
add: olcRootPW
olcRootPW: $(slappasswd -s $olcRootPW)
EOF

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/pki/tls/ldapserver.key -out /etc/pki/tls/ldapserver.crt -subj "/C=XX/L=Default City/O=Default Company Ltd/CN=$ldaphostname"

chown ldap:ldap /etc/pki/tls/{ldapserver.crt,ldapserver.key}

cat > add-tls.ldif << 'EOL'
dn: cn=config
changetype: modify
add: olcTLSCACertificateFile
olcTLSCACertificateFile: /etc/pki/tls/ldapserver.crt
-
add: olcTLSCertificateKeyFile
olcTLSCertificateKeyFile: /etc/pki/tls/ldapserver.key
-
add: olcTLSCertificateFile
olcTLSCertificateFile: /etc/pki/tls/ldapserver.crt
EOL

cat <<EOF > /etc/openldap/ldap.conf
#
# LDAP Defaults
#

# See ldap.conf(5) for details
# This file should be world readable but not world writable.

BASE    dc=$domain,dc=$suffix
URI     ldaps://$ldaphostname:636
#ldap.example.com ldap://ldap-master.example.com:666

#SIZELIMIT      12
#TIMELIMIT      15
#DEREF          never

# When no CA certificates are specified the Shared System Certificates
# are in use. In order to have these available along with the ones specified
# by TLS_CACERTDIR one has to include them explicitly:
#TLS_CACERT     /etc/pki/tls/cert.pem
TLS_CACERT     /etc/pki/tls/ldapserver.crt

# System-wide Crypto Policies provide up to date cipher suite which should
# be used unless one needs a finer grinded selection of ciphers. Hence, the
# PROFILE=SYSTEM value represents the default behavior which is in place
# when no explicit setting is used. (see openssl-ciphers(1) for more info)
#TLS_CIPHER_SUITE PROFILE=SYSTEM

# Turning this off breaks GSSAPI used with krb5 when rdns = false
SASL_NOCANON    on
sudoers_base ou=SUDOers,dc=$domain,dc=$suffix
SUDOERS_DEBUG 1
EOF

cat << 'EOF' > /etc/openldap/schema/sudo.ldif
dn: cn=sudo,cn=schema,cn=config
objectClass: olcSchemaConfig
cn: sudo
olcAttributeTypes: ( 220.127.116.11.4.1.15918.104.22.168 NAME 'sudoUser' DESC 'User(s) who may  run sudo' EQUALITY caseExactIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 22.214.171.124.4.1.1418.104.22.168.26 )
olcAttributeTypes: ( 22.214.171.124.4.1.159126.96.36.199 NAME 'sudoHost' DESC 'Host(s) who may run sudo' EQUALITY caseExactIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 126.96.36.199.4.1.14126.96.36.199.26 )
olcAttributeTypes: ( 220.127.116.11.4.1.15918.104.22.168 NAME 'sudoCommand' DESC 'Command(s) to be executed by sudo' EQUALITY caseExactIA5Match SYNTAX 184.108.40.206.4.1.1422.214.171.124.26 )
olcAttributeTypes: ( 188.8.131.52.4.1.159188.8.131.52 NAME 'sudoRunAs' DESC 'User(s) impersonated by sudo (deprecated)' EQUALITY caseExactIA5Match SYNTAX 18.104.22.168.4.1.1422.214.171.124.26 )
olcAttributeTypes: ( 188.8.131.52.4.1.159188.8.131.52 NAME 'sudoOption' DESC 'Options(s) followed by sudo' EQUALITY caseExactIA5Match SYNTAX 18.104.22.168.4.1.1418.104.22.168.26 )
olcAttributeTypes: ( 126.96.36.199.4.1.159188.8.131.52 NAME 'sudoRunAsUser' DESC 'User(s) impersonated by sudo' EQUALITY caseExactIA5Match SYNTAX 188.8.131.52.4.1.14184.108.40.206.26 )
olcAttributeTypes: ( 184.108.40.206.4.1.159184.108.40.206 NAME 'sudoRunAsGroup' DESC 'Group(s) impersonated by sudo' EQUALITY caseExactIA5Match SYNTAX 126.96.36.199.4.1.1422.214.171.124.26 )
olcObjectClasses: ( 126.96.36.199.4.1.159126.96.36.199 NAME 'sudoRole' SUP top STRUCTURAL DESC 'Sudoer Entries' MUST ( cn ) MAY ( sudoUser $ sudoHost $ sudoCommand $ sudoRunAs $ sudoRunAsUser $ sudoRunAsGroup $ sudoOption $ description ) )
EOF

cp /usr/share/doc/sudo/schema.OpenLDAP  /etc/openldap/schema/sudo.schema

ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/sudo.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f add-tls.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f chrootpw.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/cosine.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/nis.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/inetorgperson.ldif

mkdir /var/lib/openldap
chown ldap. /var/lib/openldap

cat > rootdn.ldif << 'EOL'
dn: olcDatabase=mdb,cn=config
objectClass: olcDatabaseConfig
objectClass: olcMdbConfig
olcDatabase: mdb
OlcDbMaxSize: 42949672960
olcSuffix: dc=$domain,dc=$suffix
olcRootDN: cn=Manager,dc=$domain,dc=$suffix
olcRootPW: secret
olcDbDirectory: /var/lib/openldap
olcDbIndex: uid pres,eq
olcDbIndex: cn,sn pres,eq,approx,sub
olcDbIndex: mail pres,eq,sub
olcDbIndex: objectClass pres,eq
olcDbIndex: loginShell pres,eq
olcDbIndex: sudoUser,sudoHost pres,eq
EOL

ldapadd -Y EXTERNAL -H ldapi:/// -f rootdn.ldif

cat <<EOF > chdomain.ldif

dn: olcDatabase={1}monitor,cn=config
changetype: modify
replace: olcAccess
olcAccess: {0}to * by dn.base="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth"
  read by dn.base="cn=Manager,dc=$domain,dc=$suffix" read by * none

dn: olcDatabase={2}mdb,cn=config
changetype: modify
replace: olcSuffix
olcSuffix: dc=$domain,dc=$suffix

dn: olcDatabase={2}mdb,cn=config
changetype: modify
replace: olcRootDN
olcRootDN: cn=Manager,dc=$domain,dc=$suffix

dn: olcDatabase={2}mdb,cn=config
changetype: modify
add: olcRootPW
olcRootPW: $(slappasswd -s $olcRootPW)

dn: olcDatabase={2}mdb,cn=config
changetype: modify
add: olcAccess
olcAccess: {0}to attrs=userPassword,shadowLastChange by
  dn="cn=Manager,dc=$domain,dc=$suffix" write by anonymous auth by self write by * none
olcAccess: {1}to dn.base="" by * read
olcAccess: {2}to * by dn="cn=Manager,dc=$domain,dc=$suffix" write by * read
olcAccess: to attrs=userPassword,shadowLastChange,shadowExpire
  by self write
  by anonymous auth
  by dn.subtree="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
  by dn.subtree="ou=System,dc=$domain,dc=$suffix" read
  by * none
olcAccess: to dn.subtree="ou=System,dc=$domain,dc=$suffix" by dn.subtree="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
  by * none
olcAccess: to dn.subtree="dc=$domain,dc=$suffix" by dn.subtree="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
  by users read
  by * none
EOF

ldapmodify -Y EXTERNAL -H ldapi:/// -f chdomain.ldif

cat <<EOF > basedomain.ldif
# replace to your own domain name for "dc=***,dc=***" section

dn: dc=$domain,dc=$suffix
objectClass: top
objectClass: dcObject
objectclass: organization
o: $domain $suffix
dc: $domain

dn: cn=Manager,dc=$domain,dc=$suffix
objectClass: organizationalRole
cn: Manager
description: Directory Manager

dn: ou=System,dc=$domain,dc=$suffix
objectClass: organizationalUnit
objectClass: top
ou: System

dn: ou=Users,dc=$domain,dc=$suffix
objectClass: organizationalUnit
objectClass: top
ou: Users

dn: ou=Groups,dc=$domain,dc=$suffix
objectClass: organizationalUnit
objectClass: top
ou: Groups

EOF

ldapadd -x -w $olcRootPW -D cn=Manager,dc=$domain,dc=$suffix -f basedomain.ldif

systemctl start firewalld
systemctl enable firewalld
firewall-cmd --add-service={ldap,ldaps} --permanent
firewall-cmd --reload

cat <<EOF > sudoersou.ldif
dn: ou=SUDOers,dc=$domain,dc=$suffix
objectClass: organizationalUnit
ou: SUDOers
description: $domain-$suffix LDAP SUDO Entry
EOF

ldapadd -x -w $olcRootPW -D cn=Manager,dc=$domain,dc=$suffix -f sudoersou.ldif

cat <<EOF > users_n_groups.ldif

dn: cn=readonly,ou=System,dc=$domain,dc=$suffix
objectClass: organizationalRole
objectClass: simpleSecurityObject
cn: readonly
userPassword: $(slappasswd -s $binddnpw)
description: Bind DN user for LDAP Operations

dn: uid=adam,ou=Users,dc=$domain,dc=$suffix
objectClass: top
objectClass: account
objectClass: posixAccount
objectClass: shadowAccount
cn: adam
uid: adam
uidNumber: 16859
gidNumber: 100
homeDirectory: /home/adam
loginShell: /bin/bash
gecos: adam
userPassword: $(slappasswd -s $userpw)
shadowLastChange: 0
shadowMax: 0
shadowWarning: 0
EOF
ldapadd -x -w $olcRootPW -D "cn=Manager,dc=$domain,dc=$suffix" -f users_n_groups.ldif

#cvtsudoers -b ou=SUDOers,dc=$domain,dc=$suffix -o sudoers.ldif /etc/sudoers

cat <<EOF > sudoers.ldif
dn: cn=defaults,ou=SUDOers,dc=$domain,dc=$suffix
objectClass: top
objectClass: sudoRole
cn: defaults
description: Default sudoOption's go here
sudoOption: !visiblepw
sudoOption: always_set_home
sudoOption: match_group_by_gid
sudoOption: always_query_group_plugin
sudoOption: env_reset
sudoOption: env_keep=COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS
sudoOption: env_keep+=MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE
sudoOption: env_keep+=LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES
sudoOption: env_keep+=LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE
sudoOption: env_keep+=LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY
sudoOption: secure_path=/sbin:/bin:/usr/sbin:/usr/bin
EOF

ldapadd -x -w $olcRootPW -D cn=Manager,dc=$domain,dc=$suffix -f sudoers.ldif

cat <<EOF > indsudoers.ldif
dn: cn=sudo,ou=SUDOers,dc=$domain,dc=$suffix
objectClass: top
objectClass: sudoRole
cn: sudo
sudoUser: adam
sudoHost: ALL
sudoRunAsUser: ALL
sudoCommand: ALL
EOF

ldapadd -x -w $olcRootPW -D cn=Manager,dc=$domain,dc=$suffix -f indsudoers.ldif

#ldappasswd -s $olcRootPW -w $userpw -D "cn=Manager,dc=$domain,dc=$suffix" -x "uid=adam,ou=Users,dc=$domain,dc=$suffix"

#ldappasswd -s $olcRootPW -w $binddnpw -D "cn=Manager,dc=$domain,dc=$suffix" -x "cn=readonly,ou=System,dc=$domain,dc=$suffix"

SSSD Container
lxc stop ldap-sssd-try2 --force; lxc delete ldap-sssd-try2; lxc launch images:oracle/8/amd64 ldap-sssd-try2; lxc exec ldap-sssd-try2 passwd; lxc console ldap-sssd-try2;

paste into SSSD container
ldaphostname="ldapmaster"
domain="example"
suffix="com"
olcRootPW=1234
userpw=1234
binddnpw=1234
mgrpw=1234
DNS1=192.168.3.1
DNS2=192.168.3.2
LDAPMASTERIP=10.175.235.220
SSSDIP=10.175.235.210
NETMASKIP=255.255.255.0
GATEWAYIP=10.175.235.1

cat  <<EOF > /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
BOOTPROTO=static
IPADDR=$SSSDIP
NETMASKIP=$NETMASKIP
GATEWAY=$GATEWAYIP
DNS1=$DNS1
DNS2=$DNS2
ONBOOT=yes
HOSTNAME=`cat /proc/sys/kernel/hostname`
TYPE=Ethernet
MTU=
DHCP_HOSTNAME=`cat /proc/sys/kernel/hostname`
IPV6INIT=yes
EOF

ifdown eth0

ifup eth0

cat  <<EOF > /etc/yum.repos.d/appstream.repo
[appstream]
name=Oracle Linux
baseurl=http://yum.oracle.com/repo/OracleLinux/OL8/appstream/x86_64/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle
EOF

cat  <<EOF > /etc/yum.repos.d/base.repo
[base]
name=Oracle Linux
baseurl=https://yum.oracle.com/repo/OracleLinux/OL8/3/baseos/base/x86_64/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle
proxy=http://www-proxy.web.boeing.com:31060
EOF

cat  <<EOF > /etc/yum.repos.d/powertools.repo
[powertools]
name=Oracle Linux
baseurl=http://public-yum.oracle.com/repo/OracleLinux/OL8/codeready/builder/x86_64/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle
EOF

echo "10.175.235.220  $ldaphostname $ldaphostname.$domain.$suffix" >> /etc/hosts

yum install -y hostname openssh-server nmap openssl sssd sssd-tools oddjob-mkhomedir authselect openldap-clients openldap-servers sssd-tools nss-pam-ldapd bind-utils nano mlocate --nobest

systemctl enable --now sshd

cat <<EOF > /etc/sudo-ldap.conf
binddn cn=Manager,dc=$domain,dc=$suffix
bindpw 1234
ssl start_tls
tls_cacertfile = /etc/pki/tls/cacert.crt
sudoers_base = ou=SUDOers,DC=$domain,DC=$suffix
tls_checkpeer yesuri ldaps://$ldaphostname:636
bind_timelimit 5
timelimit 15
EOF

cat <<EOF > /etc/sssd/sssd.conf
[sssd]
services = nss, pam, sudo
config_file_version = 2
domains = LDAP

[sudo]

[nss]

[pam]
offline_credentials_expiration = 60

[domain/LDAP]
ldap_id_use_start_tls = True
cache_credentials = False
ldap_search_base = dc=$domain,dc=$suffix
id_provider = ldap
auth_provider = ldap
chpass_provider = ldap
access_provider = ldap
sudo_provider = ldap
ldap_uri = ldaps://$ldaphostname:636
ldap_chpass_uri = ldaps://$ldaphostname:636
#ldap_default_bind_dn = cn=Manager,dc=$domain,dc=$suffix
#ldap_default_authtok = $olcRootPW
ldap_default_bind_dn = cn=readonly,ou=System,dc=$domain,dc=$suffix
#doesn't seem to matter if I use mapldap_default_authtok_type
#mapldap_default_authtok_type = password
ldap_default_authtok = $binddnpw
ldap_user_search_base = ou=Users,DC=$domain,DC=$suffix
ldap_tls_reqcert = demand
ldap_tls_cacert = /etc/pki/tls/cacert.crt
ldap_tls_cacertdir = /etc/pki/tls
ldap_search_timeout = 50
ldap_network_timeout = 60
ldap_sudo_search_base = ou=SUDOers,DC=$domain,DC=$suffix
ldap_access_order = filter
ldap_access_filter = (objectClass=posixAccount)
EOF

authselect select sssd --force

chown -R root: /etc/sssd

chmod 600 -R /etc/sssd

systemctl enable --now sssd

cat  <<EOF > /etc/openldap/ldap.conf
#
# LDAP Defaults
#

# See ldap.conf(5) for details
# This file should be $suffix readable but not $suffix writable.

BASE    dc=$domain,dc=$suffix
URI     ldaps://$ldaphostname:636
#SUDOers_BASE    ou=SUDOers,dc=ldapmaster,dc=ldapmaster,dc=com

#SIZELIMIT      12
#TIMELIMIT      15
#DEREF          never

# When no CA certificates are specified the Shared System Certificates
# are in use. In order to have these available along with the ones specified
# by TLS_CACERTDIR one has to include them explicitly:
#TLS_CACERT     /etc/pki/tls/cert.pem
TLS_CACERT      /etc/pki/tls/cacert.crt

# System-wide Crypto Policies provide up to date cipher suite which should
# be used unless one needs a finer grinded selection of ciphers. Hence, the
# PROFILE=SYSTEM value represents the default behavior which is in place
# when no explicit setting is used. (see openssl-ciphers(1) for more info)
#TLS_CIPHER_SUITE PROFILE=SYSTEM

# Turning this off breaks GSSAPI used with krb5 when rdns = false
SASL_NOCANON    on
sudoers_base ou=SUDOers,dc=$domain,dc=$suffix
SUDOERS_DEBUG 1
EOF

openssl s_client -connect $ldaphostname:636 < /dev/null -showcerts | openssl x509 -text | sed -ne '
   /-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p      # got the range, ok
   /-END CERTIFICATE-/q                            # bailing out soon as the cert end seen
' > /etc/pki/tls/cacert.crt

echo "sudoers : ldap files" >> /etc/nsswitch.conf

systemctl restart sssd

systemctl enable --now oddjobd

echo "session optional pam_oddjob_mkhomedir.so skel=/etc/skel/ umask=0022" >> /etc/pam.d/system-auth

systemctl restart oddjobd

If I query using ldapsearch
domain="example"
suffix="com"
export SUDOERS_BASE=ou=SUDOers,DC=$domain,DC=$suffix

ldapsearch -b "$SUDOERS_BASE" -D cn=Manager,DC=$domain,DC=$suffix -W -x adam

I get
Enter LDAP Password:
# extended LDIF
#
# LDAPv3
# base <ou=SUDOers,DC=example,DC=com> with scope subtree
# filter: (objectclass=*)
# requesting: adam
#

# SUDOers, example.com
dn: ou=SUDOers,dc=example,dc=com

# adam, SUDOers, example.com
dn: cn=adam,ou=SUDOers,dc=example,dc=com

# defaults, SUDOers, example.com
dn: cn=defaults,ou=SUDOers,dc=example,dc=com

# search result
search: 2
result: 0 Success

# numResponses: 4
# numEntries: 3

If I run
domain="example"
suffix="com"
export SUDOERS_BASE=ou=SUDOers,DC=$domain,DC=$suffix

ldapsearch -b "$SUDOERS_BASE" -D cn=Manager,DC=$domain,DC=$suffix -w 1234 -x

I get
# extended LDIF
#
# LDAPv3
# base <ou=SUDOers,DC=example,DC=com> with scope subtree
# filter: (objectclass=*)
# requesting: ALL
#

# SUDOers, example.com
dn: ou=SUDOers,dc=example,dc=com
objectClass: organizationalUnit
ou: SUDOers
description: example-com LDAP SUDO Entry

# sudo, SUDOers, example.com
dn: cn=sudo,ou=SUDOers,dc=example,dc=com
objectClass: top
objectClass: sudoRole
cn: sudo
sudoUser: adam
sudoHost: ALL
sudoRunAsUser: ALL
sudoCommand: ALL

# defaults, SUDOers, example.com
dn: cn=defaults,ou=SUDOers,dc=example,dc=com
objectClass: top
objectClass: sudoRole
cn: defaults
description: Default sudoOption's go here
sudoOption: !visiblepw
sudoOption: always_set_home
sudoOption: match_group_by_gid
sudoOption: always_query_group_plugin
sudoOption: env_reset
sudoOption: env_keep=COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS
sudoOption: env_keep+=MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE
sudoOption: env_keep+=LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES
sudoOption: env_keep+=LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE
sudoOption: env_keep+=LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY
sudoOption: secure_path=/sbin:/bin:/usr/sbin:/usr/bin

# search result
search: 2
result: 0 Success

# numResponses: 4
# numEntries: 3

Answer: problem was an extra space after /etc/nsswitch.conf
echo "sudoers: ldap files sss" >> /etc/nsswitch.conf

once that was corrected, had to install
libsss_sudo


How do I handle click events on multiple similar buttons in WPF?

Question: I'm a C# beginner and am trying to implement a numeric pad in WPF. It consists of 10 similar buttons:
<Button Content="0" Name="button0" Click="anyButtonClicked" />
<Button Content="1" Name="button1" Click="anyButtonClicked" />
<Button Content="2" Name="button2" Click="anyButtonClicked" />
...
<Button Content="9" Name="button9" Click="anyButtonClicked" />

What is the best practise to handle all those buttons? Do I build a function in the code behind for each one (Which would be mostly boring and repeating myself), or do I build one to handle any button clicked?
In the second case, how do I identify which button was clicked? What property of the sender object do I need to access?
Answer: If you want to use code behind then you can hook it up to a single event handler, you can then cast sender to a Button (or a FrameworkElement) and check its Name property.
Expanding on Goblin's answer below; if you want to stick with code behind and events you can define the event on a parent panel:
<StackPanel Button.Click="anyButtonClicked">
    <Button Content="0" Name="button0"/>
    <Button Content="1" Name="button1"/>
    <Button Content="2" Name="button2"/>
    ...
    <Button Content="9" Name="button9"/>
</StackPanel>

Then use e.OriginalSource, cast as a Button or FrameworElement, to retrieve the name.
private void anyButtonClicked(object sender, RoutedEventArgs e)
{
    var source = e.OriginalSource as FrameworkElement;

    if (source == null)
        return;

    MessageBox.Show(source.Name);
}

Alternatively you could take the MVVM approach, have a single command that all of your buttons are bound to, and pass a CommandParameter to differentiate them.
Answer: You handle the Button.Click event in the Parent control:
<StackPanel Button.Click="anyButtonClicked">
    <Button Content="0" Name="button0"/>
    <Button Content="1" Name="button1"/>
    <Button Content="2" Name="button2"/>
    ...
    <Button Content="9" Name="button9"/>
</StackPanel>

Then in your eventhandler - you can check e.OriginalSource for the button pressed.
EDIT: As for your question as to how to handle it - you could use the Content-property of the button pressed to figure out the key and then use that to perform your logic.
Comment: Hehe - no, as your app expands - that's probably not a good ide. I agree with Veer and Steven to go the Command way when you get a bit farther. "First get it working...".
Comment: Thank you.

Umm, is using the content property a good idea? I could imagine the content changing in a multi-language environment. (I haven't gotten so far yet, though.)
Answer: You really need to go by the Command approach because you may need it for key presses also.


Find all integers $n$ such that $n^2-7n+10$ is divisible by $n-3$.

Question: Find all integers $n$ such that $n^2-7n+10$ is divisible by $n-3$.
I have been advised to find an expression containing $n^2$ that is divisible by $n-3$, but I don't see how that would help at the moment.
Comment: Hint: Set $n-3=h\iff n=h+3$
Answer: We have
$$n^2 - 7n+10 = n^2 - 6n+9 -n+1 = (n-3)^2 -n+1 = (n-3)^2 - (n-3) -2.$$
Thus the expression is divisible by $n-3$ if and only if
$-2$ is. Finding all these $n$ should not be that hard. ;)
Answer: Hint. Note that $n^2-7n+10=(n-3)(n-4)-2$
Answer: I did the  division and got $$n^2-7 n+10=n-4-\frac{2}{n-3}$$
and this shows that $n-3$ must be divisible by $\pm 2$, therefore
$1\le n\le 5\land n\ne 3$ which  gives only $n=1;\;n=2;\;n=4;\;n=5$.
Comment: The denominator on the LHS is missing.


Is the set $O:= \{(x,y) \in X \times X: d(x,y) < r \}$ Borel measurable?

Question: Let $(X,d)$ a metric space and $\mathcal{X}$ its Borel sigma-algebra, i.e. the sigma-algebra generated by the open sets of $X$. Is the set $O:= \{(x,y) \in X \times X: d(x,y) < r \}$ $\mathcal{X} \otimes \mathcal{X}$-measurable, where $\mathcal{X} \otimes \mathcal{X}$ is the product sigma-algebra? My thought to show that was that $O=\bigcup_x \{x\} \times B(x,r)$ where $B(x,r)$ is the open ball of center $x$ and radius $r$...
Answer: The title and the body ask two different questions.
Is $O$ Borel measurable, i.e. in the $\sigma$-algebra generated by the open sets of $X \times X$ (in the product topology)?  Yes, indeed it is itself an open set.
Is $O$ measurable with respect to the product $\sigma$-algebra $\mathcal{X} \times \mathcal{X}$?  Not necessarily.  See this MathOverflow question and references therein.
Comment: I forgot to mention $X$ is separable.
Comment: @user44670: Ah.  When $X$ is separable then these two $\sigma$-algebras are identical, so the answer to your question in that case is an unambiguous "yes".
Comment: thanks for your quick answer, and sorry for the imprecisions.
Answer: Note that the function $(x,y) \longmapsto d(x,y)$ is continuous on $X \times X$. Continuous functions are Borel measurable.
Comment: god I'm stupid. Thanks.


Can I read the CSV file from which use first column and that column as input to spinner with no repetition?

Question: I have designed a Spinner GUI where I had given some set of options and that's been working but I need to know how to display the set of options by scanning values from CSV file and displaying as an options set, here I am able to display the set of values too, but not as an input for spinner. In my CSV file there are lot of repetitions of same value so I have used Counter from pandas and sorted, so that it will display only once.
My Code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.spinner import Spinner
import pandas as pd
from collections import Counter

Builder.load_string('''
<MainScreen>:
    AnchorLayout:
        anchor_x: 'center'
        anchor_y: 'top'
        BoxLayout:
            size_hint: 1, .9
            orientation: 'vertical'
            padding: 20
            spacing: 20
            Spinner:
                id: firsto
                text: 'select'
                values: root.optionf
                on_text: root.updatesecond(firsto.text)
            Spinner:
                id: secondo
                text: 'select'
                values: root.options

''')
class MainScreen(FloatLayout):
    def __init__(self, **kwargs):
        self.buildLists()
        super(MainScreen, self).__init__(**kwargs)
    def buildLists(self):
        df = pd.read_csv('data.csv')
        saved_column = df['marks'] #you can also use df['column_name']
        a = (Counter(saved_column))
        b = (sorted(a))
        print(b)
        self.optionf = ['Select','a','b','c']
        self.options = ['Select']
    def updatesecond(self,text):
        if text == 'a':
            self.ids.secondo.values =['1','2']
        elif text == 'b':
            self.ids.secondo.values =['3','4']
        else:
            self.ids.secondo.values =['5','6']
    def onExit(self):
        App.get_running_app().stop()

class TestApp(App):
    def build(self):
        return MainScreen()
if __name__ == "__main__":
    TestApp().run()

Is it possible to scan first column of csv file. Where first column is of distance where it is repeated more than once suppose column first is of distance of 70.1,40,5.1,40.8,70.1 where 70.1 will be repeated more than once it should be displayed only once in spinner first. Instead of this line =>>>
self.optionf = ['Select','a','b','c']

values from CSV are to be displayed.
Thank you.
Answer: I figured it out we just need to make some changes like:
instead of this line
self.optionf = ['Select','a','b','c']

make some change as
self.optionf = [str(row) for row in (a)]

where a is the value in which values are stored of column first.


Should I save a path with or without a trailing slash at the end, what's the convention

Question: I'm always confuse whether I should add a trailing slash at the end of a path, and often mix it up, leading to some file no found.
Example with drupal:
$base_theme = '/sites/all/themes/myTheme/';

or
$base_theme = '/sites/all/themes/myTheme';

The image path could extend the base theme:
$base_image = $base_theme.'images/';

or
$base_image = $base_theme.'/images';

Is there any convention? Or I can pick which one I prefer?
I would choose to finish all path with a trailing slash since too many slash is better than no slash.
Comment: Anyway, whatever way you prefer, if you start working on an ongoing project, look at how is done there. I hate when you have some paths defined with and some without a trailing slash.
Comment: I tend to agree with you that more is better than less since it won't break anything... I'm curious if there's any convention for this as well.
Comment: See related question in programmers.SE: http://programmers.stackexchange.com/questions/84778/trailing-forward-slash-in-directory-names-good-programming-practice
Comment: I do not add the trailing slash. My reasoning is that a folder name does not include the `/`.
Comment: See also https://stackoverflow.com/q/980255/1668200
Answer:
TL;DR: There's no real convention. Trailing slash would be the more globally easy to recognize format. The important thing is that you're consistent through your design and that you convey your usage clearly.

There's no real convention; but there are considerations to make.
Advantages in trailing slash:

Trailing slash usually indicates a folder path (or a prettified URL) whereas a file extension denotes a direct file link. (Think example.com/home/ VS example.com/style.css).
This is usually friendlier for people coming from UNIX and such, as in the terminal a clear convention is to leave a trailing slash for directories.
As a programmer - adding a trailing slash will result in less-likely programmer errors; for example: accidentally adding a second slash will look ugly (http://example.com/styles//myfile.css) but will not break the file link. Forgetting a slash will: http://example.com/stylesmyfile.css, however the behavior might be confusing for query strings: http://example.com/thread?id=1 VS http://example.com/thread/?id=1 <- the result really depends on how you handle your .htaccess.

Advantages in no trail:

Prettier, some might say
It's easier to remember and it's more readable to always add a slash when appending paths to a variable string than not. i.e. it's easier to remember $baseURL . '/path.php' than $baseURL . 'path.php'


Check if sum of squares of first N fibonacci numbers is co-prime with Xth fibonacci number

Question: This question is from an online coding platform.

Given two integers N and X, find whether sum of squares of fibonacci numbers from 1 to N (both inclusive) is co-prime with Xth fibonacci number or not.
Print "Yes" if it is divisible or "No" otherwise (without quotes).

Input:

The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains two space-separated integers N and X.

Output: For each test case, print the answer.
Constraints:

$1 ≤ T ≤ 10^5$
$1 ≤ N, X ≤ 10^9$

Example:
Input:
2
4 2
23673332 12
Output:
Yes
No
Explanation:
Test Case 1 : F12 + F22 + F32 + F42 = 12 + 12 +
22 + 32 = 1 + 1 + 4 + 9 = 15 and 15 is co-prime
with F2 which is 1.

I came up with a solution which uses these facts:

$\sum_{i=0}^n F_i^2 = F_n.F_{n+1}$
$GCD(F_n, F_{n+1}) = 1$
$GCD(F_m, F_n) = F_{GCD(m, n)}$

Here my Java Solution but it is not getting accepted.
import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int t = sc.nextInt();
        while (t-- > 0) {
            int n = sc.nextInt();
            int x = sc.nextInt();
            if (gcd(n, x) == 1 && gcd(n + 1, x) == 1) {
                System.out.println("Yes");
            } else {
                System.out.println("No");
            }
        }

        sc.close();
    }

    static long gcd(long a, long b) {
        if (b > a) {
            return gcd(b, a);
        }

        if (b == 0) {
            return a;
        }

        return gcd(b, a % b);
    }
}

If I change condition gcd(n, x) == 1 && gcd(n + 1, x) == 1 to gcd(n, x) <= 2 && gcd(n + 1, x) <= 2 then it gets accepted.
Can anyone shed some lights on why is this happening?
Comment: One, possibly relatively minor, issue is that the online coding question is not self-consistent. It asks to find if $2$ integers are co-prime, but then for the output, you're to print "Yes" if *it* is *divisible* and "No" otherwise. However, I'm not quite sure what "it" is referring to, plus one integer being divisible by another is *not* quite the same thing as those integers being co-prime to each other.
Comment: @JohnOmielan yes you are absolutely right...2nd part of question is little bit confusing. At first glance I was confused too but it is indeed asking to for co-prime.
Answer: Now that I analyzed my solution again I foud out that I was making a silly mistak.
Let me show what

If I change condition gcd(n, x) == 1 && gcd(n + 1, x) == 1 to gcd(n, x) <= 2 && gcd(n + 1, x) <= 2 then it gets accepted.

The problem lies in the fact that $GCD(F_m, F_n) = F_{GCD(n, m)}$ hence whenever gcd(n, x) <= 2 && gcd(n + 1, x) <= 2 is true we know for sure that $F_1 = 1$ or $F_2 = 1$ is the answer respectively.
Hence
$$GCD(F_n, F_m) = 1$$ will always be true(since $F_1 = 1$ and $F_2 = 1$).


Artificial neural networks for Temperature prediction

Question: Imagine I want to consider the temperature for a process given several input varibales. The temperature can be anywhere between 400 and 500 K. Consider I have experimental data to train the network and then I want to predict the temperature for a test point. Consider the data as non linear.
As I understand the theory of NN activation function are needed to bound the value between 0 and 1. How could I proceed in my example? Should I just scale my data between 0 and 1? Are there good and bad methods to scale (of course there will be?). Or should I modify the activation function?
However, what if one of the training point's is at 600 K. If I bound the values it would be impossible for the NN to reach this value. I hope someone can give me clarity on this issues.
Answer:
As I understand the theory of NN activation function are needed to bound the value between 0 and 1.

No. There are various activation functions, only some of them are bounded (e.g. tanh, sigmoid). One of the most popular activation functions is ReLU which has unbounded positive end. Bounded activation functions are useful for classification and recurrent neural networks, neither of which is your case.
As you are performing regression, just leave the outputs as they are. A neural network with linear output unit should handle it well.
What you might need to scale are the inputs. Neural networks often exhibit better behavior when the inputs are scaled to zero mean and unit variance.


How I can write a function that will display the path in the Browser Console

Question: I want to write a function that will display the path in the Browser Console when I click on a link of the menu on the sub-category, the menu looks like this (https://www.sephora.fr/) in this e-commerce website
For example : Parfum => ForMen => Cologne
How to get the path when I click on Cologne
Thanks
Comment: Like, breadcrumbs in the console log?
Comment: Does this answer your question? [How can I get pathname values from url in JavaScript?](https://stackoverflow.com/questions/59966711/how-can-i-get-pathname-values-from-url-in-javascript)
Answer: If you're just looking to get the path without the domain name, you can use this:
function getUrlWithoutDomain() {
   return window.location.pathname;
}

If the domain name is also important, this will get you the full url:
function getFullUrl() {
   return window.location.href;
}

Answer: Not sure if this is what you are looking for, but this will return the relative path for the website whenever an anchor tag is clicked on.
const anchors = document.querySelectorAll('a');

anchors.forEach(el => el.addEventListener('click', event => {
  console.log(event.target.getAttribute("href"));
}));

Also check out JavaScript click event listener on class for a similar question.
Comment: Side note: this is not a persistent solution, since one you leave the page you click on, you would have to execute this code in the browser console again.


AWS Elastic Load Balancer : white list only my IP

Question: My objective:
To make my AWS Elastic Load Balancer hittable by only traffic from my ip.
What I have tried:

created a security group in EC2 security groups
set an inbound rule that allows all traffic from my ip [all, all, all, /32]
assigned this ELB the newly created security group
attempted to hit the elb from an ip outside myoffice

The results:
All traffic, even from ips other than mine could still hit my ELB (and thus get through to my app servers).
What am I doing wrong? How can I block inbound traffic to my ELB (and the EC2 instances behind it)?
Comment: Check and make sure your ELBs have only the one security group.
Comment: So the only thing in your inbound rule is a Custom IP?
Comment: yes my inbound rule looks like so:  All traffic
All
All
/32
Answer: You need to create a security group on your app servers that only allows inbound traffic from the ELB security group.
As the docs say:

This feature involves two security groups—the source security group and a security group that defines the ingress rules for your back-end instance. To lock down traffic between your load balancer and your back-end instances, add or modify a rule to your back-end security group that limits ingress traffic so that it can come only from the Amazon EC2 source security group provided by the Elastic load Balancing.
Comment: This will prevent someone from bypassing the ELB and going straight to the servers directly, but it won't fix OP's issue at all if the issue has been accurately described.
Answer: Verify below.
1) Default security group of VPC if attached to the ELB, permitting 80 to any ?
2) No other SG should be attached to the ELB than what you have explicitly allowed for
3) Since you can only permit traffic in Security group and rest all will hit to implicit deny, there is another method to drop all traffic in the NACL of subnet where ELB was launched.


Cordova system browser apk link does not open

Question: I am using the cordova-plugin-inappbrowser to open a link in the system browser like so:
cordova.InAppBrowser.open('http://example.com/myapp.apk', '_system');

This works if the browser is not running already when this line is executed. It also worked with all other but my apk links that I tried.
If the browser is already running however, the tab immediately vanishes again without starting the download. Is this a bug in the inappbrowser plugin or chrome mobile? How can I make this work?
Answer: The almighty setTimeout solved this problem (I have no idea why, would be happy if someone could explain):
setTimeout(function() {
   cordova.InAppBrowser.open('http://example.com/myapp.apk', '_system');
}, 250);

Comment: Probably cordova.js wasn't loaded before you called the inAppbrowser functions
Comment: have you wrapped the function in a deviceready event listener? `document.addEventListener('deviceready', () => {
  cordova.InAppBrowser.open('http://example.com/myapp.apk', '_system');
}`


How to modify variables to be significant in logistic regression?

Question: I am running a logistic regression analysis in a particular software. My objective is to study the behavior of the software with significant variables.
However, with the data I have, there are no significant variables.
It does not matter if I modify the data and forcefully make a variable to be significant.
Any ideas how I can modify a variable so that it becomes significant?
I tried a linear combination of the output variable with different random distributions for the two values. However it did not work.
var1 = out * (random sample from distribution 1) + (1-out) * (random sample from distribution 2)
out is a binary variable (0 or 1).
Thanks
Answer: You could just add coppies of the data underneath each other to artificially increase the sample size. Eventually your variables will become significant.
Answer: Make the two distributions very different.
<code>Create data set 1:  OUT = 1, var1 ~ N(-10, 5), N = 100
Create data set 2:  OUT = 0, var1 ~N(10,5), N = 100
</code>
Merge the two and run your logistic regression.
(Since you didn't specify a language, I just wrote the above rather than R code)


What are the common problems when it comes to ear training and how do I fix it?

Question: I can think of a few, first in formost, there is 2 different type of struggles
transcribing in real time which requires you to hear and identify chords and melody
and improvising, which requires you to be able to know and hear what notes you want to play before you play it.
I think most people either can do this but can't do that or can do that but can't do this
but another problem is that beginners like me cannot even identify scale degrees/function in the context of music, heck I'm having trouble identifying or singing 2 intervals in a row.
here is my thought process from this example: sing a major interval from C then sing a major interval from E
I first play C then sing up a third no problem, then I repeat the note E and sing a major third to G#? what's the problem with that?
I just changed keys, basically, I didn't hear if as a function functioning in the key but rather changed the key in my mind in order to sing that major third.
anyways learning ear training is super hard for me. my end goal is to be able to transcribe songs in real time and compose but I don't know what I'm really suppose to know
then there's out of key notes like
modes
modal mixture
secondary dominants
modulation
swaying
extended chords
etc
Comment: Sorry, what's "swaying" in the context of this question? By any chance, is it rapidly switching back and forth between 2 keys, or do you mean something else?
Comment: what i mean by swaying is that the key change to major and minor constantly
Answer: You can't take the whole world on in one go!
Take your time about it. Stick to one key at a time, where most, if not all of the intervals will be diatonic. All from the parent scale. Get to know the scale so well you can sing from, say, note 2 to not 7; note 5 to note 1. And recognise them all when they're played. Just two notes at a time. I think it's better initially to think in terms of scale degrees and their intervals rather than just intervals on their own.
Problem potentially with intervals on their own is that an aug 4 sounds just like a dim 5, but further down the line, you'll be able to work out the probability of one being correct.
Once you are absolutely rock-solid with diatonics, modal stuff, parallel keys and modulations will stick out like the proverbial sore thumb. one of the notes (usually) will sound out of key (written with an accidental) - mainly 'cos it is - and that will alert your ear to non-diatonic intervals.
Rather like sight-reading, this can be done backwards. When I teach sight-reading, one trick is to play something and get the student to write it out, note at a time. This is what I mean by backwards. So, write an interval, sing it, play it. Then with a known start note, and maybe even a root chord to anchor your ear, play the other note, write it, sing it. Better still, get someone else to do the playing.
There's a lot more, but this is good for a few months.


Action listner not working on image in android with draglayout

Question: My xml code :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.my_slide_menu"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.my_slide_menu.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

And java file
    package com.example.my_slide_menu;

    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.View.OnTouchListener;
    import android.widget.ImageView;
    import android.support.v4.widget.DrawerLayout;
    import android.content.res.Configuration;
    import android.graphics.Color;
    import android.os.Bundle;
    import android.support.v4.app.ActionBarDrawerToggle;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v4.view.GravityCompat;
    import android.support.v4.widget.DrawerLayout;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListView;

    import com.actionbarsherlock.app.SherlockFragmentActivity;
    import com.actionbarsherlock.view.MenuItem;

    public class MainActivity extends Activity {

        private DrawerLayout drawlayout = null;
        ImageView arrow;

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

            System.out.println("On create");

            // drawlayout=(DrawerLayout)findViewById(R.id.drawer_layout);
            arrow = (ImageView) findViewById(R.id.arrow);

    //      getSupportActionBar().setHomeButtonEnabled(true);
    //      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    //      getSupportActionBar().setDisplayShowHomeEnabled(true);
    //      getSupportActionBar().setDisplayShowTitleEnabled(true);

            arrow.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {
                    // TODO Auto-generated method stub
                    System.out.println("Touch");
                    return false;

                }
            });

        }

    }

How solve this Proplem.
I want when click on image slider open.But action listner not work on image.
Without drwer click listner working.
I am making a slider menu like face book.
Please help me
My layout file is
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/arrow"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerHorizontal="true"
        android:src="@drawable/a" />

    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <ListView
            android:id="@+id/listview_drawer"
            android:layout_width="240dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:background="#111"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="0dp" />
    </android.support.v4.widget.DrawerLayout>

</RelativeLayout>

Comment: Where is this image in view ?
Answer: Set arrow as ImageButton or add:
android:clickable="true" android:focusable="true"

Hope it helps


How do I check whether a class has children classes in Python?

Question: Is there a function that takes a class as a parameter and returns True or False depending on the existence of its children classes? Can it be possible in principle?
class A:
    pass

class B(A):
    pass

has_children(A)  # should return True
has_children(B)  # should return False

I would like to know a solution without access to globals(), locals(), vars().
Comment: Just for references, I have just posted a solution working with old style Python 2 classes (no __subclasses__ method available)  under the [duplicate question](https://stackoverflow.com/a/46893520/3545273)
Answer: You can use the __subclasses__ method:
def has_children(cls):
    return bool(cls.__subclasses__())

This method is only defined for "new-style" classes (inherit from object in Python 2, default in Python 3).
Comment: Thanks, it worked.


Faulty fretboard

Question: My acustic guitar (Fender cd-140sce) is 2-years old, played an average of 1hour a day, and appears to have developped the following problem.
For several combinations of strings and positions on the fretboard, if you press the string on fret X, the string touches on the the fretboard on fret X+2. For example: the high E plays correctly, but if you try to play F you get a G note, playing F# gives you G, and playing G is the actual G.
I also notice the strings tend to vibrate on the fretboard if strum energetically, much more than before. I changed strings recently and it only changed the combinations of string/fret where the issue shows.
Answer: Seems like the neck has moved slightly. There needs to be a very slight bowing so the frets/fretwires are a little further away around the 12th fret than at the nut end. Usually, necks bend the opposite way, producing too much relief!
At the head of the guitar is a plastic plate, which when removed reveals the head of a long bolt which is known as the trussrod. It may be on your fender that the head is seen at the other end of the neck - inside the sound hole. Usually you need an Allen key - a hex key. By turning it to loosen the neck will unstraighten. A quarter/half turn at a time is recommended.
If you're unsure what to do, it's best left to an experienced person, as this can be a critical operation for the guitar
If this happened before the string change, and you're at concert pitch, it won't be the strings causing the problem..

Faulty fretboard


How to link to section in same static page?

Question: How to create a menu link to the section that will display when I click on the link and hide when i again click on the link..
link is
    contact me

the above link should open

//some code

Comment: I'm not sure if I understand your question correctly – are you looking for a way to ***toggle*** (show/hide) an elemet?
Comment: u can say this but not exactly, its like showing a section on click there is 4 sections.
Answer: You need to use Jquery and a tiny bit of css.
Javascript
$('.page-scroll').click(function() {
    $('.cat-pages').toggle('slow');
});

css
.cat-pages { display: none; }

JS FIDDLE DEMO EXAMPLE
edit:
To use jquery in drupal you use
(function ($) {
    // code goes here
})(jQuery);

go to drupal/sites/all/themes/YourTheme/
look for your  theme.info file and add this line in there
scripts[] = js/myscript.js

Then go drupal/sites/all/themes/YourTheme/js and create myscript.js file.
put this inside it
(function ($) {
    $('.cat-pages').hide();
    $('.page-scroll').click(function() {
        $('.cat-pages').toggle('slow');
    });
})(jQuery);

If the above doesn't work, try
(function ($) {
    $(document).ready(function () {
    $('.cat-pages').hide();
            $('.page-scroll').click(function() {
                $('.cat-pages').toggle('slow');
            });
    });
        })(jQuery);

PS:
Don't worry about .cat-pages { display: none; }css anymore, since I added the hide in the jquery $('.cat-pages').hide();
Comment: thank you..its working fine in fiddle but how i can use it in drupal 7...
Comment: I edited my answer.
Comment: thank you its working fine..to achieve my goals i have to play with my css...thank you ..