Too Many winlogon.exe LogonUI.exe csrss.exe open on server?

Question: I just had to restart my content server because it bogged out.  Everything was fine after i restarted IIS and SQL Server, but then i opened the task manager and found the following.  I've never seen this before, i'm hoping it's not a virus of somesort.  Any info on this would be appreciated.
Command lines are:
        winlogon.exe = winlogon.exe
<code>    logonUI.exe = LogonUI.exe /flags:0x0

    csrss.exe = see image below
</code>
Comment: What's the command line? (View, Select Columns)
Comment: winlogon.exe = winlogon.exe
logonUI.exe = LogonUI.exe /flags:0x0
Comment: Is this a machine used as a terminal services server?
Comment: its a web/ftp server.. hope that helps.
Answer: I just had the same problem on one of my servers - it turned out to be caused by an attempt to get into the server through Remote Desktop/Terminal Services - either a brute-force or massive dictionary attack (every RDP logon attempt causes LogonUI to spawn). Check your System and Security event logs, they'll contain more information (such as the originating IP of any failed remote logon attempts).
Comment: Tip: if you are concerned about the resources consumed by these processes, you can change the settings to require NLA. This won't stop brute force attacks, but will prevent failed logon attempts from spawning the processes.
Answer: I found it was the morto virus
http://www.microsoft.com/security/portal/Threat/Encyclopedia/Entry.aspx?Name=Virus:Win32/Morto.A
Malwarebytes fixes it.


CLT for Medians for Distributions Without Means

Question: Is there a version of the CLT for distributions that don't have a mean, but have a median, and finite moments of order > 1? (if such distributions exist)
Comment: There aren't any distributions with finite moments of order >1 but no mean. If any given moment exists, so do all the moments of lower order.
Comment: The sampling distribution of the sample median $\hat{M}$ is approximately normal with mean $m$ and variance $\frac{1}{4n(f(m))^2}$ where $n$ is the sample size, $m$ is the population median, and $f$ is the pdf for the observations i.e. $$\hat{M} \sim N(m,1/4n(f(m))^2)$$ This approximation is good for $n\geq 30$. Is this what you're looking for?
Answer: Example:  A random variable with a standard Cauchy distribution (t distribution with DF=1) has no mean, but median $\eta = 0$ and $f(\eta)=1/\pi.$ So according
to @MatthewHolder's Comment (see Ref.), the median $H$ of a sample of size $n=100$ from this
distribution should have $H \stackrel{aprx}{\sim} \mathsf{Norm}(\mu=0,\, \sigma=\pi/20).$
<code>set.seed(2020)
h = replicate(10^5, median(rt(100,1)))
summary(h); sd(h); pi/20
      Min.    1st Qu.     Median       Mean    3rd Qu.       Max.
-0.8457575 -0.1043798  0.0006376  0.0013486  0.1067248  0.6956875
[1] 0.1589696  # aprx SD
[1] 0.1570796  # asymptotic SD

hist(h, prob=T, col="skyblue2", ylim=c(0,2.5),
     main="Dist'n of Medians of 100 Std Cauchy RVs")
  curve(dnorm(x, mean(h), sd(h)), add=T, col="red")
</code>

Ref: This relationship is Thm. 7.9.1 in Bain & Englehardt (1992): Intro. to
Probability and Math. Stat. (2e). Also, in other math stat books along with
discussions of order statistics. Also see this Q&A.


Improper integrals are "not totally Improper"

Question: Question is to evaluate $$\int _{-\infty}^{\infty} \frac{dx}{(x^2+a^2)^2}\text {for } a>0$$
Idea is to calculate this using complex analysis/residue theory/contour integration.
Approach is consider contour $D_R$  consisting of a semicircle in upper half plane of radius $R$ with the line $[-R,R]$
(I am not familiar with idea how to draw figures in latex so, it would be better if some one can help me out if they are sure that they understood what i actually mean).
So, then, we have $$\int_{\partial D_R}  \frac{dx}{(z^2+a^2)^2}= \int_{-R}^{R}\frac{dx}{(x^2+a^2)^2}+ \int_{\mathcal{T}_R}\frac{dx}{(x^2+a^2)^2}$$
where $\partial D_R$ is boundary of contour $D_R$ and $\mathcal{T}_R$ is contour except the line $[-R,R]$.
Now, as $D_R$ is bounded domain, we can use residue theorem to find what is $$\int_{\partial D_R}  \frac{dx}{(z^2+a^2)^2}$$
we have $$\int_{\partial D_R}  \frac{dx}{(z^2+a^2)^2}=\int_{\partial D_R} \frac{dx}{(z+ai)^2(z-ai)^2}$$
$$=2\pi i .\text{Residue at } (ai) $$
$$=2\pi i .\lim_{x\rightarrow ai} \frac{d}{dx}\frac{1}{(z+ai)^2}$$
$$= 2\pi i \lim_{x\rightarrow ai} \frac{-2}{(z+ai)^3}$$
$$=2\pi i \frac{-2}{(2ai)^3}$$
$$=2\pi i\frac{-2}{-8a^3i}$$
$$=\frac{\pi}{2a^3}$$
So, I have $$\frac{\pi}{2a^3}= \int_{-R}^{R}\frac{dx}{(x^2+a^2)^2}+ \int_{\mathcal{T}_R}\frac{dx}{(x^2+a^2)^2}$$
i.e., $$\int_{-R}^{R}\frac{dx}{(x^2+a^2)^2} = \frac{\pi}{2a^3} - \int_{\mathcal{T}_R}\frac{dx}{(x^2+a^2)^2}$$
as $R \rightarrow \infty $ we see that $\int_{\mathcal{T}_R}\frac{dx}{(x^2+a^2)^2}\rightarrow 0$
So,
$$\int _{-\infty}^{\infty} \frac{dx}{(x^2+a^2)^2}=\frac{\pi}{2a^3}$$
Now, I would be thankful if some one can help me what i have done is valid and I am afraid this should be the case always at least when considering $\int_{\mathcal{T}_R}\frac{dx}{f(x)}$ for $f(x)$ a polynomial
What exactly i mean is we do not have to bother about any other extra conditions except residue theorem when considering $$\int _{-\infty}^{\infty} \frac{dx}{f(x)}$$
because in any case i am fixing a bound for $\int_{\mathcal{T}_R}\frac{dx}{f(x)}$ which goes to $0$ as $R\rightarrow 0$
So, what i would like to say is $\int_{\mathcal{T}_R}\frac{dx}{f(x)}$ is actually seen as $\int _{\partial D_R}$ where $R$ is maximum magnitude of zeros of $f(x)$ in upper half plane.
I am a bit afraid if i am missing some thing.
I would like someone to verify if my idea is true.
$$\int_{\mathcal{T}_R}\frac{dx}{f(x)}=2\pi i \sum {\text{Res. at zeros of f(x)}}$$
If this is the case always then I would like to say
$$"\text{In contrast to its name, Improper Integrals behave properly (conditions apply)}"$$
Comment: Someone else will hopefully confirm, but yes, you should be able to apply the Residue Thm quite readily in the case of polynomials.
Comment: I hope the same :) Thankyou @BennettGardiner
Answer: It seems that the only problem you need to worry about is the integral over $
\mathcal{T}_R$, otherwise the approach clearly works. If the polynomial has degree $d = \deg f \geq 2$, then you can write $f(x) = a_0 x^d + a_1x^{d-1}+\dots = \Theta(x^d)$, where by this notation I mean that there are constants $r,C_1,C_2$ such that if $|x|>r$ then $C_1|x|^d< |f(x)|<C_2|x|^d$. Thus, the integral $\int_{\mathcal{T}_R} \frac{dx}{f(x)}$ can be estimated by:
$$
\left| \int_{\mathcal{T}_R} \frac{dx}{f(x)}\right| \leq \frac{\text{length of $
\mathcal{T}_R$}}{\text{maximum of } |f(x)|} \leq \frac{\pi R}{C_1 R^d} = \frac{\pi }{C_1 }\cdot \frac{1}{R^{d-1}}.$$
This obviously tends to $0$ with $R \to \infty$ so you can be sure this term can be omitted in the limit.
Comment: I was thinking of similar idea but was not so sure how to prove... Thank You...


What are Site Link Bridges

