I updated my android studio and gradle to the latest one -> and I can't work with data binding

Question: I get this error message in app Gradle:

Failed to resolve: com.android.databinding:library:3.3.2

I see in another question it because of apt that in the Gradle
I don't have apt in my Gradle
Here is my app Gradle:
apply plugin: 'com.android.application'
android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.ophiropt.meissa"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags "-std=c++1z -frtti -fexceptions"     }   }
        ndk {
           abiFilters 'armeabi-v7a'   }
        vectorDrawables.useSupportLibrary = true}
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        } }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }}
    dataBinding {
        enabled = true }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    compile 'com.rengwuxian.materialedittext:library:2.1.4'
    compile 'com.couchbase.lite:couchbase-lite-android:1.2.0'
    compile 'com.google.code.gson:gson:2.6.2'
    compile "com.android.support:recyclerview-v7:25.0.0"
    compile 'com.android.support:cardview-v7:25.0.0'
    compile 'com.android.support:design:25.0.1'
    compile 'org.greenrobot:eventbus:3.0.0'
    testCompile 'junit:junit:4.12'
    compile 'com.afollestad.material-dialogs:core:0.9.4.5'
    compile 'com.elmargomez.typer:typerlib:1.0.0'
    compile (name:'charting-release', ext:'aar')
    compile (name:'drawing-release', ext:'aar')
    compile (name:'data-release', ext:'aar')
    compile (name:'core-release', ext:'aar')
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
}

Comment: did you enable data binding your app gradle ?
Comment: @HemantParmar yes I did, I added the code to my question
Answer: You need a google() dependency:
buildscript {
  repositories {
      google() // here
      jcenter()
  }
  dependencies {
      classpath 'com.android.tools.build:gradle:3.3.1'
  }
}
allprojects {
  repositories {
      google() // and here
      jcenter()
}

Answer: the problem by me was that the minimum SDK version with Gradle gradle:3.3.2 has to be 28 and by me, it is 25


Am I Doing It Wrong? Why Can't I Use Multiple 5-Line Staves to Represent Guitar's Open Strings?

Question: As a rock songwriter with interest in theory, I sometimes score my music to engage with it differently.  I'd open MuseScore, create 3 treble clef staves—one for the voice and two for the guitars—and a bass clef staff for the bass guitar.  I'd use the default "piano" instrument sound for playback and away I'd go!
After many years, I found out last night while reading Don Sebesky's The Contemporary Arranger that the bass guitar is a transposing instrument (I didn't know what this meant until yesterday).  It dawned on me that this whole time the playback I was hearing was two octaves higher than the actual bass sounds I'd one day record.  This was an unpleasant revelation because it meant my perception of the instrument's range has been wrong for as long as I've been composing.  I wonder if, for songs I've released, I would have written the bass part in a different octave or played different notes had I been aware of the massive space between the sounded bass notes and the notes the of the guitars (maybe) and my voice.  Then, as you might have guessed, I learned that the guitar too is a transposing instrument.  Yikes!  I really was disoriented by this.
I took pen to stave to try to visualize the notes for myself—I was having trouble seeing notes one way but hearing them in my aural imagination a different way.  I wanted to map out the actual notes so that I could see them where they "belong" on the staves.  I started with the guitar.  I had a treble clef, but I didn't want to draw all the ledger lines to get down to the E2, which is the note sounded by the open 6th string of a guitar.

So, I used the following staff, leaving it 'un-clefed' if you will, so that I could use those staff lines instead of ledger lines.  Well, lo and behold, that must have been the wrong move because look:

If I count an octave down from E4 to E3 and then an octave down from E3 to E2, and then start writing the notes of the open guitar strings, I don't end up on the right staff?  This doesn't make any sense to me.
So then, I took a different approach, just extending the ledger lines so that I had a treble clef with 12 staff lines.  I would guess that this is the better representation of the notes, but it does bother me that the first method didn't work.