Question: I have never understood what a Site Link Bridge actually does, and from all the conflicting info on the web it seems almost no one else does ether.
But according to this guy (pretty reliable video training source), Site Link Bridges are just non-transitive Site Links.
He doesn't address this in the video, but that would mean that if I disable the Bridge All Site Links option, which means Site Links are no longer transitive are they then the same thing as Site Link Bridges?
This confuses me, because in a lot of stuff I have read it says you need to use Site Link Bridges when you disable bridge all site links, but from this definition it would seem they are only useful when you have Bridge All Site Links enabled.
Comment: If you disable **Bridge All Site Links**, your Domain Controllers become the *de facto* "bridges" between the site links.
Answer: A Site Link is a logical connection between Sites. This alows the KCC/ISTG to create replication connections between Domain Controllers in different sites. Replication connections are also logical objects. Site Links very often map to your physical network topology, but not neccessarily and not always. Site Links are transitive, which means the KCC/ISTG assumes that if sites A and B are linked and sites B and C are linked, then sites A and C must be linked and logical replication connections can be created directly between the Domain Controllers in sites A and C. This is the function of Bridge All Site Links (BASL). This works when the network is fully routed, meaning sites A and C have direct physical connectivity between them, which is a function of your physical topology. When the physical topology is such that there is no direct physical connectivity between sites A and C then the "transitivity" of BASL is broken. In this case the KCC/ISTG will create logical replication connections between Domain Controllers in sites A and C where no physical connectivity exists, therefore those logical replication connections won't work, causing replication problems. This is when you would disable BASL and create Site Link Bridges to link these Site Links, so that transitivity can be re-established.
So, if Site Link 1 links sites A and B and Site Link 2 links sites B and C then you can create a Site Link Bridge between Site Link 1 and Site Link 2 so that transitivity between sites A and C can be re-established. This allows replication to occur between the Domain Controllers in each Site Link that are members of the Site Link Bridge via the common Site in each Site Link.
Answer: It may help to think of when you would disable BASL (it's enabled by default).  The prototype use case is a central data center (hub) and branch offices (spokes) that can only communicate with the data center.
http://blogs.msmvps.com/acefekay/2013/02/24/ad-site-design-and-auto-site-link-bridging-or-bridge-all-site-links-basl/
"Simply put, what we need to do is disable BASL (Bridge All Site Links) in a non-fully routed infrastructure to tell the KCC to only partner DC's across a specific site link.
"Yes, that means you also have to create specific IP site links between headquarters in NYC to each site, as the image above shows.
"And even if you have 20 sites all fully routed EXCEPT for one of them, then the same thing goes. You must disable it all because of that one site, otherwise the KCC will partner with a DC that it may not have direct communications with."
In practice you could leave it enabled and create individual site links, but when there is a communication or replication issue with a site, the KCC will flap around and create/delete connections, but it really isn't that bad.
Answer: Imagine Houston as a Hub Site, and all the highways leading to/from Houston as your Site Links:

You see the ring road around the city? It allows traffic from all directions to circumvent the city itself and continue along another highway leading to a different city.
When you enable Bridge All Site Links, you effectively build such a ring road around all of your sites, allowing direct replication between domain controllers in two sites not directly linked to eachother.
Answer: My understanding:
"A site link bridge creates a logical connection between two site links, providing a transitive path between two disconnected sites by using an interim site. For the purposes of the intersite topology generator (ISTG), the bridge implies physical connectivity by using the interim site." (1)
would mean that if you had a DC in site A that needs to replicate with a DC in site C, where A and C are only connected to each other through "site B" and B doesn't have a DC in the replication topology you would use a site link bridge to ensure the replication goes DCinA --> siteA --> siteB --> siteC --> DCinC.
If a DC is in site B and is in the replication topology then there is no need for the site link bridge to exist.

What are Site Link Bridges


Sort array by index value (true , false)

Question: Hi I want my array to be sorted on basis of 'isStarted'  ture first,
Code snippet
<code>  [0] => Array
    (
        [id] => 127
        [name] => 23-3
        [isStarted] => false
        [isAdmin] =>
    )

[1] => Array
    (
        [id] => 125
        [name] => GameStartTesting
        [isStarted] => true
        [isAdmin] => 1
    )
</code>
I want isStarted first.
Answer: try this
<code> usort ($array, function ($left, $right) {
        return $left['isStarted'] - $right['isStarted'];
    });
</code>


Bloom Filter usign Redis and Node.js

Question: I am using @albert-team/rebloom package for implementation of Bloom Filter using Local Redis
const { BloomFilter } = require('@albert-team/rebloom')
const main = async () => {
    const filter = new BloomFilter('filtername', {
      host: 'localhost',
      port: 6379,
    })
    await filter.connect()

    console.log(await filter.add('item0')) // 1
    console.log(await filter.exists('item0')) // 1
    console.log(await filter.exists('item1')) // 0

    await filter.disconnect()
  }

  main().catch((err) => console.error(err))

but i get below error.
TypeError: multi.setbit is not a function
at /Users/rohit/Downloads/Microservices/POC/node_modules/bloom-redis/lib/index.js:61:15
Two Questions :

How can i resolve the above issue?
Is there any other package of approach i can use for Bloom Filter implementation?
Answer: Node Redis supports Redis Bloom now. Works like this:
import { createClient } from 'redis';

const client = createClient();
await client.connect();

await client.bf.reserve('mybloom', 0.01, 1000);
await client.bf.add('mybloom', 'foo'),
await client.bf.mAdd('mybloom', [ 'bar', 'baz' ]);

const singleExists = await client.bf.exists('mybloom', 'foo');  // true
const multiExists = await client.bf.mExists('mybloom', [ 'baz', 'qux' ]);  // [ true, false ]

Bloom Filter usign Redis and Node.js


Detectar palavra dentro de um elemento que esta dentro de uma class especifica

Question: Tenho o seguinte código. Tentei executar dentro do elemento com a class ACTIVE, um código que verificava se tinha a palavra VIOLET dentro do elemento com a class TITLE. Mas em vez dele executar somente no elemento com a class ACTIVE, ele executava em todos que estavam com a palavra VIOLET:

var Violet = /Violet/gi;

$('.title').append($('div').hasClass("active")).contents().each(function() {
  if (this.nodeType === 3 && this.nodeValue.match(Violet)) {
    alert('teste')
  }
});

Violet

Violet

Evergarden

Answer: Provavelmente o seguinte código pode resolver o problema:
var Violet = /Violet/gi;

if($("div.active .title").text().match(/Violet/gi)){
    alert('teste')
}

O selector $("div.active .title") pesquisa pelo elemento com a classe title dentro de um elemento div com a classe active.
O resultado será um array no caso de encontrar um valor ou null/undefined caso não exista nenhum elemento que corresponda a essa pesquisa.
Answer: Muito obrigado LeAndrade e Samuelf. Com a ajuda de vocês 2, consegui fazer um código que atende as minhas necessidades.

var violet = /Violet/gi;
 $('div.active').find('li').find('div.title').contents().each(function() {
  if(this.nodeType === 3 && this.nodeValue.match(violet)) {
  $('div.active').find('li').find('div.title').css('color','red');
  } else{
    alert('Erro. O texto não é este!'); }});

Violet

Violet

Evergarden

Comment: Usar dois `find` é redundante: `$('div.active').find('li').find('div.title').css('color','red'); `... bastaria `$('div.active div.title').css('color','red');`... veja que não precisa nem de `.find()`


how to create an applescript for multiple dd terminal commands in sequence (for multiple USB Drives duplication)?

Question: I need to create an apple script to perform DD Commands in sequence, to replicate the same .img file to multiple USB flash drives
The context: the computer is connected to a powered USB hub with 7 usb flash drives connected and unmounted by diskutil. No other USB devices or disk are connected to the computer (so the USB Sticks will be assign a disk1 - disk7 resource mapping)
The steps

a file named  "source.img" will be prepared and put on the desktop (say an .img of a bootable OS)
terminal must be asked to change directory to the desktop
with administrative privileges (the password can be inserted into the script, or asked once to the user) it must be asked to perform:

"sudo dd if=source.img of=/dev/rdisk1 bs=1m"

the script must wait until the operation is concluded, then ask the terminal to perform another DD, to disk2 this time:

"sudo dd if=source.img of=/dev/rdisk2 bs=1m"
and again, wait until the operation is concluded, and then ask:
"sudo dd if=source.img of=/dev/rdisk3 bs=1m"
and so on with rdisk4, rdisk5, rdisk6, rdisk7.

at the end of the disk7 operation , the script can shut down the terminal and send a finder message to the user (or an audio notification) that the USB Duplication process to the 7 flash drives is concluded.

It's a way to create a "USB duplicator on the cheap" for bootable images to be put on multiple sticks, I need it for a school project to my students.
Anybody can help ? I am a zero with Applescript. And this thing will be useful for many.
Thank you !
Alberto
Answer: Why do you need to do it using Applescript? Why not a simple shell script like this?
<code>#!/bin/bash
cd ~/Desktop
for i in {1..7}; do
   echo "Duplicate to /dev/rdisk${i} (y/n) ?"
   read r
   [[ "$r" == "y" ]] && echo sudo dd if=source.img of=/dev/rdisk${i} bs=1m
done
say "Duplication complete"
</code>
Save it on your Desktop as "Duplicator" and then start a Terminal and in the new Terminal window type:
<code>chmod +x Desktop/Duplicator
</code>
to make it executable. Then you can run it by double-clicking the "Duplicator" icon on your Desktop.
Note:
At the moment, it just echoes the "dd" command, run it and see if you like it then remove the "echo" if all looks correct.
Note:
This works on Mavericks and Mountain Lion at least, on some older versions of OSX you may need to name the script "Duplicator.command" and/or associate the script with the Terminal app. See here.
Note:
You might try adding a "&" after the "bs=1m" so that the 7 "dd" commands run in parallel, and then adding a new line that says "wait" between the lines "done" and "say" to wait for all "dd" commands to complete. This will mean that you can answer the 7 questions immediately one after the other instead of having to sit there and watch and do them one at a time. It may also make the "dd" commands run faster or slower - depending on the relative performance of your memory sticks and USB bus. It will also avoid problems with "sudo" timing out - though these could be solved by changing the timeout in the file /etc/sudoers.


Can I use another entity in the route to provide an entity to an entity form?

Question: I am working on a custom content entity that I want to 'link' to a user by adding it as a tab to the user profile. Each user can have one such entity.
My route is defined as follows:
entity.my_entity.edit_form:
  path: '/user/{user}/my_entity'
  defaults:
    _entity_form: my_entity.edit
    _title: 'Edit entity'
  requirements:
    _entity_access: my_entity.update
  options:
    user: \d+

And the tab (module.links.task.yml):
entity.my_entity.edit_form:
  route_name: entity.my_entity.edit_form
  base_route: entity.user.canonical
  title: Entity

Though this works and the tabs show up, they result in a fatal error (cannot return getValue() on null from the getters) presumably because the form does not have an assigned entity.
If I change the route path to /user/{user}/my_entity/{my_entity}, the form works, but I cannot create a tab as the last value is unknown to the routing system.
Can I use the provided user entity instead from the route instead and during the building of the entity form retrieve (and set) the entity I need?
Answer: You can use a controller with the user as only route parameter. There you can put the code to retrieve the entity that matches the user and build the entity form:
public function myEntityForm(UserInterface $user) {

  // get $my_entity that matches $user

  $form = $this->entityFormBuilder()->getForm($my_entity);

  return $form;
}


Cannot read property 'nodes' of undefined

Question: Estou obtendo o ERRO abaixo ao tentar implementar uma estilização no meu projeto com Stylus. O mesmo acontece para background: url(...); e acho que para qualquer outra tentativa relacionada.
Encontrei no Github alguns problemas semelhantes, mas nenhuma das soluções funcionou neste caso.
Estou utilizando o plugin gulp-stylus e já utilizei antes, mas tudo sempre correu normalmente.
Cannot read property 'nodes' of undefined
    at ".section-partition" (/media/idlua/Arquivo 1/Development/Projects/project/src/css/_areas/_areas-global.styl:8:98)

Details:
    lineno: 14
    column: 75
    filename: /media/idlua/Arquivo 1/Development/Projects/project/src/css/_areas/_areas-global.styl
    stylusStack:     at ".section-partition" (/media/idlua/Arquivo 1/Development/Projects/project/src/css/_areas/_areas-global.styl:8:98)

Trecho do código que gera o ERRO (quando retiro a estilização do bg funciona):
.section-partition
  content ""
  display block
  width 100%
  height 1px
  margin 1em auto
  background-image linear-gradient(to left $color_1n, $color_2n, $color_1n)

Alguém tem alguma ideia do que pode estar causando?
Comment: Já testaste com valores fixes em vêz de variáveis como `$color_1n`?
Comment: Tentei, mas obtive o mesmo erro. Mas descobri o problema; era apenas o nome do diretório onde estava o projeto. =/
Answer: Descobri qual era o problema: apenas o nome do diretório onde estava o projeto. Havia um # no nome da pasta e isto estava confundindo o Node a encontrar os imports nos arquivos css.


Beginner question about how to understand chords in musical notation

Question: I have a question about how to interpret musical notation involving chords. In the first picture, I can see D minor chord but do I play it with right or left hand? And what notes do I play with the other hand?
If someone is able to clarify this, I'd be very grateful, as it's been confusing me a lot! Thanks!

And similarly, do I play F major with my left hand? What do I do with my right hand?
Comment: In addition to what the others have said here -- *anyone* could use this as a glorified "chart" to improvise from.
Comment: when I started, I used the chord symbols (like Dm) in your example and I learned the left hand shapes for them. As I became comfortable reading music sheets, I could then start to see all the details that make the Dm chord: some notes are inverted, some are doubled, etc and very quickly, you also learn to recognize what chord it is because the notes shapes tend to repeat a lot. Ultimately, I always use both: the symbol tells me what's up instantly and then when I read the notes I can recognize the shapes and which inversions to play, etc without spending much time decoding it.
Answer: The notes and chord symbols are two separate complementary things.
The Dm chord symbol is a short summary, abstraction, description, simplification of the overall harmony which continues until the next chord symbol, and the notes ("dots") are a concrete realization written out as notes. You could ignore the chord symbols and just play the notes, even blindly like a machine, without having to know that what you play could be described or categorized as a "Dm" chord. Or you could ignore the notes and play some improvised chordal accompaniment from the chord symbols. There's any number of ways to realize a "Dm" chord symbol as notes.

Here are some examples of music that can be labelled with a Dm chord symbol. Often in song books the chord symbols are simplifications and approximations of the notes, to make it easier to play, or because the exact notes aren't deemed that important.

In the last example, one might argue that the chords are really Dm, Dmmaj7/A, Dm7, ... etc. But it works just as well if a guitarist plays
any Dm chord there, and the "maj7" additions would be just awkward to read. Good guitarists can read the notation and play the more complicated things.
Chord symbols are used in at least the following situations

If you cannot read music ("dots") well enough
If the written-out notes aren't suitable for the performance, for some reason, you could make up your own accompaniment.
If you play a different instrument which isn't suitable for playing the written-out notes
If you just want to create additional instrument parts. For example guitar, bass, synth pad.
If you want to play variations, for example a different rhythm pattern or different harmonies, maybe differently in the second verse. Or if you just want to do a grind core version of the tune, but the written-out notation is a bossa nova.
If you want to improvise a solo over the song, you use the chord symbols as a rough map of what happens in the harmony.

The dots are used:

For writing and playing melodies and other specific musical ideas that have to be described note-for-note
For describing specific voicings, i.e. ways to spread out and double chord tones in different octaves.
If you want to play the specific accompaniment pattern.
If you want to play specific melodic or rhythmic lines that are an essential part of the song. Instrument lines, riffs, etc.
If you can't think of better things to play, the written-out notes contain at least some kind of an idea to play.
If you can't read chord symbols fast enough.
Comment: @AlbrechtHügli - "in opposite" does not work in English.  You want "in contrast" or "rather."  ...*but I wouldn't.  Rather, I would read etc.*
Comment: @aparente001:thank you so much. As you may know I am here for an English course, no joke!
Comment: Worth noting chords are also added to aid guitar or other instruments (e.g.) bass who don't need the full score, so the player doesn't need to be able to analyse this from the sheet music.
Comment: You could ignore it - but I wouldn't! In opposite I would read more additional information about chords, chord progression and the chord functions. You have written the names F,A, but you could as well write D,F,A (Dm-chord) and F,A,C (F-chord).
Comment: @Mr.Boy in fact that is the original reason for adding chord symbols to sheet music -- so someone can play along with a ukulele.
Answer: Play what is notated. The chord symbols describe the harmonic basis of what you WILL be playing.
Sometimes you'll see music that has just a melody line and chord symbols.  In that case you'd be expected to make up a LH part similar to what is written.
But in this case, if you're playing this keyboard arrangement ON a keyboard, you  play what it says.  Treat the chord symbols as just for information.
Answer: Since you're playing piano, you would normally ignore the chord symbols.  Your right hand plays the notes in the upper staff, and your left hand plays the notes in the lower staff.  The practice of printing chord symbols in sheet music was originally for the benefit of people playing guitar or banjo or ukulele or autoharp or the like: chord instruments that can't usually play all the detail present in a written-out piano part.  Such an instrument could play along in addition to a piano or instead of the piano.
Alternatively, a pianist who wants to play in a more improvisational way can also ignore the notes in the staves and play the chords.  The right hand generally plays the chords indicated above the staff, and the left hand plays the root of the chord unless a different note is indicated with a slash following the chord symbol, for example Dm/C, which means "play a D minor chord with a C in the bass."
Answer: Piano players using the music will play in one of two ways. The basic way is to play the notes shown on the treble clef with r.h., and those shown on the bass clef with l.h. Very straightforward.
The chord symbols shown are there for guitar as much as any, as a guitarist would probably play chords and read those letter names.
A piano player might use the chord symbols to embellish what he's playing - it says Dm, so he could play notes D F and A - in any order, with one or both hands, depending on style - his and that of the music, as well as considering what other instruments or vocals are around it all.
In the top example, there's F and A held as a 'chord' with r.h., and the l.h. plays a Dm arpeggio for the bar. A good pianist would know, from reading the dots, that that's what it is. Others may decide to read the 'Dm' above, and play a D and A together, l.h., and F A D r.h., for instance.
Answer:
how to interpret musical notation involving chords

You'll have to understand that sheet music of Pop songs never can represent the original performance. They can give you the idea of the notation of the tune (the pitch will be correct but the rhythm is hard to notate) and also the notation of the chords is mostly an idea what a piano reduction could look like. So you are free to play exactly the written notes or to embellish them with additional chord tones or arpeggios or rhythmic patterns just as you like. The chord letters will help you to analyze what chords are used - maybe by the original version or any other interpretation. And you even can search for other fitting chords. As a beginner like you it will be sensible to play first as written and then to try out other chord riffs that will also fit. These chord signs are very useful and helpful to understand the harmony of other new songs you plan to play, so it is always beneficial to pay attention and not ignore them. You will be also able to play the song just from a lead sheet with only lyrics and chord notation (chord letters) and make you free to improvise and play without sheet music.
So you can play the chord in the left hand and in the right hand only the melody, or with the left hand only the bass line (or bass tones) and with the r.h. the tune and the chord tones, or mix and interchange everything: This would be a good practice.
Answer: When playing sheet music as written, you play the notes that are shown.
At the start of the passage you showed,
the F and A above middle C are written, and the D below middle C is written.
Therefore you should be playing those three notes at the start of that measure.
How you play the notes is your business. I would play (and hold) the two notes in the upper staff with my right hand and play the sequence of notes in the lower staff with my left hand.
But you could decide to play the two notes in the upper staff with your left hand and play the notes in the lower staff with your right hand.
Notice that you still play the F and A above middle C and the D below middle C, so if you decide to play the D with your right hand you have to cross one arm over the other in order to reach the notes.
In the edition of the Gershwin preludes I play from, part of the second prelude consists of chord-like notes in the upper staff and melody-like notes in the lower staff, somewhat like the music you have shown. (In the Gershwin prelude, however, the chords are repeated several times a measure rather than held.)
There is a note printed over this passage that says, "Optional Version: Reverse Hands". Here the written sheet music itself is suggesting you could choose to cross your arms one over the other to play the lower notes with your right hand.
I play that passage using my left hand for the lower notes and my right hand for the upper notes. I decided I would rather try to become good at playing a melody with my left hand than to play with my arms crossed over.
But that was a choice I made, not something dictated by the written music.
Answer: I was going to suggest something slightly opposite of Lee C. I've found chords provide something of a shorthand which enables the dot information to actually be consumed faster, particularly when sight reading. When Dm appears above the staves, one doesn't have to read each individual dot but only recognize the particular pattern in which the D minor dots are assembled. For example, seeing an A as the lowest note in the bass clef, it would be natural to play it with the little finger of the left hand, but the chord would influence how the other fingers of the hand would instinctively be aligned above other notes, i.e., above D-F-A in Dm, C#-E-A in A major, C#-F#-A in F#m, and so on.Especially when sight reading at fast tempi, chords provide a very useful guide to quickly grasp the structure and articulation of the dots.
Answer: In addition to other useful answers... there is more to "a chord" than just playing the triad or triad+seventh. Choice of inversions and other arrangements of the notes is part of the art of playing from chord-notation-only charts... and even in some very simple traditional music (for example, Xmas carols), specific choice of "voicings" of chords is part of the sound people expect. So in those cases just exactly play the notes written-out, rather than a (naive choice of) triad, etc.
When you are more experienced, you'll be able to make extensions of those traditional voicings that have a compatible sound with the traditional ones. But, until then, people who know those traditional songs very well may find one's "improvisations" jarring and disappointing. :)


mysqld: Unable to determine if daemon is running: No such file or directory

Question: I was unable to re/start mysql on Ubuntu 18.04 using systemctl start mysql.service command.
It suddenly happened after restarting the server.
I see this line on the log file:

mysqld: Unable to determine if daemon is running: No such file or directory

How to solve this?
The result of journalctl -xe -u mysql.service is:
Jul 14 16:36:49 cloud systemd[1]: Starting MySQL Community Server...
-- Subject: Unit mysql.service has begun start-up
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- Unit mysql.service has begun starting up.
Jul 14 16:36:50 cloud mysqld[28159]: Unable to determine if daemon is running: No such file or directory
Jul 14 16:36:50 cloud systemd[1]: mysql.service: Control process exited, code=exited status=1
Jul 14 16:36:50 cloud systemd[1]: mysql.service: Failed with result 'exit-code'.
Jul 14 16:36:50 cloud systemd[1]: Failed to start MySQL Community Server.
-- Subject: Unit mysql.service has failed
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- Unit mysql.service has failed.
--
-- The result is RESULT.
Jul 14 16:36:50 cloud systemd[1]: mysql.service: Service hold-off time over, scheduling restart.
Jul 14 16:36:50 cloud systemd[1]: mysql.service: Scheduled restart job, restart counter is at 1.
-- Subject: Automatic restarting of a unit has been scheduled
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- Automatic restarting of the unit mysql.service has been scheduled, as the result for
-- the configured Restart= setting for the unit.
Jul 14 16:36:50 cloud systemd[1]: Stopped MySQL Community Server.
-- Subject: Unit mysql.service has finished shutting down
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--
-- Unit mysql.service has finished shutting down.
Jul 14 16:36:50 cloud systemd[1]: Starting MySQL Community Server...
-- Subject: Unit mysql.service has begun start-up
-- Defined-By: systemd
-- Support: http://www.ubuntu.com/support
--

and this the result of sudo less /var/log/mysql/error.log:
2021-07-14T16:36:50.074477Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more detai
ls).
2021-07-14T16:36:50.078158Z 0 [Note] /usr/sbin/mysqld (mysqld 5.7.34-0ubuntu0.18.04.1) starting as process 28161 ...
2021-07-14T16:36:50.095869Z 0 [Note] InnoDB: PUNCH HOLE support available
2021-07-14T16:36:50.095891Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2021-07-14T16:36:50.095895Z 0 [Note] InnoDB: Uses event mutexes
2021-07-14T16:36:50.095898Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
2021-07-14T16:36:50.095901Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2021-07-14T16:36:50.095908Z 0 [Note] InnoDB: Using Linux native AIO
2021-07-14T16:36:50.106135Z 0 [Note] InnoDB: Number of pools: 1
2021-07-14T16:36:50.108649Z 0 [Note] InnoDB: Using CPU crc32 instructions
2021-07-14T16:36:50.110883Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2021-07-14T16:36:50.129232Z 0 [Note] InnoDB: Completed initialization of buffer pool
2021-07-14T16:36:50.135317Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
2021-07-14T16:36:50.159838Z 0 [ERROR] InnoDB: Database page corruption on disk or a failed file read of page [page id: space=0, page number=5]. You may have to recover from a backup.
2021-07-14T16:36:50.159862Z 0 [Note] InnoDB: Page dump in ascii and hex (16384 bytes):
 len 16384; hex 36301e4a000000050000000000000000000000003ba6516200....

Answer: I could solve this issue using the answers from here and here.
Comment: What was the solution?


How to draw a border around a mapview

Question: i am trying to draw a margin around my mapView when a button is clicked.
So this is what i have tried and it does not work. The mapview is inside a relative layout.
LayoutInflater inflater = getLayoutInflater();

LinearLayout mView = (LinearLayout) inflater.inflate(
                        R.layout.map_view_create_ps, mapView, false);

GeoPoint viewLoc = mapView.getMapCenter();
MapView.LayoutParams params = new MapView.LayoutParams(
                        LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT,
                        viewLoc,

MapView.LayoutParams.BOTTOM_CENTER);
                mView.setLayoutParams(params);
                mapView.addView(mView);
                mView.setVisibility(View.VISIBLE);