Can you please help me understand why I couldn't use multiple 5-line staves to represent the notes of the open strings on a guitar?
Of course!
TL;DR: I've been using MuseScore for rock song notation. As a beginner in reading music, I find it mentally taxing to imagine a sound different from what's notated. I tried to represent guitar notes on an 'un-clefed' 5-line staff to help, but got confused. Why can't I use multiple 5-line staves to accurately depict the guitar's open strings?
Comment: ....and they wonder why we prefer tab.  ;-)
Comment: Does this answer your question? [Why is the usual clef for guitar G clef?](https://music.stackexchange.com/questions/118892/why-is-the-usual-clef-for-guitar-g-clef)
Comment: Another question that has the answer you need: https://music.stackexchange.com/questions/101432/why-is-guitar-music-written-one-octave-higher
Comment: @PiedPiper thanks--it's insightful (honestly I didn't check it out originally because I didn't know what the G clef was), but doesn't tackle the issue of a non-transposed solution, if that makes sense
Answer: You are trying to reinvent the wheel it seems. All you have to do if you want to see the actual pitches of the open strings of the guitar is use the grand staff:

I showed where the G and B strings are written in treble clef with parentheses.
As you said, you discovered both guitar and bass are transposing instruments, octave transposing to be more specific. They both sound one octave below where they are written so they are written one octave higher so they sound in the correct register.
The bottom line is guitar already has had a system in place for notating and reading music for hundreds of years, the octave transposing clef. This allows you to write for guitar using treble clef and only have to use 3 ledger lines to write the lowest note, open E on the 6th string.
By placing an "8" below the treble clef (which is usually excluded if it is written as specifically guitar music) it means that every pitch you see sounds an octave below where it is written. This is the way the open strings are represented for guitar, you just have to take into account that everything sounds an octave lower than written:

It takes a little getting used to but you do eventually get used to creating and reading guitar music with the octave difference.
Comment: @MichaelSeifert The open strings can be easily written with just bass clef and 2 ledger lines (not 1) above the staff. However, the impression I got from the question is the need to be able to visualize the location of the open strings in relation to the actual non-transposing treble clef. The octave transposing treble clef was chosen as the standard for guitar music many decades before we were born. It is better than bass clef because the open high E in bass clef is already at 2 ledger lines and most guitar music extends up to an octave or more above that.
Comment: The grand staff evolved for organs, where there are a lot of voices stacked at once. Although the guitar is a polyphonic, chordal instrument, throughout its history it has also spent a lot of its time being melodic. Having a single staff is easier to scan at a glance and has suited the guitar's needs through the centuries.
Comment: To head off a few follow-up questions: There are a lot of questions on here in the form "Why do we X, when it would be better to Y," and the answer is often "because that's the way that's fallen into practice," like QWERTY keyboards still being the most common even though other layouts are more efficient. But there could be some good reasons not to use a non-transposing grand staff:
Comment: @286642 Alternatively to 8va, for high guitar passages, sometimes _loco_ mark is used, which means "play the notes as written, not transposed"
Comment: @286642 The bass transposes only one octave below bass clef, not two. In the case of bass and guitar it is assumed that those instruments will sound an octave below written so the "8" is rarely if ever used in their clefs. Guitarists are used to reading several ledger lines above the staff but there is always an option to write "8va" above a passage that goes very high. That takes the transposition into consideration, so a passage written for guitar with "8va" will actually sound at regular pitch.
Comment: Why wouldn't you just use the bass clef to write a part in this range?  For the gamut that you've written, you only need one ledger line above the staff and one below it.  (I know next to nothing about guitar/bass playing, so I'm probably missing an obvious answer to this question.)
Comment: @AndyBonner "because that's the way that's fallen into practice" That does answer an awful lot of questions, although sometimes not to the asker's satisfaction, lol! +1 for your comments.
Comment: @JohnBelzaguy  thank you very much for your response to this question.  I'm wondering 1) in the case of the bass guitar, can an "8" be placed under the bass clef for a two octave transposing clef? and 2) would the octave transposing clef in your second image above become less useful as you play higher and higher pitches with the guitar?  Obviously the low E string (which requires 3 ledger lines) is the floor for the guitar, but the ceiling presumably goes inconveniently high?
Answer: I think where you've gone wrong in your second image, is by counting down one "staff" (of 5 lines) as being an octave, and two staffs (10 lines) as two octaves. But an octave is really 3½ lines.
So you're off by 2 × 1½ = 3 lines.
But you're also doing something weird by using ledger lines between "staffs" of ledger lines, because the B3 is apparently on a leader that wasn't there before.  If you count up from the G3 directly onto the next "staff" of ledger lines (without any additional ledger lines in-between), you'll get B3 in the first space.
So you're off by 2 spaces. (And spaces are the same distance apart from one another as lines are), so that's equivalent to being off by another 2 lines.
If you add up these errors 3 + 2 = 5, that's a whole staff of lines out of place, which is why your E3 and E4 are apparently in the same position.
Comment: Thank you.  I figured I was miscounting, and I appreciate the explanation here.
Answer:
If I count an octave down from E4 to E3 and then an octave down from E3 to E2, and then start writing the notes of the open guitar strings, I don't end up on the right staff? This doesn't make any sense to me.

Well, it looks like you accidentally marked your staves in multiple different ways that contradict each other, and now you've noticed that there are contradictions, but you're not sure where they came from. I'm not sure what the initial mistake that you made was, but hopefully I can help you figure it out.
I'm guessing that you started by labeling the bottom line of the three staves as E2, E3, and E4. As you know, that's a non-standard way of doing things, but there's nothing wrong with it; it'll just be hard for other musicians to understand. So, everything is good so far.
I'm guessing that after that, you drew the notes A2, D3, and G3 on the bottom staff. Again, so far, so good.
Then I'm guessing that after that, you attempted to draw B3 on the bottom staff. However, you made a mistake in doing so. If E3 is the bottom line, then B3 is the third line from the bottom. You mistakenly drew B3 in the second space below the bottom line instead.
After that, you drew E4 in what would have been the correct location if B3 had been correctly placed. As a result, the bottom line ended up being labeled as both E3 and E4, and that's the point where you noticed that something was wrong.
I have a guess as to why you made the mistake. The standard bass clef and the standard treble clef have a "gap" between them—middle C is above the top line of the bass clef, but below the bottom line of the treble clef. When you drew your B3, you made a guess (a reasonable guess, but one that turned out to be wrong) that there would also be a similar gap between your bottom staff and the middle staff, and so you expected B3 to end up below the bottom line.
However, your staves actually overlap each other. For example, the bottom line of your middle staff is E3, but the top space of your bottom staff is also E3. The space above the top line of your bottom staff is G3, but the second-from-bottom space of your middle staff is also G3.
A good option would be to simply use the grand staff, with a bass clef and a treble clef, as the other answers have suggested. Another reasonable option, albeit a non-standard one, would be to just omit your middle staff, and have one staff where the bottom line is E2 and one where the bottom line is E4. (In order to "clef" that staff, you might draw a treble clef with the number 15 at the bottom, or you might draw a bass clef one line higher than usual. The result would still be somewhat confusing for other musicians, but that clef would make it less difficult than it would be with no clef at all. Of course, none of that matters if this is all for your own use and other people aren't going to read it.)


How to show, that the set of density functions with compact support is compact wrt. Wasserstein Metric?

Question: In an Optimal Transport Math project we are currently working on we want to show that the Infimum of a Functional $\inf_{~f\in\overline{\mathcal{P}_{ac,2}(\Omega)}}H[f]$ is reached, where $\mathcal{P}_{ac,2}(\Omega)$ denotes the set of density functions on a compact set $\Omega \subset \mathbb{R}$ with finite second moments:
$\int_{\Omega}f(x)dx = 1,~\int_{\Omega}|x|^2f(x)dx < \infty$
We introduced the Wasserstein Distance as a Metric on $\mathcal{P}_{ac,2}(\Omega)$ before:
$W(\mu, \nu) = \left(\inf_{\eta \in \text{ Adm}(\mu, \nu)} \int_{\mathbb{R} \times \mathbb{R}}|x-y|^2d \eta (x,y) \right)^{\frac{1}{2}}  $
$\text{Adm}(\mu, \nu) = \{\eta \in \mathcal{P}(\mathbb{R} \times \mathbb{R}): \text{The Marginals of } \eta \text{ are } \mu \text{ and } \nu \} $
$\mu$ and $\nu$ being Probability Measures on $\mathbb{R}$.
As simplification we are only dealing with absolutely continuous probability measures on $\mathbb{R}$ wrt. Lebesgue Measure.
Since we already showed $H$ to be lower semicontinuous (and strictly convex) before, it seems obvious to show that $\overline{\mathcal{P}_{ac,2}(\Omega)}$ is compact to conclude that the Infimum is reached.
We can't seem to find a way to proof it though. Using the usual ways to show compactness seem to be very unhandy with the Wasserstein Metric. Is there an obvious point that we are just overlooking, or a theorem that could help? We didn't take any courses in Functional Analysis, so we are not very familiar with compactness in function spaces, and the Theorems we found (eg. Arzelà-Ascoli) don't seem to help either.
Answer: This is what I would suggest, but I would be open to any comments/suggestions to tighten up the analysis. Since you have already shown your functional $H$ is lower semicontinuous then you are already nearly there. A standard recipe for a problem of this sort is

 Pick a minimising sequence $\mu_n \in \mathcal{P}_{ac,2}(\Omega)$ of your functional $H$.
 Show that $\{ \mu_n \}$ has a convergent subsequence, $W(\mu_{n_k}, \mu_0) \rightarrow 0$ for some $\mu_0$ in $\overline{\mathcal{P}_{ac,2}(\Omega)}$
 Since $H$ is lower-semicontinuous then
$$
H(\mu_0 ) = \inf\left\{ H(\mu) \; : \mu \in \overline{\mathcal{P}_{ac,2}(\Omega)} \right\}.
$$

Since you have already done $3$ and you have $H$ is strictly convex giving the uniqueness of the minima, the only challenge is $2$.
Now since $\Omega$ is compact it can be shown (see here) that the space of all probability measures on $\Omega$ is compact with respect to the weak topology which guarantees a weak convergent subsequence, but it is also true that convergence in the second Wasserstein distance  metric is equivalent to weak convergence plus convergence of the first two moments of elements in the sequence. So that $\mu_{n_k} \rightarrow \mu_0$ weakly with $\mu_{n_k} \in \mathcal{P}_{ac,2}$ implies that $W(\mu_n,\mu_0) \rightarrow 0$.


How can i give link in block for only listed paths based on user id?

Question: I have created block and i want to give the only listed paths
i.e user/user_id   ex: user/123
i have given user/*  but it displays all pages where users pages are there.
i tried below ways
and enabled PHPFILTER and tried this
Answer: Try "extended_block_visibility" module, install it and then on block setting page select last option "pages on which this php code will return true" and then you can write php code inside php tag like :
<?php
if(arg(0) == 'user' && is_numeric(arg(1))){
return TRUE;
}
return FALSE;
?>

But remember this code will save inside the DB and will break site if write wrong code. Alternatively you can define theme specific visibility using this module.
Comment: ok will try and let you know.
Comment: That will definitely work if you will face any problem then let me know :)
Answer: As an option you can use path alias, for example If my user's page alias is /users/myusername
then you can set users/* in Visibility settings. So it will be available on user/* page, but not on user/*/* pages.


Do @PostMapping and stay on page without redirect

Question: I use Spring Boot.
There is a page where all ads are displayed. I need to add ads to favorites. This must be done without navigating to other pages or reloading the current page. So user can click on the button and scroll further, inside it has added to favorites. How can this be done without redirect?
I tried different variants and it doesn't work. Help me please!(
I know that I have to use js, but it doesn't work for me. Also I need to change the method addToFavorites. Can you change my code and show it clearly?
My HTML:

Headline

Description

 New York

12.07.2020 19:08

          <form  th:action="@{/favorites}" method="post">
            <input type="hidden" name="ad" th:value="${ad}">
            <button type="submit">Add to favorites</button>
          </form>

My Java:
    @GetMapping("/advert")
    public String mainPage(@PageableDefault(sort = {"id"}, size = 10, direction = Sort.Direction.DESC) Pageable pageable,
                           Model model) {
        Page<Advert> page = advertDAO.findAll(pageable);
        model.addAttribute("page", page);
        model.addAttribute("dao", advertDAO);
        return "main";
    }

    @PostMapping("/favorites")
    public void addToFavorites(@RequestParam("ad") Advert advert){
        // add to favorites
    }

Comment: You will need to send async(Ajax) requests. See this https://stackoverflow.com/a/11855073/607637. You will need jquery for this. Which you can install using webjars. See https://github.com/gtiwari333/spring-boot-web-application-seed/blob/master/main-app/src/main/resources/templates/_fragments/header.html for how to use webjar
Comment: @gtiwari333 jQuery is fading, especially with the introduction of [the Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
Comment: @chrylis-cautiouslyoptimistic- yeah.. it would be great if we can do it with vanilla js. been using jquery for about 12 years. i think its still great :)
Comment: @gtiwari333 And what should I change in the method `addToFavorites()`?
Comment: `I know that I have to use js, but it doesn't work for me` what do you mean by that? Have you already tried using JS? If so, can you share what you tried?
Comment: https://stackoverflow.com/questions/64067251/ajax-in-thymeleaf-springmvc/64069308#64069308 See this answer for an example of ajax call with vanilla JS. You should probably do pretty much similar to that except your ajax call will be POST
Answer: To do POST call without redirecting, You can use ajax call on button click that will call your controller and give response also..
$.ajax({
type: "POST", // It can be GET also
url: "your_ulr",
success: function(response){
    //if request if made successfully then the response represent the data
    // Do here whatever you want
   }
});


Can a forward pass be thrown after a handoff made in front of the quarterback?

Question: The quarterback hands the ball to a receiver; the handoff is in front of the quarterback but behind the line of scrimmage, which is a legal play.
Can the receiver now throw a forward pass?
Answer: Yes.
Like already explained in my other answer, the Hand-Off is not a pass, so yes... a pass may still be thrown as long as the passing rules are met (only one forward pass per play, ball didn't cross the line before, etc).

Handing the ball is transferring player possession from one teammate
  to another without passing or kicking it. (Rules Section 15)

There is no statement in the rules of (in)eligible pass throwers, so anyone may do so.
Also Julian Edelman (Wide Receiver) threw a TD pass in 2015: Ravens vs Patriots
Answer: No, it'd be illegal.  If the hand off is forward, it counts as a forward pass. If the receiver of that forward hand off then throws a forward pass it'd be considered the second forward pass of the play and thus be illegal.
Comment: As with the other (contradictory) answer, could you quote the specific points from the rulebook you are basing this on?
Comment: The other answer quotes and refers to a rule which states that a handoff is a transfer between players which **is not** a pass or kick. Your answer is factually wrong.
Comment: A forward handoff has its own rules, but is still not considered a pass.


How can I prevent loss of tuning when changing strings set from 0.11 to 0.12?

Question: I have an Epiphone Les Paul Custom and it's tuned in standard C and my playing style is mostly Desert Rock. I'm using a set of 0.12 strings and considering changing to a 0.11 set to have less tension on the strings and for the strings to be easier to bend. However there seems to be a small loss of tuning when using 0.11 strings.
Are there any guitar settings or anything else I could be doing to prevent the minor loss of tuning?
Answer: You should take your guitar to a professional guitar luthier or repairman and pay them for a setup.
Because you have changed from one gauge of strings to another, in order for your guitar to play in tune and for the strings to be the same height from the frets and fingerboard (what we call the "action"), your guitar truss rod will have to be adjusted to slightly change the amount of bend or "relief" in the neck.
Also, assuming we are talking about an electric guitar, the position of each of the six bridge saddles will have to be adjusted to recalibrate the speaking length of each string, using the appropriate screwdriver or wrench in conjunction with an electronic tuner.
If the electric guitar has a tremolo system, the spring tension on the back of the mechanism may need to be similarly adjusted to enable the bridge to sit in the proper position.
In some cases the nut may have to be replaced or the six string slots in the nut may have to be deepened or widened with special files.
Do not worry; all this is normal. Guitars are designed to be adjustable so that a professional can calibrate the guitar to accommodate whatever gauge of strings you prefer to play. But every time you decide to go with a different gauge, a setup may be necessary.
Comment: How can one avoid a "chicken and egg" problem when trying to select what kinds of strings one will want to use?  On my acoustic guitar with my 'special' tuning, the fifth string (which in my tuning is the largest) sits up a bit high and plays a bit louder than the sixth string, but I'd like the sixth string to be about as loud as the fifth.  Using a smaller gauge fifth string would likely make it less loud, but calibration probably will to.  I don't want to make it too soft.  Should I guess at having the guitar calibrated using a smaller gauge on the theory that...
Comment: ...if that makes the fifth string too quiet it will be easier for a luthier to expand the grooves to accommodate a larger string, than contract them to fit a smaller one?
Comment: Obviously you'll have to do some experimenting with gauges. As for the nut, nut slots can be filed to make them deeper or wider, but there is no way to make them smaller. In that case you'd need to purchase a new nut, one with slots already cut in it, or a blank nut, and have the technician file new slots. Nuts are not very expensive. Here is a link to a catalog. http://goo.gl/mq4AK


Serve PHP page mapped as part of Django's (Python's) virtualhost

Question: I have a question similar to this: Apache : Map one virtualhost to a subdirectory of another virtualhost
Except mine is about serving PHP within Django's domain like that:

example.com serves Django, uses WSGI etc.,
example.com/some_app needs to be fully based on PHP, cannot go through Django,

How can I do that? I believe this is possible, but could you give me any clues about how to accomplish that?
Answer: The Alias directory takes precdence over WSGIScriptAlias, so define Alias directive for /some_app to directory which is setup with PHP files.


How do I use the Cufón module to change the title of a view?

Question: I bought a new theme and I am not getting much support from the place I bought it from. My theme has nice fancy titles in blocks, which are implemented using the Cufón module to change the text. I was wondering if it was possible to do the same with the title of my views.
I have tried overriding the views-view-table-tpl and added
 around the title, but it didn't have any effect.
How can I achieve this?
Answer: Edit the page.tpl.php template, and add the cufon class to the page title (
). Alternatively add a h1.title rule to the Cufón module.
If you dont't use the Cufón module, add this to your template.php.
drupal_add_js('Cufon.replace('h1.title');', 'inline');

Comment: thanks ipwa but that isnt doing it for me. I'll have to keep digging thanks.
Comment: Hi Reg Gordon, I just saw that in line 1165 of your Drupal aggregated file that cufon is being called on all elments with the cufon font. Cufon.replace('.cufon'); That means that if you get the cufon class to your page titles, then your title will get the font replaced to Futura Md BT, which is the cufon font you're using. If you add the class to your page.tpl.php and then clear your cache, I am sure you will get the desired effect unless there is another template intercepting the page.tpl.php
Comment: Updated my answer to have an alternative solution, remember to clear cache when modifying templates.


Email changes in hudson

Question: I am looking for a way in hudson to email the changes from a project, only if there are changes. I see how to email changes when a build is successful but I only want to send the email if the build is successful and there were changes.
Answer: Maybe (not tested) the Jenkins Email-ext plugin can help you:

This plugin extends Hudson's built in email notification functionality by giving you more control.  It provides customization of 3 areas.

Triggers - Select the conditions that should cause an email notification to be sent.
Content - Specify the content of each triggered email's subject and body.
Recipients - Specify who should receive a email when it is triggered.

You might need to rebuild that plugin to add your specific trigger condition, like in this example.

Email changes in hudson


Algebraic aspect of (Riemann) surface

Question: Let $X$ be a Riemann surface of genus $1$ and let $x \in X$. Set $P = x^3$ considered as a divisor on $X$. Then let $$V_j = \{f: M \rightarrow \mathbb{C} \cup \{\infty\} : f \text{ is a meromorphic function on } X \text{ with } \operatorname{ord}_x(f) \geq -j\}$$ for $j = 2, 3, 6$ and $\operatorname{ord}_x(f) \geq -j$ means the order of poles of $f$ at $x$ is never greater than $j$.
This $V_j$ is a $\mathbb{C}-$vector space, and by the Riemann–Roch theorem $$\dim_\mathbb{C}(V_j) = j$$ for $j = 2, 3, 6.$
In fact, $V_j \cong \mathbb{C}^j$ as vector spaces which gives that $V_2$ is a proper subspace of $V_3.$ In fact, $V2, V3 \leq V_6$. So the we can extend a basis $\{1, a\}$ of the isomorphic copy of $V_2$ to a basis of isomorphic copy of $V_3$ in the form $\{1, a, b\}$.
Here $a$ is a non-constant meromorphic function in $V_2$ and $b$ is a non-constant meromorphic function in $V_3$ such that $b \notin \operatorname{span}_\mathbb{C}(1, a)$.
By this construction, I would like to verify that $a ,b$ considered as elements of $V_6$ will satisfy a polyomial with coefficient in $\mathbb{C}.$ Then this should give me a way to think (or embed) $X$ in to a projective space $\mathbb{CP}^2.$
Can anyone help of how the polynomial part and embed part can be done ?
Comment: If you write \mbox{dim} or \text{dim} instead of \dim, then when you type 3\mobx{dim}(A) you will see $3\mbox{dim}(A)$ instead of $3\dim(A),$ and with \mbox{dim}A you see $\mbox{dim}A$ instead of $\dim A.$ The space to the left and right of $\dim$, coded as \dim, depends on the context, and that doesn't happen with \mbod{dim}. Similarly with \mbox{span} instead of the standard usage, \operatorname{span}. In actualy LaTeX, as opposed to MathJax, you can write \newcommand{\span}{\operatorname{span}} BEFORE the \begin{document} and then just type \span in the body of the text.
Comment: . . . . and if you're doing this kind of math, then definitely it's worth knowing things like this.
Answer:
Find $C$ such that $b^2-Ca^3$ has a pole of order $5$ at $x$,
find $C_2$ such that $b^2-Ca^3-C_2 ab$ has a pole of order $4$,
find $C_3$ such that $b^2-Ca^3-C_2 ab-C_3 a^2$ has a pole of order $3$,
find $C_4$ such that $b^2-Ca^3-C_2 ab-C_3 a^2-C_4 b$ has a pole of order $2$,
find $C_5$ such that $b^2-Ca^3-C_2 ab-C_3 a^2-C_4 b-C_5a$ has a pole of order $1$

No rational function has only one pole thus it is constant $$b^2-Ca^3-C_2 ab-C_3 a^2-C_4 b-C_5a-C_6=0$$

Then $z\to [a(z):b(z):1]$ is a rational map and a morphism $X\to \Bbb{P}^2$.
It is injective because $a-a(z_0),b-b(z_0)$ have respectively 2 and 3 poles thus the same number of zeros. If $z_1\ne z_0,a(z_1)=a(z_0),b(z_1)=b(z_0)$ then $(b-b(z_0))/(a-a(z_0))$ has no pole thus it is constant which is a contradiction. $z\to [a(z):b(z):1]$ is an embedding because for the same reason $a-a(z_0),b-b(z_0)$ never have a common double zero at $z_0$.
Comment: All your "C" are complex numbers ? I do not know the exact form of $a, b$. How to find such $C$ in each step ? It is from some existence theorem ? Or do I miss some concepts ? It is great if you can collaborate a little more.

Algebraic aspect of (Riemann) surface


How do I use 2 different taxonomy view modes on one node page?

Question: On a node page I have a term reference field. This term contains 3 fields
For the term I've created a few view modes:

view_mode_first contains: field_1
view_mode_second contains: field_2, field_3

hook theme suggestions:
  function theme_theme_suggestions_taxonomy_term_alter(array &$suggestions, array $variables) {
    $term = $variables['elements']['#taxonomy_term'];
    array_splice($suggestions, 2, 0, 'taxonomy_term__' . $term->bundle() . '__' . $variables['elements']['#view_mode']);
  }

node field template, where I'm displaying referenced terms:
  {% for item in items %}
      {% set first = item.content|merge({'#view_mode': 'view_mode_first'}) %}
      {{ first }}
  {% endfor %}

  {% for item in items %}
      {% set second = item.content|merge({'#view_mode': 'view_mode_second'}) %}
      {{ second }}
  {% endfor %}

But as a result I'm getting the same templates everywhere: taxonomy-term--name--view-mode-first.html.twig and not a taxonomy-term--name--view-mode-second.html.twig
I found that if I disable render cache in a settings.local file, both templates work:
$settings['cache']['bins']['render'] = 'cache.backend.null';

Is there possibility to disable render cache for specific node and/or fields?
Answer: The problem is that the view mode is also part of the cache keys and you would need to update them as well to avoid that both view modes are cached under the same cache id.

Is there possibility to disable render cache for specific node and/or
  fields?

Yes, this is another possibility, you can disable caching of specific entities, in this case taxonomy terms, by removing the cache keys, which are in the #cache property. It's easier to manipulate this array in PHP, but this should also be possible in Twig. You can try to get #cache with the filter |without('keys') and merge it later with first and second.
You can also try to remove #cache completely from the second rendering
{{ second|without('#cache') }}

because all relevant cache metadata should bubble up already from the first rendering of the taxonomy term.
Comment: Wow! `without('#cache')` did the trick. Thanks a lot for your help and explanation!


Issue while running a java application in Linux env

Question: I have a java project built in eclipse in my Windows machine. Now i had to run it in Linux machine. I created a jar , and i am trying to run the jar.
The main class, takes a XML file as input. Previously on Windows, i had given path of the file in Windows. Now i kept the .xml file in the root location in Unix.
can i modify the code in Windows, to the root path of Linux machine and try to run the jar.
I did it like this ,
XYZ parsero = new XYZ("//root//workflow.xml");

Created the jar and tried to run in Unix.
I got the below exception.
java.net.UnknownHostException: root

How do i need to run this.
Comment: I got the solution.

It should be

    XYZ parsero = new XYZ("/root/workflow.xml");

unlike in Windows.
Comment: as you found the solution, post it as an answer and mark as accepted
Comment: The reason why you use ``\\`` on Windows is because ``\`` is the escape character in strings. You can write `\t` to mean tab, `\n` to mean line feed, and ``\\`` to get a literal backslash. `/` is not an escape character and already literal, so you don't write two any more than you write `"hheelloo  wwoorrlldd"`.
Comment: @ fmodos I did not have the permission to do that till 8hrs. So i commented. I will put it. Thanks for pointing.
Answer: I got the solution. It should be XYZ parsero = new XYZ("/root/workflow.xml"); unlike in Windows


Montar Query com JOINS

Question: Tenho um query executada no DB2:
SELECT f.*
       FROM Fat f
            INNER EFat ef
                  ON f.id = ef.id AND f.seq = ef.seq

Como faço a reversa dela no Java? Tentei dessa forma, mas dá erro, todas as minhas classes estão com os seus devidos relacionamentos:
StringBuilder sb = new StringBuilder();
sb.append("SELECT f FROM ")
.append(getClasseGenerica().getSimpleName() + " f ")
.append(" INNER JOIN f.eFaturas ef ")

Minha dúvida é para fazer, isso:
ON f.id = ef.id AND f.seq = ef.seq

Com isso no JAVA:
.append(" AND f.id = ef.id AND f.seq = ef.seq ")
 Query query = getEntityManager().createQuery(sb.toString());

Quando coloco AND ou WHERE sempre dá erro na execução da query.
Comment: Na pergunta tem um `AND` no lugar do `ON`
Comment: Não entendi o que informou.
Answer: No JPQL só é possível fazer o inner join da forma que você está tentando quando as classe são relacionadas (Ex. Detro de Fat tem um Atributo do tipo Efat).
Como alternativa você pode fazer a querie da seguinte forma.
SELECT f
FROM Fat f,  EFat ef
WHERE f.id = ef.id
    AND f.seq = ef.seq

https://docs.jboss.org/hibernate/orm/3.3/reference/pt-BR/html/queryhql.html#queryhql-joins
Ou você pode fazer conforme abaixo:
SELECT f.*
FROM Fat f
    in(f.eFaturas) ef
WHERE  f.seq = ef.seq

Comment: Marciano,no meu caso todas as classes estão relacionadas. Como poderia fazer da maneira que estou tentando?
Comment: Coloquei mais um exemplo de como fazer dessa forma, verifique por favor.
Comment: Tentei usando essa forma, mas continua dando erro na criação da query.
Comment: Caused by:  org.apache.openjpa.persistence.ArgumentException: Encontrado "ef" no caractere 306, mas esperado: ["*", "+", "-", "/", "AND", "GROUP", "HAVING", "OR", "ORDER", ].
Comment: Você consegue exibir a querie que o seu sistema esta criando ? Se possível exiba também suas entidade que facilitará encontrar o problema.
Comment: Conseguir resolver o problema, como já está tudo relacionado essa parte .append(" AND f.id = ef.id AND f.seq = ef.seq ") que estava querendo fazer não precisa, porque pelo o mapeamento já faz isso, então basta somente passar o os dados finais que desejava igual informou e funcionou. Valeu

Montar Query com JOINS


Is there a word for when you scoop to the same note?

Question: I'm a vocalist who's done different kinds of ensembles over the years, and I often have this instinct to scoop to (rearticulate? emphasize?) a repeated note if the other voices change to make a different chord. Here's a basic example:

Is there a word for this? Maybe it's a bad habit that doesn't have a name because it's a bad practice? My voice teacher suggested that he'd notate this with a tenuto, but Wikipedia's description for tenuto doesn't seem relevant to what I'm doing?
Comment: The "typesetting magic" is probably jTab or ABCjs, as documented [here](https://music.meta.stackexchange.com/questions/2782/documentation-for-abcjs). It's kind of more trouble than it's worth, and very buggy. Screenshots are maybe better IMO.
Comment: I see that on some other questions there's some music typesetting magic. I couldn't immediately find a guide for that notation so I included a screenshot instead (sorry!) If someone wants to swap this screenshot out for some fancy-schmancy music code, be my guest! or point me toward a tool/guide I can use to generate my own
Comment: If you are doing it on purpose, know what it sounds like to others and want that effect, then it is not a bad practice for you. But it is not clear to me exactly what it is you are doing: are you sliding from a C to a G?
Comment: @PJTraill Nope, I'm using a scoop to rearticuate the same note (G->G in the example) -- I hope that made sense, I'm not really sure how else to describe it short of uploading an audio file or something
Answer: Simple question, simple answer.
It is called a scoop. Adele, John Legend use the technique. I used to wonder if it was because they couldn't hit the note directly. Still do...
Comment: @Alan - But we *do* restart the note off-pitch and then adjust up to land on the correct pitch in the question's example...
Comment: I think I disagree here. Scooping refers to starting a note off pitch and then adjusting up/down to land on the correct pitch. Whereas this question refers to when you're already singing the correct note, and wish to re-articulate it. There are several ways to re-articulate without scooping (adding a glottal attack for example). I think @jacob was just using scooping as one example of how to do this.
Comment: in fact, Musescore has an articulation for this, and they call it a scoop, so if you wanted any reference for people understanding the terminology you could certainly go find some. +1
Answer: The technical term for what people are calling "scooping" is glissando. You are sliding up or down from one note to another in a continuous (legato) manner. Most vocal terms are Italian since we Italians created the disciplined art of teaching voice called Bel Canto, (meaning beautiful voice), with masters of the art like Manuel Garcia.
Comment: I think that glissando is a wider term and scooping refers to this very specific case.


How can I prevent images from overlapping when the window is scaled up?

Question: When I make the window larger, the images scale with it and eventually overlap each other.
What I want it to be:
https://i.stack.imgur.com/MUIhH.png
What happens when I scale window:
https://i.stack.imgur.com/c1aCn.png
Html:

    <link rel="stylesheet" type="text/css" href="styleE.css">

Css:
#triggerButton {
    position: absolute;
    right: 0;
    left: 0;
    margin: auto;

}

#primaryButton {
    position: absolute;
    right: 0;
    left: 0;
    margin: auto;

}

.spinner{

    transform-origin:top left;
    position: absolute;
    right: 0;
    left: 12%;
    width: auto;
    max-width:11%;
    margin: auto;
}

Thank you!
Comment: can you create the jsfiddle or provide the URL
Answer: Position: absolute pulls the elements out of the DOM rendering rules. The CSS as written tells the browser to always place these elements at X position no matter what size of the element or screen. A List Apart has an excellent article for getting a good grounding in how positining works: http://alistapart.com/article/css-positioning-101
Remove the positioning and instead use either the "display:" or "float:" properties. Things will begin to flow according to the DOM rendering rules.
In addition, make sure applied CSS classes have functional or semantic naming. Avoid using classes that make reference to design treatment since things like colors/big/small can and do change over time., ie, "whitebackground". The code is much better served using something like the "client-name" or .theme and then declaring the background color for that class or on the BODY tag.
https://stackoverflow.com/a/19385846/4064180
Comment: Thanks, you helped a ton! Changing the "position:absolute;" to "display:block;" solved the scaling problem but it created another. I was using the "position:absolute" on the ".spinner" class to stack images on top of each other. If I lose the "position:absolute" the image stops scaling like I wanted it to but they stop stacking. Thanks again!
Comment: @AnthoneyKalasho wrap the spinner in a `div`, give the `div` `display:block` and then the elements inside the spinner `position:absolute`
Comment: @starvator I did that but it didn't change anything
Comment: @AnthoneyKalasho give the `div` a `height`
Answer: Instead of using percentages for the width of your buttons and spinner, give it a fixed width such as 300px.
Also, you should consider removing the position: absolute as it serves you no purpose. Instead, remove it completely and add display: block;


Null deviance in glm R

Question: This is a question about the difference in calculating the null deviance in a simple Poisson model with and without an intercept.
If
y = c(2,3,6,7,8,9,10,12,15)
x = c(-1, -1, 0, 0, 0, 0, 1, 1, 1)

glm(y~x, family = poisson)

# Call:  glm(formula = y ~ x, family = poisson)
#
# Coefficients:
# (Intercept)            x
#      1.8893       0.6698
#
# Degrees of Freedom: 8 Total (i.e. Null);  7 Residual
# Null Deviance:      18.42
# Residual Deviance: 2.939        AIC: 41.05

The null deviance can be calculated as follows:
lf = sum(y * log(y) - y - log(factorial(y)))
ln = sum(y * log(mean(y)) - mean(y) - log(factorial(y)))

2*(lf - ln)

# [1] 18.42061

If I fit the model without intercept:
glm(y~x - 1, family = poisson)

# Call:  glm(formula = y ~ x - 1, family = poisson)
#
# Coefficients:
#     x
# 2.373
#
# Degrees of Freedom: 9 Total (i.e. Null);  8 Residual
# Null Deviance:      191.9
# Residual Deviance: 94.74        AIC: 130.9

The null deviance is now 191.9.
Can someone tell me how to calculate the null deviance for this model - I was under the impression that it would be the same as for the intercept model, i.e. a single parameter equal to the mean, but obviously it is not.
I presume I've incorrectly assumed that the null model is the same in both cases. Is it not or am I making a stupid mistake? I'd actually never considered this case before in any detail and there is obviously a gap in my knowledge somewhere.
I can get the null deviance as follows:
glm(y~1-1, family=poisson)

# Call:  glm(formula = y ~ 1 - 1, family = poisson)
#
# No coefficients
#
# Degrees of Freedom: 9 Total (i.e. Null);  9 Residual
# Null Deviance:      191.9
# Residual Deviance: 191.9        AIC: 226

but I don't know what this model is.
Apologies if this has been answered before but the only similar question I have seen (Why does the null deviance in glm.nb differ between models of the same response variable?) does not give an explicit explanation.
Comment: It looks to me like the null model considered in the last case is a Poisson distribution with mean 0.
Comment: @jbaums, wouldn't it be mean 1 (ie, `log(1) = 0`)?
Comment: @jbaums Perhaps you could write that as a brief answer?
Comment: @gung - yes that makes sense.
Answer: Thanks to @jbaums.
y = c(2,3,6,7,8,9,10,12,15)
x = c(-1, -1, 0, 0, 0, 0, 1, 1, 1)

For the no intercept null model we have:
$$
Y \sim {\rm Poisson}(1)
$$
leading to the following null model likelihood term:
$$
\mathcal L(y) = \exp(-1)/y!
$$
or loglikelihood term:
$$
l(y) = -1 - \log(y!)
$$
The log-likehood for the null model is then the sum of these terms:
lnull = sum(-1 - log(factorial(y)))

As usual the log-likelhood for the saturated model is:
lf = sum(y * log(y) - y - log(factorial(y)))

so the null deviance is:
2*(lf - lnull)
# [1] 191.8602

Comment: No, you had the basic idea right, @jbaums, it was just a detail.

Null deviance in glm R


Help/Question about Microphone / Phantom power and audio interface

Question: Just a quick short question,
I have a USB audio interface (emu0202) which plugs into my pc but of course, the interface (emu0202) isn't 'Phantom Power' capable,
So I wanted to know if it's possible to plug a separate wall powered phantom power brick into a USB audio interface
So it'll go like: MIC > Wall Powered Phantom Power Brick > USB PC Powered Audio Interface > PC
MIC > Wall Powered Phantom Power Brick (via XLR cbl) > USB PC Powered Audio Interface (via XLR cable) > PC (via USB)
Answer:
MIC > Wall Powered Phantom Power Brick (via XLR cbl) > USB PC Powered Audio Interface (via XLR cable) > PC (via USB)

Given that the Emu 0202 seems to have an XLR input, it sounds like that should work.
The Emu 0202 is a very old interface - is it already running happily on your PC with no driver support issues? If not, it might be worth considering investing in a new USB interface or USB mixer with phantom power instead.
Comment: Yes, this is the correct way. Of course, it might actually be cheaper to just buy a new interface that also has phantom power instead of buying merely a phantom power injector.
Answer: You could. Just search 'phantom power adapter'.  I see there are some quite cheap ones available.   (Make sure you're getting one designed to provide 48v to studio microphones with full-size XLR connecters.  There are other types of 'phantom power'.)
Your Emu 0202 is now classed as end-of-life.  Modern USB-powered audio interfaces have phantom power built in. For a neater solution you might consider upgrading to something like the Focusrite Scarlett 2i2.


drop mediator in fault sequence is mandatory in wso2 esb 4.9.0

Question: We removed the drop mediator in default fault sequence and added payload factory to construct business specific message response. We noticed all ESB servers are going down when there are time outs from back end services. We tried to control servers going down with manipulating time outs on each back end services but no luck. We were thinking is there any issue in removing drop mediator from fault sequence
Answer: To send the response to the client, add <respond/> mediator after the payload factory mediator.
Answer: When you construct the business-specific message response, if you need to send it back to the client you will have to use a respond mediator. Drop mediator will stop processing and send back a 202 Accepted to the client.


Problem with HttpOnly Cookies

Question:  I have a problem with creating HttpOnly Cookies , I use the following code to creat new cookie:
    //A.aspx
    HttpCookie ht = new HttpCookie("www");
    ht.Value = "www";
    ht.Name = "www";
    ht.HttpOnly = true;
    ht.Expires = DateTime.Now.AddDays(1);
    Response.AppendCookie(ht);
    Response.Redirect("B.aspx");

    //B.aspx
    HttpCookie cookie = Request.Cookies["Allowed"];
    HttpCookie htt = Request.Cookies["www"];
    if (cookie != null)
    {
        Response.Write(cookie.HttpOnly);
        Response.Write(htt.HttpOnly);
    }
    else
    {
        cookie = new HttpCookie("Allowed");
        cookie.HttpOnly = true;
        cookie.Value = "ping";
        cookie.Expires = DateTime.Now.AddMinutes(2);
        Response.Cookies.Add(cookie);
        Response.Write(cookie.HttpOnly);
        Response.Write(htt.HttpOnly);

    }

The problem is that the final result is always : False, although the HttpOnly property is set to True .
Can anyone explain me a way to figure this out ?
Thanx
Answer: Cookie parameters (expiration date, path, HttpOnly etc) are not sent back to the server by the browser, only the values. Sending them back would only introduce unnecessary bloat. Therefore the cookies in Request.Cookies will only contain the names and values.
If you want to see if your HttpOnly value is taking effect, use Firecookie or something similar to inspect the cookies. Or try accessing them in JavaScript - that's what it's supposed to prevent.
Comment: @Israa: Why do you need to distinguish between HttpOnly and not HttpOnly on the server side? It doesn't make any sense. If you really need to do so, keep a list of cookie names that are HttpOnly on the server and use that to find out which cookie is which.
Comment: @Israa: You do realize that if I have full control over the HTTP client (which I, as the user, do) I can send your server any made up cookies I wish, right? Even if there was a flag that tells your server it's "HttpOnly", I could just set that as well. You need to come up with another way of securing your data.
Comment: @Matti Virkkunen, But if I need to distinguish between httpOnly and regular cookies in my page what I should do ? And how can I access httpOnly cookies in javascript since it is httpOnly ?!
Comment: @Matti Virkkunen : I need to do so because I will save a value in cookie and check if this cookie exist, if so the page will retern some data, therefore I need to know if it is HttpOnly because anyone could make a cookie with the same name and get the data returned.
Comment: Thanks , well I guess there is no way to secure my data then :D
Comment: @Israa: Oh, I'm sure there is. At least to some extent. Maybe you should ask a new question about a better way to secure your data, with more details about your situation.
Comment: You could encrypt data with a machine key - then users will have really tough time to send their own data in your cookie.

Problem with HttpOnly Cookies


Highlighting primary link for specific content types

Question: If I have a navigation item called 'News' in my primary links, how would I go about highlighting it for all news content type nodes?
Thanks!
Answer: For Drupal 6 you have the choice of using the Menu Trails module, or the Menu Position module, which is available for both 6 and 7.
Both modules let you define criteria for where nodes should appear in the menu structure (eg, based on node type, and taxonomy).


Passing an array of object from custom module to template in drupal 8

Question: Follow this about passing an array to template. But my array is array of object so I'm getting some errors on the page, this is the one of them:

User error: "0" is an invalid render array key in
  Drupal\Core\Render\Element::children() (line 97 of
  core/lib/Drupal/Core/Render/Element.php)

This is my code :
Controller
  public function content() {
      return array(
        '#theme' => 'my_page',
        '#text' => "Lorem Ipsum",
        '#myvariable' => array('key' => $myArrayofObjects),
      );
  }

mymodule.module
function my_page($existing, $type, $theme, $path) {
  return array(
    'my_page' => array(
        'variables' => array(
            'text' => NULL,
            'myvariable' => array(),
        ),
    ),
  );
}

my-page.html.twig

Test twig template!

{{text}}

{% for key, value in myvariable %}
  Key : {{ key }}
  Value : {{ value }}
{% endfor %}

This is the array :
Array
    (
        [0] => stdClass Object
            (
                [name] => User1
                [user_id] => 1
                [email] => firstname.lastname@example.com
            )

        [1] => stdClass Object
            (
                [name] => User2
                [user_id] => 2
                [email] => email@example.com
            )

        [2] => stdClass Object
            (
                [name] => User3
                [user_id] => 3
                [email] => firstname.lastname@example.com
            )
     )

How the best way to pass an array of object from module to template and render or loop it using twig engine?
Answer: In your controller why you are using like this
'#myvariable' => array('key' => $myArrayofObjects),

Change it as
'#myvariable' => $myArrayofObjects,

and in my-page.html.twig

Test twig template!

{{text}}

{% for key, value in myvariable %}
  Key : {{ key }}
  Name : {{ value.name }}
  User ID : {{ value.user_id }}
  Email : {{ value.email }}
{% endfor %}

Comment: Thank's @AAjay Reddy, finally it works.

If you are willing, can you give an explain why `#myvariable => array('key' => $myArrayofObjects),` changed to `#myvariable => $myArrayofObjects` ? For my knowladge. Thanks
Comment: @UgyAstro - You don't need `'key'` because when you do the `for` loop in the Twig, it will automatically associate the index with `key` and each element in the array with `value`.

In your example, the `key` index variable will be the `'key'` string and the `value` will be the actual array of objects.
Comment: @edwardchiapet given correct explanation, thanks edwardchiapet


How to display content from a second database

Question: I have two separate mysql databases setup:
1) With all the Drupal 7 related tables etc etc
2) A custom database into which I will feed simple high score data from an external source eg. username, score, time etc
Is there currently a module which will turn my second database into something an end user can view/sort in a Drupal Page or content type? Obviously there is little point in collecting user high scores data is the users can't see it. I have come across only the Data module, but it is unclear to me as to if this does exactly I would need it too. For example there doesn't seem to be an options to change the tables appearance or style, something which the D6 only module Table Wizard did do. Has anyone used this module before, and if so has it been for a purpose similar to mine?
Comment: _"I have come across only the Data module, but it is unclear to me as to if this does exactly I would need it too"_...have you at least tried to install it and see?
Comment: I believe the data module can be used to expose the data you have to Views.
Answer: Maybe consider the Forena module for accessing your data in your custom database. It seems like a perfect fit for what you're asking for. It also includes charting features, which is typically a related requirement. Not many people know about it, which is why I wanted to mention it here.
Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
Various DBMSs are supported, such as Oracle, MS Sql, Postgress, SQLite, MySQL, any PDO compliant DBMS. You didn't specify if your custom database is any of those, but any of these will do ... And there are quite some reasons for considering Forena.
Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links.
Note: I'm a co-maintainer of Forena.


No tests found with test runner 'JUnit 4'

Question: Ao criar um novo pacote e dentro desse pacote  criar um novo teste ao tentar rodar o teste o eclipse retorna a  mensagem: "No tests found with test runner 'JUnit 4'"
Dentro do projeto eu tenho outro pacote com outros testes que rodam normalmente.
Alguém sabe me dizer o que fazer?
Answer: Veja se existe pelo menos um método anotado com @Test na sua classe de teste.
Exemplo:
<code>@Test
public void testFoo() {...}
</code>
Comment: O @Test só é suportado a partir da versão 4 do JUnit, então se for uma versão anterior não vai haver a anotação no método. É bom ver também se o projeto tem o JUnit 4 configurado nas dependências, já que ele está sendo executado com essa versão.


Finding most similar observations in two data sets

Question: I have the following question.
Given are two data sets A and B with around 10,000 observations described by different variables categorical and numeric. The task is to find these observations in B which are most similar to the observations in A. What approach would you suggest?
My first idea was to build a logistic regression model. Coding all observations with 1 in data set A and all observations with 0 in data set B. The outcome of this approach would be a score. My hypothesis is that the zeros with the highest score are most similar to A. What do you think of this relatively simple approach?
Cheers
Comment: What about a knn classifier? See for instance http://archive2.cra.org/Activities/craw_archive/dmp/awards/2003/Mower/KNN.html
Comment: I' ve read that knn has problems when you work with categorical and numeric variables at the same time?
Comment: Maybe you can find some relevant info here: http://stackoverflow.com/questions/13625849/knn-classification-with-categorical-data
Comment: Thank you, so if I would use KNN I have to reclassify every class of every categorical variable into a new variable as a binary variable with 1 and 0?
Comment: Looks like it's a way to do it. Can't help you more on this. Maybe someone else would.
Comment: So you basically have a set of individuals and 2 sets of variables for those individuals, is that right ? If so then Multiple Factor Analysis would be great as it allows to compare the different viewpoints (your two sets of variables)
Answer: This is more of a comment than an answer, but it got too long for the comment box and hopefully it will prompt good discussion.
Your approach is basically a repurposed version of propensity score matching. The basic technique is general and sound. It's worth noting that Gary King, one of the gurus of logistic regression, objects to propensity score matching for the purposes of causal inference [1], but his objections are specific to causal inference and not to the more general end of inferring similarity.
The Python module Dedupe [2] makes use of similar techniques for matching records. This requires a notion of equality between entities in A and B, which might not be applicable to your problem. But the sources they cite in their bibliography could be interesting.
And, as mentioned in the other answer, using a Random Forest instead of a logistic regression allows you to compute a proximity matrix between points as a side effect [3], [4]. Note that this will also return similarities between points in the same data set. This opens up an interesting can of worms: if you compute the similarities among all points in both data sets, you'll naturally have similarities between points in different sets.
References

King, G. and Nielsen, R. (2016), "Why Propensity Scores Should Not Be Used for Matching." Available at http://j.mp/1FQhySn.
Eder, D. and Gregg, F. (2016), Dedupe. Available at https://github.com/datamade/dedupe.
Liaw, A. and Wiener, M. (2002), Classification and Regression by
randomForest. R News 2(3), pp. 18-22. Available at https://cran.r-project.org/web/packages/randomForest/.
https://stackoverflow.com/a/26611881/2954547
Comment: Thank you for your answer. I would like to rate your answer for your answer and for your taste of music ;). Unfortunately I' ve not enough points. But for now it's party time. See you on Monday.
Comment: @burton030 that comment is better than an upvote. CrossValidated is great, welcome