The above is called when the button is clicked
my create_ps_layout is as such
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="@android:color/transparent">
<LinearLayout android:layout_width="fill_parent"
    android:id="@+id/linearLayout1" android:orientation="vertical"
    android:layout_height="fill_parent"
    android:background="@drawable/rounded_boarder"></LinearLayout>

 </LinearLayout>

And the drawable background is like this
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="@color/translucent_black" />
<corners android:bottomRightRadius="30dp"
    android:bottomLeftRadius="30dp" android:topLeftRadius="30dp"
    android:topRightRadius="30dp" />
    <stroke android:width="2dip" android:color="#FFB600"/>
</shape>

This does not work, but could you guys point me in the correct direction on how to draw a border around the mapview when the button is selected?
Answer: put you mapview in one RelativeLayout and set padding property of the RelativeLayout as follow:
      <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" android:layout_weight="1"
            android:background="#444" android:padding="2dp">

            <com.google.android.maps.MapView
                android:id="@+id/mapView"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:apiKey="YOUR-MAP-KEY"
                android:clickable="true"/>
        </RelativeLayout>

Answer: Create a simple stroke rectangle drawable (an xml shape) and toggle it on you map view.
Here is a sample. I use a SurfaceView instead of the MapView for simplicity, it should work pretty same.
res/drawable/red_frame.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <stroke android:color="#ff0000" android:width="3dp"/>
    <padding android:left="3dp" android:top="3dp" android:right="3dp" android:bottom="3dp" />
</shape>

res/layout/activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <CheckBox
            android:id="@+id/frame_switch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:text="Show frame" />

    <SurfaceView
            style="@android:style/TextAppearance.Large"
            android:id="@+id/target"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/frame_switch"/>

</RelativeLayout>

And finally the Java glue – MainActivity.java:
public class MainActivity extends Activity {

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

        final View target = findViewById(R.id.target);
        final CheckBox checkbox = (CheckBox) findViewById(R.id.frame_switch);

        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                target.setBackgroundResource(isChecked ? R.drawable.red_frame : 0);
            }
        });
    }
}

Answer: Follow these steps :
1- Create image_border.xml in the drawable with the below code :
 <?xml version="1.0" encoding="utf-8"?>
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
 <item>
    <shape android:shape="rectangle" >
        <gradient
            android:angle="90"
            android:centerColor="#30ffffff"
            android:endColor="#30ffffff"
            android:startColor="#30ffffff" />
    </shape>
</item>
<item
    >
    <shape android:shape="rectangle" >
        <solid android:color="#30ffffff" />
    </shape>
</item>

2- create another XML image_borderless.xml in the drawable with the below code :
 <?xml version="1.0" encoding="utf-8"?>
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <shape android:shape="rectangle" >
        <gradient
            android:angle="90"
     ></gradient>
    </shape>
</item>
<item
  >
<shape android:shape="rectangle" >
   </shape>
</item>

3- in your onClick implementation add this code :
       wp1.setOnClickListener(new OnClickListener() {
   @Override
    public void onClick(View v) {

       //wp1 to add a boarder if selected
      wp1.setBackgroundDrawable(getResources().getDrawable(
                    R.drawable.image_border));
            wp1.setPadding(8, 8, 8, 8);
      //wp3 to hide the boarder if not selected
       wp3.setBackgroundDrawable(getResources().getDrawable(
                    R.drawable.image_borderless));

       }
    });

Answer: create layer list as follows.and add it as a background to your relative layout.this will give a border with a drop shadow
here is the link for further details http://www.uifuel.com/android-creating-a-drop-shadow-in-xml-layout/
 <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">

     <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#00CCCCCC" />
        </shape>
    </item>
     <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#10CCCCCC" />
        </shape>
    </item>
     <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#20CCCCCC" />
        </shape>
    </item>
     <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#30CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <solid android:color="#50CCCCCC" />
        </shape>
    </item>

    <item>
    <shape>
            <solid android:color="@color/white" />
        <corners android:radius="3dp" />
    </shape>
    </item>
</layer-list>

How to draw a border around a mapview


Store number in javascript variable, then add to it when script runs?

Question: I have a variable I want to equal 0 when the page loads. var number = 0; When a button is clicked, I want to store that result inside the number variable and keep adding to it.
var number = 0;

$(document).on('click', ".math", function() {
var number = number + 8;
alert(number);
});

I know this seems pointless, but I am really trying to figure out how to do this. The user cant see what is happening behind the scenes, but the  number that number is will depend on content that is shown. It just keeps saying that number is equal to 8 and never changes. How do I allow it to increment? Thanks!
Comment: Don't re-use `var` again in your function. Just `number = number + 8;`. And don't debug with `alert`. Use the console.
Comment: `number = number + 8;` as you are trying to manipulate the value of the global `number` variable. Having keyword `var` will create another variable and the newly created variable will have function scope, not global.
Answer: Here is a working demo. Basically you shouldn't use var if you want to access the global number variable.

var number = 0;
alert(number);
$(document).on('click', ".math", function() {
  number = number + 8;
  alert(number);
});

<button class="math">Click me!</button>


Django filtering by multiple tags in many to many ORM object

Question: I have three models. Query, QueryStringTag, and Tag. These models are apart of a tag cloud that I have built. A Query can have many Tags and a Tag can have many Querys. The Tag and Query models have foreign keys to the connecting QueryStringTag model that holds all of the information about how a query is associated with a tag and vice versa.
Here are my models...
class Tag(models.Model):
    name = models.CharField(max_length=101)
    use_count = models.IntegerField(default=1)

class QueryStringTag(models.Model):
    tag = models.ForeignKey(Tag, related_name='qstag')
    querystring = models.ForeignKey(QueryString, related_name='qsquerystring')

class QueryString(BaseObject):
    """
    Query string holds an SQL statement and query properties for execution
    """

    server_id = models.IntegerField()
    schema = models.CharField(max_length=255, blank=True)
    archived = models.BooleanField(default=False)
    query = models.CharField(max_length=60000)
    variables = models.TextField(blank=True)
    created_by = models.ForeignKey(User, related_name='queries_created')
    updated_by = models.ForeignKey(User, related_name='queries_last_edited')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField()
    touched_by = models.CharField(max_length=1000)
    config = models.TextField(blank=True)
    runs_started = models.IntegerField(default=0)
    runs_completed = models.IntegerField(default=0)
    runs_completed_duration = models.IntegerField(default=0) # total number of seconds spent running this query to completion
    formats = "pretty_html html json prettyjson csv excel tableau".split()

I currently have it set up so a user clicks any given amount of tags in the tag cloud and an array of tag primary keys are sent down to my django view looking something like this: ['12', '14', '15']
I need to use Django ORM to retrieve all queries that are associated with all of the tags the user clicked on. So if a user clicks on the tags, 'user', 'game', and 'truck' it should bring me back only the queries that are associated with all of the tags that the user clicked on. This is an AND relationship, not an OR relationship. Meaning "Query1" would be associated with '12' and '14' and '15'.
What would the correct syntax be for this?
Comment: It would be easier to implement this if you have `Tag` as `ManyToManyField` in `QuerySting`. What's the purpose for having `QueryStringTag`?
Comment: @ShangWang The long and short of it is that our local dev environment wont accept a `ManyToManyField`. I had to do it this way.
Comment: I've only done this with `ManyToManyField` and there are tons of answers related to that: http://stackoverflow.com/questions/13270513/django-manytomany-filter-matching-on-all-items-in-a-list and http://stackoverflow.com/questions/8618068/django-filter-queryset-in-for-every-item-in-list. Maybe raw sql would help.
Comment: @ShangWang This is a `ManyToManyField`, accept it is just spelled out. All the `ManyToManyField` does is make a center connecting table much like what I am doing.
Comment: Of course I'm aware of that. Maybe I'm missing something but my point is that your design makes it hard to do it using django ORM api. Although I still don't quite get what's blocking you from using `ManyToManyField`.
Comment: @ShangWang Trust me, man. If I could, I would. lol.
Answer: qsts_pks = QueryStringTag.objects.filter(tag__pk__in=['12', '14', '15']).values_list('id', flat=True)
queries = QueryString.objects.filter(qsquerystring__pk__in=qsts_pks)

Relevant docs here and here


docker-ce worked on CentOS 7 VPS but no longer works

Question: In middle of September I've rented CentOS 7 VPS, installed docker-ce from stable repo there, according to the docs and all was fine.
Today I've realized that docker daemon doesn't working. I've failed to start it with
# systemctl start docker

and all what I've found with
journalctl -xe`

was
ноя 15 18:19:06 *hostname* systemd[1]: containerd.service: control process exited, code=exited status=1

I've tried to reinstall docker-ce, but still cannot start it:
ноя 15 18:19:06 *hostname* sudo[24909]: myuser : TTY=pts/5 ; PWD=/home/myuser ; USER=root ; COMMAND=/bin/systemctl start docker
ноя 15 18:19:06 *hostname* systemd[1]: Starting containerd container runtime...
-- Subject: Начинается запуск юнита containerd.service
-- Defined-By: systemd
-- Support: <link>
--
-- Начат процесс запуска юнита containerd.service.
ноя 15 18:19:06 *hostname* systemd[1]: Starting Docker Application Container Engine...
-- Subject: Начинается запуск юнита docker.service
-- Defined-By: systemd
-- Support: <link>
--
-- Начат процесс запуска юнита docker.service.
ноя 15 18:19:06 *hostname* systemd[1]: containerd.service: control process exited, code=exited status=1
ноя 15 18:19:06 *hostname* systemd[1]: Failed to start containerd container runtime.
-- Subject: Ошибка юнита containerd.service
-- Defined-By: systemd
-- Support: <link>
--
-- Произошел сбой юнита containerd.service.
--
-- Результат: failed.
ноя 15 18:19:06 *hostname* systemd[1]: Dependency failed for Docker Application Container Engine.
-- Subject: Ошибка юнита docker.service
-- Defined-By: systemd
-- Support: <link>
--
-- Произошел сбой юнита docker.service.
--
-- Результат: dependency.
ноя 15 18:19:06 *hostname* systemd[1]: Job docker.service/start failed with result 'dependency'.
ноя 15 18:19:06 *hostname* systemd[1]: Unit containerd.service entered failed state.

What should I do to figure out problem more specific and fix it?
Answer: You most probably face this issue https://github.com/docker/for-linux/issues/475
Remove modprobe overlay from containerd unit, which is a dependency for docker unit
One possible solution is to use systemd override features as described in the provided url
# cat /etc/systemd/system/containerd.service.d/override.conf
[Service]
ExecStartPre=


If the roots of an equation are $a,b,c$ then find the equation having roots $\frac{1-a}{a},\frac{1-b}{b},\frac{1-c}{c}$.

Question: Actually I have come to know a technique of solving this kind of problem but it's not exactly producing when used in a certain problem.
Say we have an equation
$$2x^3+3x^2-x+1=0$$
the roots of this equation are $a,b,c$. If I were to find the equation having the roots $\frac{1}{2a}, \frac{1}{2b}$ and $\frac{1}{2c}$ then I can use the root co-efficient relations and use the rule of creating equations from roots.
This gives me the result : $$4x^3 + 2x^2 -3x -1 =0$$
A much much simpler way to solve this math is: if we pick that, $f(x)= 2x^3+3x^2-x+1$ and the values of $x$ are $a,b$ and $c$ then $f\left(\frac{1}{2x}\right)$ will denote an equation (if we just write $f\left(\frac{1}{2x}\right)=0$ ) which has the roots $\frac{1}{2a}, \frac{1}{2b}$ and $\frac{1}{2c}$. And this way the result also matches the result of my previous work.
But now I face an equation
$$x^3+3x+1=0$$ and if the roots are $a,b,c$ then I have to find the equation with the roots $\frac{1-a}{a},\frac{1-b}{b},\frac{1-c}{c}$.
If I use the root-coefficient relations then I have the result
$$x^3+6x^2+9x+5=0$$ (which is correct I think).
But here $f\left(\frac{1-x}{x}\right)= 3x^3-6x^2+3x-1$. So writing $f\left(\frac{1-x}{x}\right)=0$ won't give me the actual equation.
Where am I mistaking actually?
Comment: Are you saying that if $f(x)$ has roots $a,b,c$ then $f(\frac{1-x}{x})$ is a polynomials and has roots $\frac{1-a}{a}, \frac{1-b}{b}, \frac{1-c}{c}$?
Comment: @PaoloLeonetti if we are talking about roots of polynomial, we're talking about equating it(polynomial) to $0$. Hence if $f(x)=0$ is a polynomial *equation*, then $f(\frac{1-x}{x}) =0$ will definitely be a polynomial.
Answer: Hint:  let $y=(1-x)/x \iff x=1 / (y+1)\,$, then:
$$
P(x)=P\left(\frac{1}{y+1}\right)=\frac{1}{(y+1)^3}\big(1+3(y+1)^2+(y+1)^3\big)
$$
The polynomial in $y$ is therefore:
$$
1+3(y+1)^2+(y+1)^3=y^3 + 6 y^2 + 9 y + 5
$$
This can be verified in WA by calculating the resultant[ x^3+3x+1, 1-x-xy, x ].
Answer: The equation $x^3+3x+1=0$ has roots $a,b,c$. Find the equation whose roots are $\frac{1-a}{a},\frac{1-b}{b},\frac{1-c}{c}$.
So let $y=\frac{1-x}{x}$ ... invert this equation, we have $x=\frac{1}{1+y}$, now substitute this into the original equation & you get $\color{red}{y^3+6y^2+9y+5=0}$.
Note that in your previous example you should have made the substitution $y=\frac{1}{2x}$ and then inverted this to $x=\frac{1}{2y}$ ... which of course leads like exactly the same thing.
Answer:
A much much simpler way to solve this math is; If we pick that, $f(x)= 2x^3+3x^2-x+1$ and the values of x are a,b and c then f(1/2x) will denote an equation (if we just write f(1/2x)=0 ) which has the roots 1/2a, 1/2b, 1/2c.

This is not true. Suppose we have $f(x) = (x - 1)^2$. This has the root 1. And $f(1/2x) = (1/2x - 1)^2$. But we solve for the root we get $1/2x - 1 = 0$, so $x = 2 \neq 1/2$.
Comment: 1/2x -1 =0 , 1/2x =1 and so multiplying both sides with x, we get x= 1/2. So I think my conjecture still stands...
Comment: @Sami you do realise $1/2x = \frac{1}{2}x$ and not $\frac{1}{2x}$?
Answer: First consider the polynomial with roots $a,b,c$:
$$g(x)=(x-a)(x-b)(x-c)=x^3-(a+b+c)x^2+(ab+ac+bc)x-abc$$
and let
$$r=a+b+c \quad\quad s=ab+ac+bc \quad\quad t=abc$$
And we accordingly write
$$g(x)=x^3-rx^2+sx-t$$
Now we multiply the linear factors of the expression having the desired roots:
$$f(x)=\Big(x-\frac{1-a}{a}\Big)\Big(x-\frac{1-b}{b}\Big)\Big(x-\frac{1-c}{c}\Big)$$
$$||$$
$$x^3-\frac{ab + ac+bc-3abc}{abc}x^2+\frac{a+b+c+-2(ab+ac+bc)+3abc}{abc}x-\frac{1-(a+b+c)+ab+ac+bc-abc}{abc}$$
and not that each of the coefficients can be expressed with $r,s,t$. Specifically we observe that
$$f(x)=x^3-\frac{s-3t}{t}x^2+\frac{3t-2s+r}{t}x-\frac{1-r+s-t}{t}$$


building dynamic pivotviewer collections using ria services

Question: Is it possible to build pivotviewer collection of data from database using ria services & EF ?
Answer: Essentially yes. The major part of creating pivot collections however is the creation of the deepzoom images and collections. If you truly need to build dynamic collections, then start off by looking at the JIT server example.
The approach I have personally (successfully) taken with dynamic collections is to run a batch process which runs every x minutes (for example) and re-creates the pivot collection using pauthor.


Different content, one database

Question: Is it possible to have a multi-site installation, where I have different content for each site, but using a single database?
Answer: Yes it is possible. Use the Domain module. But if the sites will not share any data, no special modules are needed. Set a unique "Table name prefix" when installing Drupal on each site instance.
Comment: Actually I am interested in creating a jobboard for many countries .i.e one jobboard for each country.Each jobboard will have different content(i.e. different jobs).Which method should I use for such a multisite project?Thanks
Comment: We cannot give opinion-based answers here.
Comment: @Dion This answer already answers the content part. The fact content is collected in job boards doesn't change the answer.
Comment: @apaderno That makes sense,thanks for the help.

Different content, one database


How to pass a date variable into a php query

Question: I've been trying many different ways to pass the dates into the query as a variable, and nothing I've tried has worked. When I put the exact dates in there like below, the query works fine.
<code>$ly = mysqli_query($link,'SELECT SUM(rtype_price) FROM client WHERE date BETWEEN "2017-01-01" AND "2017-12-31"');

while($row1 = mysqli_fetch_array($ly))
  {
    $ly_cash = $row1['SUM(rtype_price)'];
  }
</code>
For example, I've been trying something like this:
<code>$ly_start = date('Y-m-d', strtotime('first day of previous year'));
$ly_end = date('Y-m-d', strtotime('last day of previous year'));
</code>
then passing $ly_start and $ly_end into the query like this:
<code>$ly = mysqli_query($link,'SELECT SUM(rtype_price) FROM client WHERE date BETWEEN "$ly_start" AND "$ly_end"');
</code>
Comment: Concatenation problem : `BETWEEN "'.$ly_start.'" AND "'.$ly_end.'"'`
Comment: You will never get the value as expected if you put a variable inside a single quote. ` "$ly_start" AND "$ly_end"` will out put something like ` "$ly_start" AND "$ly_end"` not `YYYY-mm-dd AND YYYY-MM-DD` as expected,
Comment: Wow, so simple. That was the trick, inverting the single/double quotes. Starting with "SELECT instead of 'SELECT and then the date variables as '$ly_start' worked. Thank you!
Comment: Possible duplicate of [What is the difference between single-quoted and double-quoted strings in PHP?](https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php)
Answer: Inverting the quotes did the trick. This works:
<code>$ly = mysqli_query($link,"SELECT SUM(rtype_price) FROM client WHERE paid = 1 AND date BETWEEN '$ly_start' AND '$ly_end'");
  while($row1 = mysqli_fetch_array($ly))
  {
    $ly_cash = $row1['SUM(rtype_price)'];
  }
</code>
Thank you ild_flue
Comment: ever heard of prepared statements?


Recommender Engine for documents VS Search engine indexing

Question: I have a lot of books and I want to make recommendations to users based on the description and the title of those books.
I think that one way is to preprocess the content of the title and description fields (eliminate undesirable words, punctuations), apply the TF-IDF algorithm and then a K-means algorithm to group the books into categories to make recommendations.
However, another approach could be to index all the books using ElasticSearch or Amazon Kendra and build a search engine.
Which approach is better in this case? Is it possible to combine both approaches to improve recommendations?
Comment: Do you have any data on how users interact with the books? Otherwise you cannot make a recommender engine.
Answer: Clusters don't help you much, in particular since most likely you'll end up with one huge cluster that contains almost everything and some small clusters that contain mostly duplicates.
So for recommendations use an actual recommender system approach such as NMF. Or use similarity search, of course, based solely on the product descriptions and not on user information.


Numbers $n$ such that $n$ plus the sum of $n$'s digits is $313$

Question: Good morning, everyone. Here is the problem I'm faced with:

The sum of the number $n$ and the digits of $n$ equals $313$. What are the possible values of $n$?