Python Pandas add time in hours with date

Question: Hi I have this piece of code. I want to add date and specific time in hours and seconds together. But it results in this error: TypeError: dtype datetime64[ns] cannot be converted to timedelta64[ns]
These are my data:
#converting dates in 'string' to 'date' data type
#It is written in this format: 18.04.2017
df['Start Date']=df['Start Date'].astype('datetime64[ns]')

#converting times in 'string' to 'date' data type
#It is written in this format: 17:30
df['Start Time']=df['Start Time'].astype('datetime64[ns]')

What I am trying to do:
df['Start'] = df['Start Date'] + df['Start Time']

this results in this error: TypeError: dtype datetime64[ns] cannot be converted to timedelta64[ns]
#my expected result is this:
18.04.2017 17:30

Answer: Use:
df['Start'] = pd.to_datetime(df['Start Date'] + ' ' + df['Start Time'])


Populating table with select dropdown (from database)

Question: As shown in the code below, I have a dropdown list, populated from table "tabela". Below it I have a table which I need it to be populated depending on the option select from the dropdown?
How can I do this?

    <?php
        $pdo = new PDO('mysql:host=localhost;dbname=dbname; charset=utf8', 'user', 'pass');
        $sql = "SELECT id, pref, nome FROM tabela GROUP BY pref,nome ORDER BY nome";
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $users = $stmt->fetchAll();
    ?>
    <select>
        <?php foreach($users as $user): ?>
            <option value="<?= $user['id']; ?>"><?= $user['pref']; ?> - <?= $user['nome']; ?></option>
        <?php endforeach; ?>
    </select>

                tipo1

                Tipo1
                Modelo
                Qtde
                Tipos
                Pessoas
                Vazios
                Porcent

            <?php
                foreach ($dbh->query("SELECT *, (ocupacao)*100 as ocupacao1 FROM tabela WHERE prefixo=8510") as $row) {
                    printf(
                        "

                            %s - %s
                            %s
                            %s
                            %s
                            %s
                            %s
                            %s

",
                        $row->pref, $row->nome, $row->model, $row->qtde, $row->tipos, $row->pessoas, $row->vazios, $ocupacao1 = round($row ->ocupacao1 * 100)/100 . '%');
                }
            ?>

Answer: Using the way you are gathering the data you need to echo the results into the html.
<?php foreach ($dbh->query("SELECT *, (ocupacao)*100 as ocupacao1 FROM infografico WHERE prefixo=8510") as $row) { ?>

     <?php echo $row->pref; ?>
     ...

<?php } ?>

It would most likely be better to gather the data you need in the table first and form your array as required, then loop through that array and echo into the table.
Comment: Sorry, I don't know too much about this. How exactly can I do this?
Answer: I think first of all you should change your foreach() statement into:
<?php foreach($users as $user) { ?>
  <option value="<? echo $user['id']; ?>"><? echo $user['pref']; ?> - <?echo $user['nome']; ?></option>
<?php }; ?>

I find this a bit more clean and readable :)
Then you will need to enable the page to "filter" the rows by select - this can be done either by posting the select contents each time you change the select value (so basically you create a form that will submit itself every time you change what is in select - not very modern solution) or use AJAX to send the contents and retrieve the results.
If you decide to go second option (which I would highly recommend) you should take a look at some tutorials on changing page content basing on AJAX response. I would recommend to go to jQuery for that - since you should find quite some functions there that would help you out...
Comment: that's what I don't know how to do!


Adicionar ao carrinho e quantidade no Woocommerce

Question: Tenho um site usando woocommerce, e preciso que não só na página de detalhe do produto apareça a opção de adicionar ao carrinho, e a quantidade, mas, que apareça nas listagens de produtos, nas categorias e etc.
Existe algum plugin pra isso, mesmo sendo pago?
Alguém já fez isso?
Answer: Adicione esse código no functions.php do seu tema
<code>add_action( 'init', 'erc_shop_archive_add_to_cart_button' );
function erc_shop_archive_add_to_cart_button() {
    add_action('woocommerce_after_shop_loop_item','woocommerce_template_loop_add_to_cart', 11);
}
</code>
O que essa função faz é adicionar uma ação chamada woocommerce_template_loop_add_to_cart no evento woocommerce_after_shop_loop_item quando o hook init for iniciado.