By reasoning I concluded that it has to be a $3$ digit number and by hit and trial I found $305$ as one of the answers. How would I find all possible values of $n$?
It would be great if someone could throw light on how to proceed in a mathematical way and get the values of $n$ (as opposed to brute-forcing/trial-and-error).
I tried as below:
Let our number be $xyz$, where $x,y,z$ are the digits of the number. Then we seek solutions to
$$\underbrace{100x + 10y + z}_{n} + \underbrace{x+y+z}_{n's \; digits} = 313$$
Thus, simplifying, we seek integer solutions to
$$101 x + 11 y + 2 z = 313$$
I am stuck now as to how to solve this.
Thanks to all in advance.
Answer: The greatest possible sum of digits for a positive integer less than $313$ is $20$ (from $299$) so the minimum value you need to test is $293$. The sum of digits in this range is at least $3$ ($300$) and is at least $4$ for numbers other than $300$ so the greatest number you need to test is $309$
Either you are less than $300$ when, with units digit $a$ you have $290+2a+11=313$ and $a=6$, or greater than $300$ when $300+2a+3=313$, and $a=5$.
Answer: You are on the right track with:
$$\overline{xyz}+x+y+z=101x+11y+2z=313.$$
$x\ne 1$, because otherwise $11y+2z\le 117<212$.
$x=2$, then:
$$z=\frac{111-11y}{2} \Rightarrow y=9, z=6 \Rightarrow \overline{xyz}=296.$$
Answer: $$101x+11y+2z=313$$
where $x,y,z$ are numbers between $0$ and $9$.
If $x\le 1$, then $101x+11y + 2z \le 101+11(9)+2(9)=101+13(9)=218 $
If $x=2$, then we have $$11y+2z=111$$
Since $z\le 9$, we have $$11y =111-2z \ge 93$$
Hence, we must have $y=9$. $$2z=111-11(9)=111-99=12.$$
Hence $296$ is a solution.
If $x=3$, then we have $11y+2z=10$ which forces $y=0, z=5$.
The solutions are $305$ and $296$.
Answer: Going from your final conclusion,
$$101x + 11y + 2z = 313$$
it seems sufficient to simply notice that $x,y,z \in \{0,1,2,3,...,9\}$ since the number's digits are $x,y,z$. In particular, we can eliminate further: we must have $x \in \{1,2\}$ since the maximum value of $11y+2z=117$ (when you have $y=z=9$). The least value of $11y+2z$ is obviously $0$, so with the previous we know:
$$x \in \{1,2,3\}$$
From here, it becomes more processes of elimination.

Suppose $x=1$. Then $11y+2z = 313-101 = 212$. However the maximum value noted earlier for the former expression is $117$, so the one's digit ($x$) definitely cannot be $1$.

Suppose $x=2$. Then $11y + 2z = 313 - 202 = 111$.
Try $y=9$. This yields $z=6$.
Try $y=8$, which yields $z = 11.5 > 10$, so we can immediately conclude that $z=2,y=9$ is the only solution here. We need not try more $y$'s.

Suppose $x=3$. then $11y + 2z = 313 - 303 = 10$.
As is easily deducible, this immediately implies $y=0$ and $z=5$. Thus, that would be the only solution to this case.

Thus, we end up with two solutions:
$$x=3,y=0,z=5 \implies 305 \; \text{ is a solution} $$
$$x=2,y=9,z=6 \implies 296 \; \text{ is a solution} $$
Throw in some details to show numbers with fewer than $3$ or more than $3$ digits cannot be solutions (should be pretty easy), and you have thus shown these are the only base-$10$ solutions to
$$n + s(n) = 313$$
where $s(n)$ denotes the sum of the digits of $n$.


Checking whether a line segment is above another in $\mathbb{R}^3$

Question: There are two non parallel line segments $U$ and $V$ in $\mathbb{R}^3$, each given by their two end points $u_0, u_1$ and $v_0, v_1$, such that if they are projected into $\mathbb{R}^2$ by their $x$ and $y$ coordinates, they intersect. We want to know whether the line $U$ is above $V$. More exactly, suppose their projections on $\mathbb{R}^2$ intersects at point $(x, y)$. We want to know whether the $z$ coordinates of line segment $U$ at point $(x, y)$ is larger than the $z$ coordinates of line segment $V$ at point $(x, y)$.
Assuming that $u_0, u_1, v_0, v_1$ are all lattice points, is there a way to do this that doesn't explicitly calculates the $x$, $y$ and $z$ coordinates? In order words, how to check this without floating point arithmetic?
Motivation
This comes up when I am trying to compute the 3D convex hull of the projection of a triangulation of polygon from $\mathbb{R}^2$ into $\mathbb{R}^3$ during the computation of the weighted delaunay triangulation of the set of points.
Answer: I think this condition does the job:
$$ 0 \le \det\left[\begin{matrix} v_0-u_0 & u_1-u_0 & v_1-v_0 \end{matrix}\right]
\det\left[\begin{matrix} P(u_1-u_0) & P(v_1-v_0) \end{matrix}\right] \tag{$\ast$} $$
Here $P$ is the coordinate projection onto the $xy$-plane; the matrix $\left[\begin{matrix} a & b \end{matrix}\right]$ means the matrix with vectors $a$ and $b$ as columns; the first determinant is $3\times3$ and the second is $2\times 2$.  (Note that the latter determinant is a subdeterminant of the former, so there's some opportunity to reuse computational results.)
To derive this, consider the following method of solving the problem directly by computing $x,y,z$.  First we find the intersection of the projections by solving the system
$$ P(u_0) + s(P(u_1)-P(u_0)) = P(v_0) + t(P(v_1)-P(v_0)) \tag1 $$
Then we compute the $z$ coordinates and compare them:
$$ u_{0z} + s(u_{1z}-u_{0z}) \mathrel{\stackrel{?}{\le}} v_{0z} + t(v_{1z}-v_{0z}) \tag2 $$
If you solve the system (1) using Cramer's rule and plug the resulting $s$ and $t$ into (2), you'll find that it's equivalent to ($\ast$)... assuming I haven't made some elementary error.
(Geometrically, ($\ast$) is checking the handedness of the tetrahedron formed by the four vertices.)


Mapping the function signature of the right function in a list in typescript

Question: I'm building a message formatter that has a bunch of different kinds of messages it can build. Depending on what kind of message it's building, different render functions will be called. Each of these functions can accept different parameters, or optional parameters.
I'm having trouble setting this up and having typescript understand what I'm doing.
Here's some messy code to give you an idea of what I'm after.
export enum MessageType {
  Greeting,
  Warning,
}

getFormattedMessage(messageType:MessageType, ...messageParams): string {
  const messageBuilders: {[K in MessageType]: () => string} = {
    [MessageType.Greeting]: () => 'Hi There',
    [ErrorType.Warning]: ({name}) =>
      name ? `${name} is required` : 'That thing is required',
  }

  return messageBuilders[messageType](...messageParams)
}

getFormattedMessage(MessageType.Greeting)
// output, "Hi There
getFormattedMessage(MessageType.Warning)
// output, "That thing is required"
getFormattedMessage(MessageType.Warning, {name: "A fancy hat"})
// output, "A fancy hat is required"

There are a few issues with the above code. For instance, I'm having trouble setting up the typescript signatures properly for getFormattedMessage or for messageBuilders.
I'd like to get to a point where if I type getFormattedMessage(MessageType.Warning,  into my editor, vsCode will suggest the variables that show up in the signature of the render function attached to the Warning type, and so on.
Thanks a bunch!
Answer: Here a helper identity function newMessageBuilder is used to let the compiler infer the type of messageBuilder implicitly and at the same time constraint its type's lower bound; then use Parameters<(typeof messageBuilders)[K]> to constraint the type of messageParams according to the value of messageType.
export enum MessageType {
  Greeting,
}
export enum ErrorType {
  Warning = 1,
}

function newMessageBuilder<T extends {[K in MessageType | ErrorType]: (...messageParams: any[]) => string}>(messageBuilders: T) { return messageBuilders; }
const messageBuilders = newMessageBuilder({
  [MessageType.Greeting]: () => 'Hi There',
  [ErrorType.Warning]: ({name}: {name: string}) =>
    name ? `${name} is required` : 'That thing is required',
});

function getFormattedMessage<K extends MessageType | ErrorType>(messageType: K, ...messageParams: Parameters<(typeof messageBuilders)[K]>)  {
  return (messageBuilders[messageType] as any)(...messageParams);
}

getFormattedMessage(MessageType.Greeting)
// output, "Hi There

// ERROR Argument of type '{ a: number; }' is not assignable to parameter of type '{ name: string; }'.
// Object literal may only specify known properties, and 'a' does not exist in type '{ name: string; }'.(2345)
getFormattedMessage(ErrorType.Warning, {a:1})
// output, "That thing is required"

getFormattedMessage(ErrorType.Warning, {name: "A fancy hat"})
// output, "A fancy hat is required"

There are of course still issues with the above like the (messageBuilders[messageType] as any) that I am ignoring because I found no solution leaving as an exercise for readers.
Playground Link


MySQL: WP usermeta table: get types, then names, then sort

Question: I think this is a cross tab job, but I'm not seeing it!  In the Wordpress usermeta table, the data is like this:
| userid | meta_key | meta_value
| 123    | grant    | Education

And
| userid | meta_key | meta_value
| 123    | orgname  | ABC School

I need to search the table for all grant types of, say, 'Education', and then sort the results so that the org names are alphabetical.
The net result should effectively be a data set along these lines:
| userid | grant     | orgname
| 123    | Eductaion | ABC School

How can I do that?
Thanks in advance!
Please note: these pages are not within wp itself, but are using the wp db. Thanks.
Comment: Can you explane a little more? or an example about what exacly want be your final result?
Comment: H Zalonis - I've added the third code block to show what I'd like to come out at the end. Thanks!
Comment: They are 2 tables with a foreight key userId? or you have nothing yet?
Comment: Hi - no, the first two examples above are from the same table, usermeta. The meta_key field can have any value, as can the meta_value. The userid field relates to the user table, and all of the extended info about the user is held in usermeta table and referenced by the userid field.
Comment: Yes I think I understant what do you want to do. Check if my answer helps you.
Answer: Check this if it's what you want.
<?php
$query = "SELECT userid ,meta_key, meta_value
FROM table
GROUP BY userid ";
$row = mysql_query($sql) or die(mysql_error());
$data = $array();
$i=0;
while( $res = mysql_fetch_array($row) )
{
  $data[$i] = $res;
  $i++;
}
echo "
";
for($i=0;$i<=count($data);$i+=2)
{
   echo "
";
      echo "userid 	";
      echo "".$data[$i]['meta_key']."	";
      echo "".$data[$i+1]['meta_key']."	";
    echo "
"

   $sql= "SELECT userid ,meta_key, meta_value
            FROM table
           WHERE userid = '".$data[$i]['userid']."' ";
   $row_sub = mysql_query($sql) or die(mysql_error());
   $j=0;
  while( $resSub = mysql_fetch_array($row_sub ) )
  {
    $subData[$j] = $resSub ;
    $j++;
  }

  for( $j=0;$j<=count($subData[$j]);$j+=2 )
 {
    echo "
";
      echo "".$subData[$j]['userid ']."	";
      echo "".$subData[$j]['meta_value']."	";
      echo "".$subData[$j+1]['meta_value']."	";
    echo "
"
 }
}
echo "
";
?>

Comment: Thanks Zalonis.  The code is giving me some errors, but I can see where you're going with it.  It's given me a couple of ideas which I will try out, thanks!
Answer: <?php
  $all_meta_for_user = get_user_meta( 123 );
  echo "
";

  print_r( $all_meta_for_user ); // get all meta data of a particular user
  exit;
?>

look here for more Get User Meta
Comment: Hi wordpresser - should've mentioned that the pages I'm working on are not within wp, but use data from the wp db.  Sorry, my mistake, I'll edit.


Como descrever o banco de dados de um chat com varias pessoas

Question: Que é fácil fazer uma conversa entre 2 pessoas, isso eu sei, mas e ai alguém pode citar o exemplo de como fazer uma conversa em grupo? Com um número ilimitado de pessoas.
Conversa entre 2 pessoas:
TABELA MYSQL

|   De    |     Para      |   Mensagem   |

|  User1  |     User2     |     Olá      |

Alguém tem uma ideia diferente para adicionar mais pessoas nessa conversa?
Comment: uma mensagem para todos os usuários poderia utilizar a coluna para como null por exemplo.
Answer: Ou assim:
Table:
| Channel |  who                   | message |
|  #uno   | [nick1, nick2, nick3]  |   Olá   |

Ou:
| sender | receiver                | message |
|  nick1 | [nick2, nick3, nick 4]  |   Olá   |

Ou ainda
| id | Channel | who                  |
|  0 | #uno    | [nick1, nick2, ... ] |
----------------------------------
| sender  | toChannel | message |
|  nick1  | 0         |   Olá   |

As possibilidades são, literalmente, infindas; O que tens de te preocupar é ter uma lista de receptores da mensagem, e loopar "enquanto não enviei para este, envia, caso contrário tira-o desta lista"
Comment: Gostei da terceira resposta, a vista é muito eficaz, obrigado! :)


Covariant derivative of (1,1)-tensor

Question: Suppose I have an endomorphism $J:TM \to TM$ and a connection on M. It is possible to define $\nabla_X J$ by transforming $J$ into a (1,1)-tensor and using the extension of $\nabla$ to tensors. Going back we get an endomorphism $\nabla_X J:TM \to TM$.
Is there a way to define $\nabla_X J:TM \to TM$ directly?
Comment: No, we don't get an endomorphism.
Comment: Just to clarify: Alexei is referring to your claim that $\nabla J$ is an endomorphism from $TM$ to itself. That is not true.
Comment: You're right. I was trying to say $\nabla_x J$. I'll correct it.
Answer: As was mentioned in the comments, $\nabla L$ is not a (1,1) tensor.  It is actually a (1,2) tensor.  However contracting with a vector field $X$ gives us an endomorphism $\nabla_X L$ of $TM$ which is equal to $\nabla_X \circ L - L \circ \nabla_X$.  You can check this is consistent with the definition you get when you extend $\nabla$ to $T^*M$ and then to $TM^* \otimes TM$.

Covariant derivative of (1,1)-tensor


Delete duplicate text in TextField mysql and can't make it unique

Question: I can't delete the duplicate rows, because can't set the textfield to unique, how to solve this?
Comment: Please provide considerably more information as it's unclear as to what you're asking here.
Comment: the textField in mysql how can I delete a duplicate rows?, I've tried to set it to unique, but I can't, thats what I am asking, how to do it, because I have a big table, i need to quick delete those duplicates rows, even If i create a hash_text field, those duplicates in the textField will stay anyway, how to remove them
Comment: @Hello - is there any primary key for that table? for example some auto increment value....
Comment: @Hello - please provide you table structure
Answer: Use query like this
DELETE FROM TABLE_NAME
WHERE ID NOT IN (SELECT DISTINCT ID FROM TABLE_NAME)

Answer: if you have forigen key in the table, you must change values in other tables also..
Otherwise see this links:
How to remove duplicate entries from a mysql db?
How to delete duplicate rows from a MySQL table
Remove duplicate rows in MySQL


Adding 365days or Year in SQL Query - MOODLE

Question: I am trying to create a report where we can see course completion date and the date when it will expire. Here is what I got so far:
SELECT u.firstname AS 'Firstname' , u.lastname AS 'Lastname', cat.name AS 'Organisation', c.fullname AS 'course',
DATE_FORMAT(FROM_UNIXTIME(p.timecompleted),'%Y-%m-%d') AS completed

FROM prefix_course_completions AS p

JOIN prefix_course_categories AS cat
JOIN prefix_course AS c ON p.course = c.id
JOIN prefix_user AS u ON p.userid = u.id
WHERE c.enablecompletion = 1
ORDER BY u.firstname

I'm trying to add a new column where 'completed' columns data + 365 = expiration date. I have tried so many methods like DATE_ADD/DATEADD but I still can't get it. Can you please help me. I would appreciate any suggestions and help.
Thanks in advance
Answer: This should do what you want:
DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(p.timecompleted),
                     INTERVAL 1 YEAR), '%Y-%m-%d'
           ) AS expiration_date