How to read from two files in the same time shell

Question: I have two files,
A

john 1 2 3 4 5 6 7
Ely 10 9 9 9 9 9 9
Maria 3 5 7 9 2 1 4
Rox 10 10 10 10 10 10 10

B
john 7.5
Ely 4.5
Maria 3,7
Rox 8.5

What i want to do is create another file with only the persons who have in file A their average greater or equal with the 8.5 and in B their mark also greater or equal to 8.5, so in my example the C file would contain only Rox because only she fulfil the criteria.
I have this
#shell program
echo "Fiserul are numele $1"
filename=$1
filename2=$2
echo "">temp.txt
touch results
compara="8.5"
cat $filename | while read -r line
do
    nota=0
    media=0
    echo " $line"
    rem=$( echo "$line"| cut -f 2- -d ' ')
    for word in $rem
    do
        echo "$word"
        nota=$(($nota+$word))
        echo "Nota=$nota"
    done
    media=$(($nota / 7))
    if [ "$(echo $media '>=' $compara | bc -l)" -eq 1 ];
    then
        nume=$( echo "$line"| cut -f 1 -d ' ')
        echo "$nume $media" >> temp.txt
    fi
    echo "Media : $media"
done
cat $filename2 | while read -r line
do

so I have in the temp.txt files the persons who fulfil the criteria for file A but my question is how can i compare them with the persons from filename2 and create "results" from them ?
I've tried with two while loops but i get an error, could someone please help ?
Thanks!
Comment: @shellter - award for the worst answer ever!  congratulations!