If you want exactly 365 days (so things are off around leap years), you can use INTERVAL 365 DAY instead.
Comment: @Nightshade I suspect you left out the comma before `DATE_FORMAT`
Comment: wow sir thanks for your fast reply. I have tried the code above but I am getting a **Query failed** message: _You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(p.timecompleted), INTERVAL 1 YEAR), '%Y-%m-%d' at line 3_

I inserted the code below the completed and also tried to use DATEADD instead of DATE_ADD but still no luck.
Comment: so dumb of me. I forgot the comma. Been taking care of my kid in hospital for the last 3 days. Thank you so much sir's for the help. Everything works fine now. Thank you! @Barmar
Comment: Thank you @gordon Linoff


Unable to dismiss CNContactViewController

Question: I'm trying to let the user create a new contact. While I've got the screen to prompt the user to put in all his details there is no navigation bar at the top(Like there is in the default Apple Contacts app). There is no way to exit the scene. I'm using the ContactUI framework in swift 2.0 and Xcode 7.3. Here's the code:
// create a new contact
    let createNewActionHandler = {(action: UIAlertAction) -> Void in
        let newContact = CNMutableContact()

        let contactPicker = CNContactViewController(forNewContact: newContact)
        contactPicker.delegate = self
        contactPicker.navigationController?.setToolbarHidden(false, animated: false)
        self.presentViewController(contactPicker, animated: true, completion: nil)

    }

Here's what I'm trying to get:
Apple Default
Here's what I have:
What I have
I'm launching the new contact view controller from an action sheet in a tab view controller. I tried embedding the tab in a Navigation view controller but to no effect. I even tried setting the setToolbarHidden property of the navController but it didn't help.
Thanks for any help. I saw the issue raised in other forums but they didn't help.
Answer: You have to embed contactViewController to UINavigationController
and Implement Delegate Methods.
let createNewActionHandler = {(action: UIAlertAction) -> Void in
    let newContact = CNMutableContact()

    let contactPicker = CNContactViewController(forNewContact: newContact)
    contactPicker.delegate = self
    let navigation = UINavigationController(rootViewController: contactPicker)
    self.presentViewController(navigation, animated: true, completion: nil)

}

//MARK: - Delegate

  func contactViewController(viewController: CNContactViewController, didCompleteWithContact contact: CNContact?) {
      viewController.dismissViewControllerAnimated(true, completion: nil)
  }

  func contactViewController(viewController: CNContactViewController, shouldPerformDefaultActionForContactProperty property: CNContactProperty) -> Bool {
      return true
  }

Answer: The view controllers must be embedded in UINavigationController and you should push or show view controller:
navigationController?.pushViewController(contactPicker, animated: true)

instead of presenting view controller
Answer: Since you are presenting contactPicker viewcontroller on top of current active controller, you will not have access to navigationbar as the view is presented fully,if you want to have button's as in Apple contact app you need to embed your presenting viewcontroller inside UINavigationController, and add left and right bar button items.
Refer the following apple sample which demonstrates the same.
https://developer.apple.com/library/ios/samplecode/iPhoneCoreDataRecipes/Listings/Classes_RecipeAddViewController_m.html
Answer: I tried all methods but none worked, So I made a custom method
extension UIBarButtonItem {
    private struct AssociatedObject {
        static var key = "action_closure_key"
    }

    var actionClosure: (()->Void)? {
        get {
            return objc_getAssociatedObject(self, &AssociatedObject.key) as? ()->Void
        }
        set {
            objc_setAssociatedObject(self, &AssociatedObject.key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            target = self
            action = #selector(didTapButton(sender:))
        }
    }
    @objc func didTapButton(sender: Any) {
        actionClosure?()
    }
}
extension UIViewController {
    func addDissmissButton(){
        let cancelButton = UIBarButtonItem.init(title: "Dismiss", style: .plain, target: self, action: nil)
        cancelButton.actionClosure = {
            self.dismiss(animated: true)
        }
        self.navigationItem.leftBarButtonItem = cancelButton
    }
}


Select verificando uma condição

Question: Preciso fazer um select onde é verificado uma condição.
Ex: Se o valor de um determinado campo for < 0 atribui a soma desse campo a coluna "PerdaGerada" caso contrario atribuir a coluna "LucroGerado".
Algo como mostrado abaixo:
SELECT TOP 10
       TBL.PRODUTO PRODUTO,
       COUNT(TBL.ID) AS QTD,

       SE TBL.VALORGANHO < = ENTAO SOMA DE VALOR GANHO VAI PRA COLUNA "PERDAGERADA"
       SE TBL.VALORGANHO > = ENTAO SOMA DE VALOR GANHO VAI PRA COLUNA "LUCROGERADO"

FROM TABELAVENDAS TBL
WHERE TBL.DATAEMISSAO BETWEEN '20150901' and '20150930'
GROUP BY TBL.PRODUTO
ORDER BY 1 DESC

Comment: Dica: use `CASE`
Comment: fiz assim ...
CASE WHEN (ACC.VALORGANHO < 0 SUM(ACC.VALORGANHO) AS PERDAGER ELSE SUM(ACC.VALORGANHO) AS ECONOMIAGER END

mais nao deu certo nao
Comment: tenta `CASE WHEN x THEN y WHEN w THEN z END AS "alias"`
Infelizmente não tem como fazer um alias dinâmico, até onde eu sei.
Comment: Não consegui desta  maneira ...
Answer: Pra chegar nesse resultado você pode usar CASE
Exemplo:
 SELECT TOP 10 TBL.PRODUTO , COUNT(TBL.ID) AS QTD ,
 SUM(CASE WHEN TBL.VALORGANHO <= 0 THEN TBL.VALORGANHO ELSE 0 END) AS PERDAGERADA ,
 SUM(CASE WHEN TBL.VALORGANHO >= 0 THEN TBL.VALORGANHO ELSE 0 END) AS lUCROGERADO FROM TABELAVENDAS TBL
    WHERE TBL.DATAEMISSAO BETWEEN '20150901' and '20150930'
    GROUP BY TBL.PRODUTO
    ORDER BY 1 DESC

Comment: Diego, muito obrigado !!! sua resposta foi precisa !! Certinho !!
Comment: @AlvaroVieira fico feliz que tenha dado certo e ajudado !

Select verificando uma condição


How to model discretised values of a continuous variable?

Question: I have some measurements--tissue swelling in response to an injury--with limited precision (mm). Thus, although the underlying phenomenon is continuous, my values are discrete. The values range between 0 and 20 mm. Many of these discretised values are zero (i.e. no measurable tissue swelling, although it might be present at a sub-mm scale).
Is it legitimate to treat the measurements as discrete and model them e.g. by the Poisson distribution, or should I stick to a continuous one? Which one makes sense for a zero-rich dataset? Maybe exponential?
Comment: Treating these as continuous could lead to bias since you do not know what value exactly it represents, maybe they all had the lower bound value or something. So maybe treating them as ordinal would be a better option.
Comment: What's the range of values in your data set?
Comment: @DoctorMilt I updated the question.
Answer: One obvious solution is to treat this as interval censored data. I.e. when you record 1 mm, you might believe that this really means the true value lies between 0.5 and 1.5 mm (similarly, 0 means 0 to 0.5 mm). That's relatively straightforward. Whether that really makes any difference to the results of any analyses you might do, is hard to predict.
Additionally, you might want to add zero-inflation, if you think there's truly zeros in your data (because many methods for interval censoring would actually assume that you basically never have an exact zero). However, this may not make too much of a difference in your analyses and the model may have trouble figuring out whether patients are in (0, 0.5) vs. exact 0 / would struggle to estimate the related parameters, unless you have something that would give the model information about how to distinguish the cases/which cases are which.


Inserir variável em valor de animate jquery

Question: Estou tentando inserir esse valor no scrollTop mas não esta retornando, algum problema?
var top = $('.sku').offset().top;

$(window).animate({
    scrollTop: top
}, 500)

Comment: Está chamando isso dentro de um `$(document).ready(function(){ ... })` ou `$(function(){ .. })`?
Comment: Em que momento está inicializando essa variavel `top`? certifique-se de que o elemento já tenha sido renderizado para pegar a posição dele, senão sempre vai retornar 0.
Comment: @BrunoRomualdo Sou meia leiga no assunto, poderia dar um exemplo ou algum documento para eu dar uma olhada?
Comment: Era isso mesmo, thanks!
Comment: Sempre que possível coloque seu `javascript` no final da tag ``, antes do fechamento dela.
Comment: Já formulo um resposta mais explicativa para futuras pesquisas.
Answer: Certifique-se de pegar a posição do elemento depois de ele ter sido renderizado, veja o exemplo:

    ... estilos e tudo mais

Teste

Como boas práticas recomenda-se colocar o javascript (inclusive os imports) no final da pagina antes do fechamento da tag , pois o navegador bloqueia a renderização até que esses scripts sejam carregados:

    ... Seu conteudo html

    // Vai carregar  js depois que a pagina for renderizada

E ainda você pode usar o document.ready do Jquery para executar um script apenas quando o documento estiver pronto:

Comment: Boa!! Ótimo!!!!
Answer: Em principio o valor deve estar a ser passado correctamente, no entanto, a animacao só parece funcionar se usares no $("html, body").
Assim
    var top = $(".sku").offset().top;
    $("html, body").animate({ scrollTop: top }, 500);

Comment: Tinha um typo, faltava o `.` no `$(".sku")`
Comment: Olá boa tarde, o problema é que esse exemplo retorna para o topo como retornasse valor 0
Comment: Opa sim! tinha colocado, mas não é o problema, é como ele nao pegasse o valor da variavel
Comment: O que retorna se fizeres `$(".sku").length`?


Link de WhatsApp não funciona em iOS

Question: Estou desenvolvendo uma landing page onde haverá um ícone com link para o WhatsApp.
Segui  esse tutorial.
http://api.whatsapp.com/send?1=pt_BR&phone=55XXXXXXXXXXX

No Android funciona perfeitamente, conforme imagem:
Porém, no iOS não funciona, quando o usuário clica no link ele é levado para a página do WhatsApp na App Store.
Existe alguma particularidade no iOS? O link precisa ser feito de forma diferente?
Answer: Estranho, eu utilizo o mesmo link de compartilhamento num site e funciona normalmente no iPhone.
Eu até pedi, agora há pouco, para uma amiga testar no iPhone dela para tirar dúvida e está tudo normal.
Por via das dúvidas, tenta utilizar a nova URL de compartilhamento do Whatsapp:
https://wa.me/<NÚMERO NO FORMATO INTERNACIONAL>
Exemplo: https://wa.me/5511999999999
Se quiser enviar uma mensagem pronta, a URL será
https://wa.me/<NÚMERO NO FORMATO INTERNACIONAL>?text=<MENSAGEM CODIFICADA PARA URL>
Exemplo: https://wa.me/5511999999999?text=OlaMundo
Outra sugestão da documentação do Whatsapp é utilizar Share Extension e UIActivityViewController.
Tenta também testar em outro aparelho iOS. Existe uma mínima possibilidade do problema ser o dispositivo.
Referências

Usando a Conversa em um Clique
I'm an iPhone developer, how can I integrate WhatsApp into my app?
Comment: Eu testei com o seguinte código https://wa.me/555499999999?text=teste e não funcionou no iPhone.
Comment: Estranho, deveria funcionar. Não funciona em nenhum iPhone ou é em um dispositivo específico? Aqui esses links funcionam normalmente. Dá uma olhada nos links que eu deixei na resposta, são da documentação oficial do Whatsapp.
Answer: Por algum motivo algo mudou na página do WhatsApp web que é o link que ele abre primeiro (isso pode ter a ver com o Safari) quando abrir a página da web antes de clicar em "enviar mensagem" araste a página para baixo come se fosse atualizar, você verá que vai aparecer a opção de "abrir no app whatapp" é só clicar ali e ele abrirá o WhatsApp na tela de envio de mensagem... Espero ter ajudado.

Link de WhatsApp não funciona em iOS


While sempre retorna o último registro em sql server

Question: Tenho um select para trazer todos os registros que foram inseridos e preciso fazer um while para percorrer este select e dar um insert em outra tabela temporária. Só que o while está trazendo sempre o último registro
O que pode estar errado?
        DECLARE @CONTADOR INT
        DECLARE @CONTADORLOOP INT = 1

        SELECT @CONTADOR = COUNT(*) FROM #tableConta

        SELECT * FROM #tableConta

        WHILE(@CONTADORLOOP IS NOT NULL AND @CONTADORLOOP <= @CONTADOR)
        BEGIN

            SELECT @EMP_VLR = EMPCOD, @PLANO_COD_RED = PLANOCODRED FROM #tableConta where PLANOCODRED = @P_PLANO_CTA_COD_RED

            PRINT @EMP_VLR
            --INSERT INTO #tableDebCred (TOTAL2, EMPCOD2, PLANOCODRED) VALUES (@VLRTOTAL2, @EMP_VLR, @PLANO_COD_RED)

                SET @CONTADORLOOP = @CONTADORLOOP  + 1

        END

    END

Comment: O que há em `@P_PLANO_CTA_COD_RED` ?
Comment: ela pega o valor declarado em uma variável ali foi 18906 como pode ver na imagem
Comment: dentro do seu while você recupera todos os registros de `#tableConta` já que seu `PLANOCODRED` é o mesmo para todas as linhas. É isto mesmo que deseja fazer ? E mais, o `Insert into` com `select` não te atende neste caso ?
Comment: como que ficaria dai? Tem algum exemplo?
Comment: Veja se atende. [Exemplo](https://stackoverflow.com/questions/25969/insert-into-values-select-from)
Answer: Se eu entendi direito acredito que um Insert com Select atenderia sua necessidade
INSERT INTO TABLEDEBCRED (TOTAL2, EMPCOD2, PLANOCODRED)
SELECT @TOTAL2, EMPCOD, PLANOCODRED FROM TABLECONTA
    WHERE PLANOCODRED = @P_PLANO_CTA_COD_RED;


How to modify field_suffix after form submit?

Question: I have a form with a custom suffix (#field_suffix) for a field. I need to change the suffix value after the form has been submitted. Which hook should I use to achieve this ?
Sample Code :
<code>$form['field_test']['#field_suffix']='Suffix-1';
</code>
Edit:
I want to show "Suffix-1" when editing form and "Suffix-2" during display of content.
Comment: Is the form using ajax?
Comment: No I'm not using ajax. I just want to show "Suffix-1" when editing form and "Suffix-2" during display of content.
Comment: "suffix 2 when display content" ??? Where is the form displayed? What is the form for? I don't understand what you are trying to achieve.
Comment: When I'm editing a content type (node/edit), my "field_test" should show "Suffix 1" as the #field_suffix. After I save the content type and view it, it should show "Suffix 2" for "field_test"
Comment: so both suffix1 and suffix2 are displayed on the edit form? But suffix1 if it is new content but suffix 2 if editing content that has been saved before?
Comment: No. Only "suffix 1" is displayed during node edit. After saving node, the "suffix 1" should be changed to "Suffix 2".
Comment: ? the form is only displayed when editing the form if this is a node edit form. How do you expect to display the suffix if you are not viewing the edit form I'm confused.
Answer: I found a solution to achieve this functionality.
<code>function hook_node_view($node, $view_mode, $langcode) {
$node->content['field_test'][0]['#markup'] = $node->content['field_test']['#items'][0]['value'].'Suffix-2';
}
</code>
Comment: Although this code achieves what I require, I'm not sure if this is the right approach. So I'm not marking this answer as accepted until I know for sure that there is no alternate method.


How do I ensure that a SOCK5-proxy is not used by malicious applications?

Question: I have created a jumphost/bastion, that will act just as that - a jumphost to certain hosts:ports.
I am aware of that I can limit users/groups with the following:
Match User Alice
   PermitOpen some.host.tld:80 another.host.tld:22 third.host.tld:443

And due some requirements, I need to be able to utilize SOCKS-proxies. This is enabled by the following:
   PermitTTY yes
   PermitTunnel yes
   AllowTcpForwarding yes

This works as expected.
However..
How do I ensure that only the application that the client specifically allowed is the only application (such as Firefox) is using the SOCK-proxy and not some random other application on the client?
Can I limit the sessions/applications using the connection on the SSH-server?
I did try with "MaxSessions 1", but sadly it does not seems to apply on SOCKS-proxies.
Comment: There's a solution here: https://serverfault.com/questions/914808/how-to-forbid-connecting-to-localhost-for-ssh-socks5-proxy - maybe it fits your needs?
Comment: https://serverfault.com/a/336091/164840
Comment: https://github.com/TooTallNate/node-socks-proxy-agent
Comment: duplicate of https://serverfault.com/questions/336067/how-can-i-setup-a-socks-proxy-over-ssh-with-password-based-authentication-on-cen/
Comment: https://stackoverflow.com/questions/6054092/how-to-add-authentication-to-a-socks5-proxy-server
Comment: I would not argue that this is a duplicate, since the question is more broad.
However, I should narrow it down be more clear about what I mean.
Comment: @Marcel can you add that into your answer below, so I can mark that as a solution? This seems indeed like the best way to do it for now.
Answer: One way of authenticating the usage of the socks5 is to have a reverse proxy with basic auth forwarding traffic to it, but you won't be able to protect it against usage by other users that can see the port in the loopback device locally. The Dynamic Port Forwarding from SSH will trust anyone with access to the machine it's listening on. But maybe, if you manage to have -D to listen to a unix domain socket, you might be able to set user+group permissions to the named pipe and have some form of security against non root users. But ssh's user manual don't mention any unix domain socket forwarding for dynamic port forwarding (-D) for socks4/5 usage. I think it's a long shot. You should trust people logged into the machine.
There's a solution here:
how to forbid connecting to localhost for ssh socks5 proxy


Python program erroring out with "maximum recursion depth exceeded while calling a python object"

Question: I have a python program that I am currently working on which is working pretty well except for the fact that I am running into "recursion depth" issues and I am not sure how to rework my program to avoid this.
my program is basically something like this in a nutshell:
def foo()
    x = 0 #

    while x != 1:
        x = (mydll.InPortB(base+1)) & 1 # this is a hardware input like a push button(on or off)
        time.sleep(0.5)

     bar = ser.readline() # input from serial source
     if len(bar) != 10:
         foo()
     ''' it continues checking "bar" using some more if statement. Finally when the
         logic is satisfied the program outputs something but still restarts foo() as
         I need the program to run endlessly but I am not sure how to fix the recursive
         nature of the program'''
      if bar = 1234567890:
          print "yay you win"
          foo()
#start
foo()

Ultimately my program works as it is but eventually will crash out with the recursion limit error so not ideal as I need this program to run endlessly but being a total newb to programming I am unsure how to fix it. I did try to split my program into two or three separate function rather than just the one but it was still exhibiting the recursion issue.
Thanks for any input. If anyone needs more code I can post it but thought the small piece should be sufficient to see where I am going. Any help would be appreciated.
Comment: You could make the arming while loop more concise this way: `while not (mydll.InPortB(base+1)) & 1: time.sleep(0.5)`
Comment: Am I misreading that, or shouldn't that `while` block run infinitely if entered?
Comment: Thanks sr2222. That helped cleanup my code a little. I had tried a few iterations and couldn't get it to work right but your suggestion worked perfectly. Thanks
Comment: @Daenyth, if you are referring to my original code then "arming" was a misprint, it should have been X instead. Copy/paste issue. :-0 If you were referring to sr2222's suggestion, it worked out perfectly.
Comment: @ouldsmobile: Your original code. You should update the question with the correct code.
Comment: @Daenyth thanks for pointing out the error, it has been corrected.
Answer: I would try this since it repeatedly calls the function at the same recursion level:
def foo()
    x = 0 #
    while arming != 1:
        x = (mydll.InPortB(base+1)) & 1 # this is a hardware input like a push button(on or off)
        time.sleep(0.5)

     bar = ser.readline() # input from serial source
     if len(bar) != 10:

     ''' it continues checking "bar" using some more if statement. Finally when the
         logic is satisfied the program outputs something but still restarts foo() as
         I need the program to run endlessly but I am not sure how to fix the recursive
         nature of the program'''
      if bar = 1234567890:
          print "yay you win"

#start
while 1:
    foo()

Comment: If I infer his logic correctly, I think he may need to pull the `if len(bar) != 10:` block out and put it in a while loop inside `while True:` with the print statement coming after the len check on bar in the main body of code.
Comment: This is the route I chose to go though I am pretty sure the other answers would have worked as well. I had to rejig a couple of my IF statements but in the end it seems like this is working well. I am going to let it run overnight to see if it runs without exiting. Thanks!!
Answer: Inside of foo just use a loop such as:
while True:

    x = 0 #
    while arming != 1:
        x = (mydll.InPortB(base+1)) & 1 # this is a hardware input like a push button(on or off)
        time.sleep(0.5)

     bar = ser.readline() # input from serial source
     if len(bar) != 10:
         # do whatever you want but don't call foo

You don't need to call foo recursively for the program to keep running. The while True will take care of that.