Q:"How do I get to Chicago by bike?"
A: "Well it would be much easier for me to drive you there because I have a really nice car and I'm also very smart, but sorry I don't have time.  Good luck!"
Comment: This would be much easier to do in awk, but I don't have time to sketch it out for you. Good luck.
Comment: Hey, thanks for the tip!
Comment: @user3133172, you'll note that the comment was posed as a **comment**, not an answer. Also, awk **is** the better tool for the OP's real question -- having support for proper floating-point math means all the hackery with `bc` would be unnecessary. Likewise all the subprocesses invoking cut and similar tools (though they aren't necessary in bash either, but are rather evidence of the OP not knowing the available native string-manipulation tools and resorting to out-of-process ones).
Answer: If you really want to read two files at the same time (which doesn't appear to be your actual question -- join is indeed the right tool for what you're doing), you can open them on different FDs:
while IFS= read -r -u 4 line1 && IFS= read -r -u 5 line2; do
  echo "Line from first file: $line1"
  echo "Line from second file: $line2"
done 4<file1 5<file2

Answer: Use the join command to combine A and B into a single file C:
$ join A.txt B.txt
john 1 2 3 4 5 6 7 7.5
Ely 10 9 9 9 9 9 9 4.5
Maria 3 5 7 9 2 1 4 3,7
Rox 10 10 10 10 10 10 10 8.5

It should be simple to modify your current script to process the data in this form.


Two whole notes on the same measure, what does it mean?

Question: I'm starting to analyze the Slavic March by Tchaikovsky. In measures 6, 8 and 9 the Clarinet has these repeated whole notes, but I don't know what they mean (I'm not a clarinetist). The bassoon/fagotto also has the same repeated whole notes in measure 8.
As far as I understand they're not the same as a "breve" since that wouldn't fit, is that correct?
Comment: Do the bars before & after have two voices?
Answer: There are two clarinets (and two bassoons) playing in unison. This notation is one way of accounting for all of the notes.
Note that for all of the stemmed notes, there are stems pointing in both directions. Stems up are for the 1st player, and stems down for the 2nd. But since a whole note has no stems, they write it like that.
It looks kinda silly, and has fallen out of favor in modern scores.
Comment: There are also two horn parts shown. According to what I have read in Behind the Bars, writing the two parts on the same stave is still fine as long as the parts are rhythmically similar. When they go on for a long time playing the same note, that would be marked as "unison", but when they split to different notes, that would be marked "divisi." The score above is a little outdated in that way because both parts are written out despite having so much unison in that section. If the parts have significantly different rhythm, they need separate staves.
Comment: Also, this score is intended to be used by the conductor. The players will have their own parts, avoiding any confusion.
Comment: Opinions will differ, but I think the cleanest thing would be to write only a single line (so also get rid of the double stems) and mark the section "a2" (for "a due", translated: "for two").
Comment: Thanks, that makes sense! How would it be written on a modern score? Just a single whole note for both voices?
Comment: @Matt How would that work in practice? It looks to me as if the two instruments in question sometimes play the same note and sometimes play different notes, and on a few occasions, one plays a note and one doesn't. If you only wrote a single line and no double stems, how would each player know when they were supposed to play which note? (I assume two different notes would still have to be written as two different notes?)
Comment: @JanusBahsJacquet In a modern score, if the parts differ significantly, then the best thing is to write two separate parts. These tricky ways of combining staffs were used before modern typesetting (and computers) to save on time, and potentially on paper/ink as well. Now though, it should be no trouble to generate a separate part for each unique line.
Answer: Looking at Fagotti, there are two voices written. It's easy to see, with up and down tails. When a semibreve is written there is no tail to determine whether it's fag 1 or fag 2, so two semibreves on the same note have to be written instead. Same ruling applies to all instruments, clarinets included.


What is the series expansion of reciprocal of theta function $\frac{1}{\theta(z;q)}$?

Question: "The" theta function is an ambiguous concept, but one definition I have found is:
$$ \theta(z;q) = (z;q)_\infty(q/z;q)_\infty = \frac{1}{(q;q)_\infty}\sum_{k \in \mathbb{Z}}z^k q^{\binom{k}{2}} \tag{$\ast$} $$
I found this recently on arXiv but maybe there is a textbook.  The second equation is known as the Jacobi triple product:
$$ (q;q)_\infty(z;q)_\infty(q/z;q)_\infty = \sum_{k \in \mathbb{Z}}z^k q^{\binom{k}{2}} $$
Therefore it might make better sense to call the theta function this result of this triple product rather than definition ($\ast$) Before I forget $(z;q)$ is an abbreviation for a factorial called the Pochammer symbol
$$ (z;q) = \prod_{i=0}^\infty (1 - z q^i)$$
My question is if there is an easy expansion for the reciprocal of the theta function. I certainly could not think of one:
$$ \frac{1}{\theta(z;q)} =  \frac{1}{(z;q)_\infty} \frac{1}{(q/z;q)_\infty} = (q;q)_\infty \frac{1}{\sum_{k \in \mathbb{Z}}z^k q^{\binom{k}{2}}} \tag{$\ast$}  = \sum \;?\,?\,?$$
Comment: There are some minus signs missing in the triple product.
Answer: Andrews in [1] (equation (2.1)) sights the partial fraction expansion
$${\prod_{n\gt0}\frac{(1-q^n)^2}{(1-zq^n)(1-z^{-1}q^{n-1})}}=\sum_{m\ge0}\left(\frac{(-1)^mq^{m(m+1)/2}}{1-z^{-1}q^m}-z\frac{(-1)^mq^{m(m+1)/2}}{1-zq^m}\right)\tag{*}$$
where $1\lt|z|\lt|q|^{-1}$ and $|q|\lt1$. Making the substitution $z{\to}z/q$, one obtains an expression for $1/\theta(z,q)$. The Laurent series expansion of the righthand side of $(*)$ is given in Lemma 1 of the paper and proved in Section 2. To wit one has,
$${\prod_{n\gt0}\frac{(1-q^n)^2}{(1-zq^n)(1-z^{-1}q^{n-1})}}=\sum_{\substack{(N,r)\in\mathbb{Z}\\r\ge|N|}}
{(-1)^{r+N}z^Nq^{(r^2-N^2)/2+(r+N)/2}}\tag{**}$$.
References
[1] HECKE
MODULAR
FORMS
AND
THE KAC-PETERSON
IDENTITIES, G.E.Andrews


Importance of predicates similar to the form $(Ex)(y)R(a_1,...,a_n,x,y)$ where $R$ is general recursive

Question: In Introduction to Metamathematics (Kleene) there are a few theorems pertaining to predicates of the the form $$(Ex)R(a_1,...a_n,x) \,\,\,\,\,\,(x)(Ey)R(a_1,...a_n,x,y)\,\,\,\,\,\,(Ex)(y)(Ez)R(a_1,...a_n,x,y,z)\,\,\,\,\,\,...$$
$$(x)R(a_1,...a_n,x) \,\,\,\,\,\,(Ex)(y)R(a_1,...a_n,x,y)\,\,\,\,\,\,(x)(Ey)(z)R(a_1,...a_n,x,y,z)\,\,\,\,\,\,...$$
where $R$ is general recursive.
e.g.

Theorem 35 ($\S72$): The satisfying predicates $P_1,...,P_s$ for F in Theorem 34 [Gödel's Completeness Theorem of pure predicate calculus] can be chosen so that $P_j(a_1,...,a_{n_j}) \equiv (Ex)(y)R_j(a_1,...,a_{n_j},x,y)\equiv (x)(Ey)S_j(a_1,...,a_{n_j},x,y)$ where $R_j$ and $S_j$ are primitive recursive ($j = 1,...,s$).

i.e. For a formula F that is irrefutable in the predicate calculus, there is a satisfying model in the domain of natural numbers such that the predicate letters $P_1,...P_s$ of this model are of the form above.
My question is: Why do we care about theorems like this? Why are number theoretic predicates of this form important?
I would understand the significance of this theorem if we could choose a model so that the predicate letters $P_1,...P_s$ were just general recursive (not $(Ex)(y)R$ where $R$ is general recursive).  This way we would could find a model where the predicates are effectively decidable.   However, predicates of the form above are not necessarily effectively decidable.
Answer: This is the arithmetic hierarchy, and the relevant notation ($\Pi^0_n, \Sigma^0_n,\Delta^0_n$) is quite snappy so I'll use it.
There is a tight connection between syntactic complexity and computational complexity. Specifically:

A set $X\subseteq\mathbb{N}$ has a $\Sigma^0_n$ definition if and only if $X$ is many-one reducible to ${\bf 0^{(n)}}$ (for $\Pi^0_n$, we get many-one reducibility to the complement of ${\bf 0^{(n)}}$).
A set $X\subseteq\mathbb{N}$ has a $\Delta^0_n$ definition (that is, $X$ has a $\Pi^0_n$ definition and $X$ also has a $\Sigma^0_n$ definition) if and only if $X$ is Turing-reducible to ${\bf 0^{(n-1)}}$.

(Here the "${\bf a^{(n)}}$" notation denotes the $n$th Turing jump of the degree ${\bf a}$ - and I'm taking ${\bf 0^{(0)}}$ to just be ${\bf 0}$, the degree of the computable sets, for simplicity.) Moreover, these facts relativize - e.g. replacing $\Sigma^0_n$ with $\Sigma^0_n$ relative to $A$ and replacing ${\bf 0^{(n)}}$ with $deg(A){\bf ^{(n)}}$. We can add more characterizations, and in particular we have Shoenfield's limit lemma and its extensions.
In particular, results of the type you mention provide computational upper bounds.


Porque o max nem o min retorna o valor esperado?

Question: Eu estou precisando pegar o maior e o menor valor de um determinado campo para poder fazer um filtro, só que o SELECT MAX nem o MIN não funciona.
Como podem ver na imagem a baixo, eu preciso dessa quantidade de usuários

Nome da tabela: prt_license
SELECT MAX(users_licensed) FROM prt_license.

Quando eu executo essa Query, ele me retorna 50
SELECT MIN(users_licensed) FROM prt_license.

Quando eu executo essa Query, ele me retorna 100
O que eu posso fazer?
Comment: Qual o tipo da coluna?
Comment: pois é, agora que to reparando, ela é um varchar... ela é gerada automaticamente pelo sistema
Comment: Está correto o resultado. 5 é maior que 1
Comment: Só que tem campos com 400 usuarios, esse seria o maior
Comment: 4 fica entre 1 e 5, ordenando por strings seria 100, 3, 400, 50, 9, etc
Answer: Basicamente é erro de tipo.

A string 50 começa com "5"
A string 100 começa com "1"

O Min e o Max agem por ordem alfabética em strings.
Para testar, mude a query para isto:
SELECT MIN(0 + users_licensed) FROM prt_license

ou isto:
SELECT MAX(0 + users_licensed) FROM prt_license

Assim você estará forçando uma interpretação numérica. Mas isto é só para testes, idealmente você deve trabalhar com a coluna do tipo correto.
Outro bom teste (apenas como aprendizado) seria você colocar as colunas com um padding de zeros à esquerda, e ver que aí por "coincidência" as strings se comportam como números no quesito de ordenação:
010
050
100
120

etc.
Para converter a coluna
Faça backup antes de alterações deste tipo. A query abaixo converte a coluna da tabela para o tipo correto, fazendo com que seu SELECT original funcione numericamente.
 ALTER TABLE prt_license MODIFY users_licensed INTEGER;

Depois da conversão, basta isto:
 SELECT MAX(users_licensed) FROM prt_license;

Comment: Não esperava por isso XD
Comment: Que solução engenhosa
Comment: Resolvido, valeu
Comment: @gabrielfalieri a solução eu postei agora no final, que é converter a tabela de fato. O SELECT foi só para testes.
Comment: Mudei pra integer... melhor mesmo
Answer: Como as colunas são varchar, a ordenação é diferente de colunas numéricas.
Você pode fazer um cast na coluna pra trazer o resultado esperado.
Note que, idealmente, isso é só pra você ver que o MIN e MAX funcionam normalmente. O certo é trabalhar corretamente com os tipos das colunas.
SELECT MIN(CAST(users_licensed AS SIGNED)) FROM prt_license

SELECT MAX(CAST(users_licensed AS SIGNED)) FROM prt_license


If $f(x)\cdot f(f(x)) = 1$ for all $x \in \mathbb{R},$ and if $f(10) = 9$ then find the value of $f(5)$

Question: If $f\colon\mathbb{R}\rightarrow \mathbb{R}$ is a continuous function satisfying $f(x)\cdot f(f(x)) = 1$ for all $x \in \mathbb{R},$ and if $f(10) = 9$ then find the value of $f(5).$
Attempt: Put $x=10,$ we have $f(10)\cdot f(f(10)) = 1.$
So, $9\cdot f(9) = 1,$ then $f(9) = \frac{1}{9}.$
Could someone help me how calculate $f(5)$ ? Thanks.
Answer: It follows from the assumption that for every $y$ in the image of $f$ we have$$f(y)=\frac{1}{y}.$$Now, as you already found out yourself, both $9$ and $1/9$ are in the image. As $f$ is assumed to be continuous, it follows that $5$ is also in the image, and so,$$f(5)=\frac{1}{5}.$$
Answer: You have calculated $f(9)=1/9$. So consider the interval $[9,10]$. Since $f$ is continuous, by intermediate value theorem, you can find $z$, which lies in $[9,10]$ such that $f(z)=5$.
Now $f(z)\cdot f(f(z))=5 \cdot f(5)=1$. Then $f(5)=1/5.$


Transformar sql em orm do django

Question: Não sei como escrever este código sql na orm do django, não encontrei nada equivalente na documentação, alguém sabe como fazer?
select coluna, split_part(split_part('string', '$', 2), '/', 1) as nova_coluna from tabela
Answer: Você deve usar o método raw() para passar queries sql puras e retornar instâncias de um model
Person.objects.raw('SELECT * FROM myapp_person')

Pode encontrar mais exemplos aqui
Answer: A solução que encontrei:
Precos.objects.filter(cod__produto=request.cod.prod).annotate(referrer_split_part=
Func(F(Func(F('recebidos'),
Value('$'), Value(2), function='split_part')),
Value('/'), Value(1), function='split_part')).values('recebidos_split_part')

Transformar sql em orm do django


try_files explained

Question: I want a simple redirect. If the REQUEST_URI is "/", i want redirect to "/blog/".
After reading some Pitfall-Docs and BestPractices, i guess try_files is for what i search. But the nginx wiki doesnt clarify to me, how it works exactly. There are two (or one) path(s) and an uri? uri seems to be the REQUEST_URI which is what iam looking for. But i dont understand, how path1 (and path2) interacts with it. What is when evaluated. Can you help me to get the point?
P.S.: nginx version 1.0(.8)
Answer:
There are two (or one) path(s) and an uri? uri seems to be the
  REQUEST_URI

No. It is the fallback URI. try_files path1 [path2] uri check if path1, path2 is exist. If it not, Nginx will redirect to the uri.
For example: try_files $uri $uri/ /index.php; is equivalent to:
if (!-e $request_filename) {
   rewrite ^ /index.php last;
}

Comment: There's one small difference between your rewrite and the try_files.  The rewrite will preserve the query string by default, and the try_files fallback will not.  You either need to add $is_args$args to the try_files /index.php or add ? to the rewrite /index.php to make them truly equivalent.
Comment: So, path1 and path2 are checked against the filesystem? and if these files not found, they assumed the last argument as uri to use??
Answer: If you want a redirect, then try_files isn't what you want.  Try this:
rewrite ^/$ /blog/ redirect;

Comment: It's better to use location = / { rewrite ^ /blog/ redirect; } or location = / { return 302 $scheme://$host/blog/; } than a server-level rewrite.  Also, saying that try_files is a list of locations is misleading, as it will only perform an internal redirect for the last argument, all the arguments before the last are literally checks for files on the filesystem, and if one is found, $uri is set appropriately before calling the location's content handler.
Comment: Did you include the =?  location / and location = / mean very different things.
Comment: Okay - thanks a lot. But can you still clarify try_files? :)
Comment: Sure - basically, you give it a list of locations, and it can be as long as you want.  It will try to serve the request from each of those locations, in order, until it finds one that works.
Comment: @kolbyjack then i get an too-many-redirect error (i tried the 2nd example)). location / will always get evaluated and initiate the redirect. Regardless if location /blog is before, after or inside location /. :/ what am i doing wrong?

try_files explained


laravel ajax, How to send form having value='put' successfully?

Question: I'm making function that if edit form is sent using ajax, validate and send response to view. But, page load on new URL like localhost:8000/comment/id. and the page shows messages that I want. How can I get that response in view not reloading?
HTML
<form class="modify-form" method="post" action="{{ route('comment.update', $mypage->id) }}">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="hidden" name="_method" value="put">

{{ $mypage->message }}

</form>

Route
Route::match(['put', 'patch'], 'comment/{id}', ['as'=>'comment.update', 'uses'=>'MyPageController@update']);

jQuery
var $writeForm = $('form.visitor');
$writeForm.find('.write').click(function(e){

    var url = $writeForm.attr('action');

    e.preventDefault();
    $.ajax({
        url: url,
        type: 'POST',
        data: $writeForm.serialize(),
        success: function(res){
            if (res.status) {
                location.reload();
            }
        },
        error: function(res){
                $writeForm.after('
'+res.responseJSON.errors+'
')
                //console.log(res.responseJSON.errors);
        }

    });

});

Controller
public function update($id) {

    $validator = validator::make($data = Input::all(), mypage::$edit);

    if($validator->passes()) {

        $mypage = mypage::findOrFail($id);

        $message = Request::input('message');
        $mypage->update(['message' => $message]);

        $mypage->save();

        $response = array();
        $response['status'] = true;

        return response()->json($response);

    }

    if ($validator->fails()) {

        $response = array();

        $response['status'] = false;
        $response['errors'] = $validator->errors()->all();

        return response()->json($response, 400);

    }

}

Comment: I would reccommend using Vue.js, I know this may not be the answer you're after but its a great suggestion since vue.js is lightweight easy to use and has great compatability with Laravel.

It allows you to pull and post data from the back end with ease and has a lot of methods at your disposal comapred to vanilla Ajax methods.
Answer: You can create a Partial (small view) for the comment.
Then, when you create / update the comment, Laravel can return the view for the comment, and with JQuery append it to the HTML.
You can create the partial for the commment: (Very simple)

{{$comment}}

You can return the partial like any view:
return view('partials.comment')->with('comment', $comment);
Then back in JS append it like:
$("#comments-container").append(res);
Comment: Can I request some example please ?
Answer: Try this

Ajax:

type: $('input[name="_method"]').val(),
data: $writeForm.serialize(),
success: function(res){
    if (res.status == true) {
        // Reload the current page, without using the cache
        document.location.reload(true);
    }
},

Controller:

if ($validator->fails()) {
    return response()->json([
        'status' => false,
        'errors' => $validator->errors()->all()
    ], 400);

}

if($validator->passes()) {
    $mypage = mypage::findOrFail($id);

    $message = Request::input('message');
    $mypage->update(['message' => $message]);
    $mypage->save();

    return response()->json(['status' => true], 200);
}

Comment: just on new url , {"status":false,"errors":["The message field is required."]} is shown
Comment: {"status":false,"errors":["The message field is required."]} is right , but I want to bring that on my page. not new page
Comment: now you need to display this message inside you view page. using jquery `each` function inside the error: function() {}` block
Comment: error: function(res){
                $writeForm.after(''+res.responseJSON.errors+'')
                //console.log(res.responseJSON.errors);
        } is that wrong ?
Comment: I thought that responses are not sent back.
Comment: like so: `error: function(res){ $.each(res.errors, function(i, error) {
                $writeForm.after(''+ error +'');
        });  }`
Comment: same. on page url:`http://localhost:8000/comment/id` show{"status":false,"errors":["The message field is required."]}
Comment: do you want to reload your page on the response?


Linear Transformation of polynomials

Question: Let $V= \Bbb{R}_2[x]=\{P(x)=a_0+a_1x+a_2x^2 \mid a_0,a_1,a_2 \in \Bbb{R}\}$ and let $f: V \to \Bbb{R[x]} $ defined by $f(P(x))=xP(x)- \frac 1 2x^2P'(x)$

Find the matrix of $f$ in the basis $\{1,x,x^2\}$.
Find $\ker(f)$ and $Im(f)$.

For part one 1 just took the linear transformation of each vector of the basis and put them in columns to get $$ \left[ \begin{array}{ccc}
0 & 0 & 0 \\
1 & 0 & 0 \\
0 & \frac 1 2 & 0 \end{array} \right]  $$
My problem is with part 2, as this is the first time I encounter linear algebra with polynomials I have no idea what $$ \left[ \begin{array}{ccc}
1 & 0 & 0 | & 0\\
0 & \frac 1 2 & 0| & 0\\
0 & 0 & 0 | & 0\end{array} \right]  $$  means, neither is it clear to me what $$ \left[ \begin{array}{ccc}
1 & 0 & 0 | & a\\
0 & \frac 1 2 & 0| & b\\
0 & 0 & 0 | & c\end{array} \right]  $$
means. Can anyone explain to me clearly what the solutions of these systems represent and how do I find the kernal and image.
Edit I read the comments and found that the kernel of the matrix is $\ker(f)=\{(0,0,t) \mid t \in \Bbb{R}\}$ but in the image I have problem in the last equation where I get $0z= c$ how should I proceed? Do I take two cases?
Comment: On 2. you are looking for $P(x)$ s.t. $2xP(x)=x^2P'(x)$. But don't forget that your space contains only degree 2 polynomials.
Comment: You have calculated your first matrix correctly. Now note that the first two columns span the image, and the the third basis vector (corresponding to $x^2) is in the kernel.
Comment: How do you go back from the columns of the (correct) matrix in part 1 to your original $V$? Permuting rows of the matrix without permuting the given ordered basis will give you a different linear transformation.
Answer: The whole point of choosing a basis so you can write a matrix is so that the origins of the problem don't matter. You have algorithms for finding the image and kernel of a matrix -- i.e. the column space and the (right) nullspace -- these algorithms don't care where you got the matrix from, they simply work on the matrix. Once you have those, you can use your basis again to convert the result back to polynomials.
Answer: First find kernel and image of your matrix $A$.
Then remember that $A$ represents your linear mapping $f$ with respect to the basis $\{1,x,x^2\}$. Thus, you can translate the kernel (respectively image) of $A$ to the kernel (resp. image) of $f$.
Comment: Please review my edit concerning the image part.
Comment: Your kernel is correct. So -- translating it back using the basis $\{1,x,x^2\}$ -- what polynomials are in the kernel? Regarding the image: You should have learned some method to compute the image of a matrix. Apply it.
Comment: I found the image to be $(a,2b,0)$ then the kernel is the set of polynomials of the form $tx^2$ and the image is the set of the polynomials of the form $a+2bx$ , is this true? Thank you
Comment: Yes, this is correct. You still can make the result a little bit nicer: By substituting $b' = 2b$ you can remove the $2$ in the expressions $2b$. BTW, if this answer was helpful, feel free to upvote.

Linear Transformation of polynomials


If $g\in C^1(\mathbb R^n, \mathbb R)$ and $u:\mathbb R\to\mathbb R^n$ is bounded, is $g(u)$ bounded?

Question: Let $u:\mathbb R\to\mathbb R^n$ be a bounded function. Assume that $g\in C^1(\mathbb R^n, \mathbb R)$. It is possible to conclude that $g(u)$ is bounded itself?
If yes, does it come from that it is composition of a continuous and bounded functions?
Comment: I am curious about the source of this problem. A similar question appeared  a few minutes ago (by a different user)  and it was deleted.
Comment: In my case, it is the final step of an exercise for my physic class and I just wanted to be sure that I was arguing right. Many classmates post questions here (I can not guarantee it was any of them).
Answer: As $u$ is bounded, $u(\mathbb{R})$ is contained in some compact set $K$. As $g$ is continuous, $g(K)$ is also compact, and consequently a bounded set. As
$$(g\circ u)(\mathbb{R})\subseteq g(K)$$
it follows that $(g\circ u)(\mathbb{R})$ is a bounded set, and consequently $g\circ u$ is bounded.


How to implement the DriverSetup class in Selenium Webdriver framework

Question: How to implement the DriverSetup class in Selenium Webdriver framework..
Currently I am launching driver in @BeforeClass for each testng test class, please let me know if how can I implement the common driverLaunch/driverSetup class for all test
Thanks in Advance..
Comment: if you want for each test to launch a different browser through setup, use `@BeforeTest` or `@BeforeMethod` of TestNG to achieve it. Thanks.
Answer: Init your WebDriver in @BeforeTest or in @BeforeSuite and close it in @AfterTest or @AfterSuite. So in this case every test method will get run in the same browser.
Answer: Did u mean a common setup for all classes? If so create a base class and extend it in every test class. In Base class have @BeforeClass to do the required.
It would be somewhat like:
public class BaseClass {
    WebDriver driver;
    @BeforeClass
    public void setUp() {
        driver = new FirefoxDriver(); // or any driver u want, or based on requirement create a if else scenario
    }
}

And in Testclass do like:
public class TestClass extends BaseClass {
    // your class body with tests here
}

So whenever u run ur tests through testng it will call the setUp method in BaseClass and setup browser for u.
Comment: Thanks for suggestion. Worked well for me and able to get driver instance in Listener classes as well.


Customize user login block

Question: I've been playing around with Drupal 8 since about a week. A couple days ago I tried to design the user login page to my needs but I couldn't quite do it. My problem is the following:
I want to customize the user login form (/user/login). I can edit the user login page (page--user--login.html.twig) but I can't find out what the name is of the user login form? How can I restructure the elements of the user login form? Or am I looking in the wrong place?
I appreciate any help you can give!
Answer: One thing that helps immensely is to enable Twig debugging in your services.yml (not recommended for production environment).
parameters:
  twig.config:
    debug: true
    auto_reload: true
    cache: false

The auto_reload and cache settings can also be set to their development settings so you do not need to rebuild cache (remove compiled twig templates manually).
This will enable HTML comments that show what template is being used for various components in markup. Bartik and Classy, by default, displays this as block.html.twig. The template suggestions for a block is block--PLUGINID.html.twig where the PLUGINID is the the block's plugin id with underscores replaced by dashes.
Example debug output from my local development environment using a sub-theme of Classy:

templates/block--user-login-block.html.twig
Comment: Yep, form id isn't a suggestion so you have to add it yourself: http://www.foreach.be/blog/how-manipulate-forms-drupal-8
Comment: I enabled the debugging for Twig already. In the HTML comments the suggestions are these: block--personal-content.html.twig, block--system-main-block.html.twig, block--system.html.twig, block.html.twig. I created a file like you mentioned and tried to output the variables with {{ kint() }} but nothing gets outputted.
Comment: I am not able to reproduce this. I see the following suggestions for the markup right above selector `.block-user-login-block`: block--userlogin.html.twig, block--user-login-block.html.twig, block--user.html.twig, block.html.twig. And block--user-login-block.html.twig has a "x" by it signifying that it is in-use.
Comment: Another possibility is that you have not added the user login block to a region for your theme or maybe your theme does not have that region enabled.
Comment: If I place the user login block in the content region and create a block--userlogin.html.twig file and try to output the variables with kint it works (normal page). But I want to customize the user login block on the url **/user/login**. When I go to this page no variables are being outputted by kint. Thanks for your help!
Comment: Okay, I misunderstood your question. You don't want to modify the user login block. You just want to modify the user login page, which should be more akin to s-a-k-a's answer or by using `user-login-form.html.twig`. The user login page will not have a user login block because it is redundant.
Comment: Could you clarify your question so that it is specific to the user login form on the user/login page instead of user login block, @adiii4?
Comment: It looks like user-login-form.html.twig isn't valid, sorry.
Comment: Okay, I edited my question. Thanks I will look into the blog post and give you some feedback if I made it! You helped me very much!
Answer: You have this page:

/user - page--user.html.twig
/user/login - page--user--login.html.twig
/user/password - page--user--password.html.twig

I suggest you to use, for all this page
{% extends "page.html.twig" %}

Inside of this page page--user.html.twig with this

{% if page.content %}
       {{ page.content }}
    {% endif %}

And the joke is in css you have this:
.user-login input[type="text"],input[type="password"],input[type="email"],input[type="submit"]:hover, form, label, input[type="submit"]

I did only page--user.html.twig and css for all type.
If you want to structure the elements in a different way look this:

form.html.twig
form-element.html.twig
menu-local-tasks.html.twig

And pls put debug: true inside services.yml
Comment: But what if I want to structure the elements in a different way? I want to put each elements in different bootstrap coloumns.
Comment: I edit my post.. put debug: true inside services.yml
Comment: Its already true :) Don't all form elements change when I edit the form-element.html.twig? Or do I misunderstand something?
Comment: And how you would customize the fields ? for example lets say with a bootstrap theme and willing to give it's classes to the form fields ?
Answer: SimpleLogin: https://www.drupal.org/project/simplelogin
It is a simple module for Customize Drupal Login, Password and Register pages with Background images.

Customize user login block


UIDatePicker in IOS 14 showing background tabBar in keyboard

Question:
When using date picker in keyboard in IOS 14 getting this kind of output. It is not overlaying my tab bar controller in back. Can anyone help?
Answer: You can add the view in your current UIWindow which is accessible through root view of your ViewController like this:
self.view.window?.addSubview(calendarView)

And then make it overlay all other UIViews, like this:
self.view.window?.bringSubview(toFront: calendarView)

Comment: It worth mentioning that since iOS 13.4, there is preferredDatePickerStyle in UIDatePicker which you can set the style with inline, wheels, compact and automatic modes.
Comment: here the calendar view i am implementing is in input source of text field that is in keyboard and i think your method will. bring my seperately implemented view to front. Am i right?
Comment: By the i found a roundway, i changed the style of datepicker to wheels and it is fine now. By the way if you have any suggestions regarding this please share