The estimation of Harmonic numbers

Question: I am following "Concrete Mathematics"'s treatment of Harmonic Numbers (pg. 262 onwards). They show that $\lim_{n\to\infty}\left(H_{n}-\ln n\right)=1-\frac{1}{2}\left(\zeta\left(2\right)-1\right)-\frac{1}{3}\left(\zeta\left(3\right)-1\right)-\dots$ using some beautiful arguments, and then claim the right hand side converges (and is the famous Euler's constant). However, I don't understand how they can claim it converges without further justification, which I can't find.
Indeed, they show just before that $\ln n<H_n<\ln n+1$; however, this also does not imply convergence, unless I'm missing something.
Comment: In the second edition, it's on p. 278, and they say "In fact, $\zeta(r)-1$ is approximately $1/2^r$, so this infinite series converges rather rapidly and we can compute the decimal value $\gamma=0.5772156649\ldots$". Maybe they added that as a clarification in the second edition?
Comment: No, now I see I have this as well...
Answer: I believe I have found an answer: To show that $1-\frac{1}{2}\left(\zeta\left(2\right)-1\right)-\frac{1}{3}\left(\zeta\left(3\right)-1\right)-\dots$ converges it is enough to show that $\sum_{k=2}^{\infty}\left(\zeta\left(k\right)-1\right)$ converges, but exchanging the order of summation (legal, since the series is positive) we have $\sum_{n=2}^{\infty}\left(\sum_{k=2}^{\infty}\frac{1}{n^{k}}\right)=\sum_{n=2}^{\infty}\frac{1}{n\left(n-1\right)}$ which obviously converges (the last step using geometric series formula).
Comment: To connect with the hint in the text, here's another way of doing it:
$$\zeta(r)-1=\frac{1}{2^r} + \sum_{n=3}^{\infty} \frac{1}{n^r} <\frac{1}{2^r} + \int_{2}^{\infty} \frac{dx}{x^r} = \frac{1}{2^r} \left( 1 + \frac{1}{r-1} \right) < \frac{1}{2^{r-1}}. $$

The estimation of Harmonic numbers


Como definir o tamanho de um botão em centímetros?

Question: Preciso colocar um botão com altura e largura em centímetros, onde o tamanho se mantenha caso seja acessado em resoluções de tela diferentes. Isso é possível? Se sim, como?
Answer: É impossível fazer isto. Não existe uma forma de fazer porque não há como fazer confiavelmente.
Algumas pessoas usam uma forma calculando o DPI configurado, mas isto não reproduz a real relação do monitor.
O WPF tentou fazer isto mas os resultados são imprecisos e no fundo não cumpre o que promete.
Nessa resposta no SO tem como fazer a conversão se quiser insistir, mas não fale que eu não avisei que não dá certo:
<code>int CentimeterToPixel(double centimeter) {
    double pixel = -1;
    using var g = this.CreateGraphics())
    pixel = centimeter * g.DpiY / 2.54d;
    return (int)pixel;
}
</code>
Coloquei no GitHub para referência futura.
Em geral isto nem é uma boa ideia. Cada pessoa tem uma necessidade diferente de visualização. O tamanho em centímetros pode ser bom para o papel, não para a tela.
Já usei sintaxe do C# 8.


What are some books that have works of mathematicians?

Question: I am looking for a book that have important works of mathematicians before 21st century. I am not looking for any particular mathematician but it will be nice if the matter is arranged in topic wise format, like all great works in algebra etc. I am not looking for historical or philosophical books but the original works, edited to suit modern symbols and language.
Thanks a lot.
Comment: There are some sourcebooks, perhaps some that have translations and modern notation, not sure http://bookstore.ams.org/hmath-10/
Answer: You could try "God Created the Integers: The Mathematical Breakthroughs That Changed History" by Stephen Hawking. I think it fits your description accurately, except maybe (IIRC) the modern notation part.
Comment: @JonathanRichardLombardy "IIRC" means "If I recall correctly".
Comment: What do you mean by IIRC? Anyways the book looks really amazing thanks for the suggestion.
Answer: You could try and own a book that talks about Ramanujan's lost notebook. The finders of the book laid out the assertions he made in context with contemporary mathematics. This book is the 8th listed here.


What is the Big-O performance of this algorithm and how do I solve this normally?

Question: Hello I have an algorithm that I am having trouble with finding the performance.
 i=math.ceil(n**0.5)
 while n % i != 0:
  i -= 2

Would this be O(2^n)?
Comment: what is this supposed to be solving?
Answer: I don't know what you are trying to do, but your current code will run give error cannot divide by zero for many cases for example for n=13, but if you do i-=1 in place of i-=2 then your code will work fine without any error for every n and complexity would be O(n^(1\2)).
Comment: @PadraicCunningham yeah was just about to correct that
Comment: Could you explain how you got this?  What would it be with the i -= 2 in place?
Comment: It won't loop forever as you cannot divide by 0
Comment: @church I made an edit. It will not run infinite but give error because for n=13 initially i=4 then i becomes 2 and then i becomes 0 and n%0 will give error cannot divide by zero.
Comment: @Crunch The way to get the O(n^(1/2)) is by looking at the loop. You start at i=n^(1/2) and decrease it linearly every iteration. Therefore the complexity (performance as you put it) is O(n^(1/2). Whether you decrease i by 1 or 2 doesn't impact the Big-O complexity.


Rails assets pipeline - not precompiling subdirectory

Question: In both assets/stylesheets and assets/javascripts, I have a folder called admin, which has a handful of appropriate Coffeescript and SASS files.
$ cat app/assets/javascripts/admin.js
//= require jquery
//= require jquery_ujs
//= require_tree ./admin

$ cat app/assets/stylesheets/admin.css
/*
*= require_self
*= require_tree ./admin
*/

$ cat config/application.rb | grep 'assets.paths'
config.assets.paths << "#{Rails.root}/app/assets/stylesheets/admin"
config.assets.paths << "#{Rails.root}/app/assets/javascripts/admin"

After precompiling, the admin folders (and their contents) are nowhere to be seen in public/assets.
I'm probably making a fundamental mistake here; I've done very little playing with the pipeline besides the basics of images, application.js etc.
Can anyone point out what I'm doing wrong?
Answer: From what i can see, they are manifests. By default only application.css and application.js are precompiled. Other need need to be added.
You need to add them to the production.rb environment as follows (comment is from the file itself):
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w( admin.css admin.js )

Also, you can ditch the config.assets.paths in your application.rb, because those paths are loaded by default.


Filter records with multiple columns

Question: There are 4 attributes in a table. Only one attribute can be set to Y at a time. Is there a SQL Server function to find this.
Comment: Do you want to identify records which have more than 1 set? Or do you only want to output valid records which only have 1 set?
Comment: Check this https://stackoverflow.com/questions/28717868/sql-server-select-where-any-column-contains-x. There are a couple of solutions for a similar problem.
Comment: I want to get the list of records which have more than one attribute set to Y.
Answer: You could use a concatenation trick here:
SELECT *
FROM yourTable
WHERE Attribute1 + Attribute2 + Attribute3 + Attribute4
      NOT LIKE '%Y%Y%';

But this would also match a record having N for all 4 attributes.  If you also want to insist on one Y, but not more than one Y, then use this version:
SELECT *
FROM yourTable
WHERE
    Attribute1 + Attribute2 + Attribute3 + Attribute4 LIKE '%Y%' AND
    Attribute1 + Attribute2 + Attribute3 + Attribute4
      NOT LIKE '%Y%Y%';

Answer: You can use the following boolean expression to restrict at most one "Y" value among the attributes:
IIF(Attribute1 = 'Y', 1, 0) +
IIF(Attribute2 = 'Y', 1, 0) +
IIF(Attribute3 = 'Y', 1, 0) +
IIF(Attribute4 = 'Y', 1, 0) <= 1

Comment: @sivabalanarayanan . . . `<= 1` does not meet the requirements of your question.  It is surprising you accepted this.
Comment: It is surprising that both of us happen to be looking at this hours old question at the same moment.
Comment: @GordonLinoff It works when I changed the condition to it > 1. One could have overlooked it. I accepted as I was thinking about CASE statements and IFF is a shorthand way for CASE.
Answer: If you just want to identify records as either "Valid" or "Invalid", then you could do something like this:
IF OBJECT_ID('tempdb..#Sample','U') IS NOT NULL DROP TABLE #Sample; --SELECT * FROM #Sample
CREATE TABLE #Sample (
    Attribute1 char(1) NOT NULL,
    Attribute2 char(1) NOT NULL,
    Attribute3 char(1) NOT NULL,
    Attribute4 char(1) NOT NULL
)

INSERT INTO #Sample (Attribute1, Attribute2, Attribute3, Attribute4)
VALUES ('Y','N','N','N')
    ,  ('N','Y','N','N')
    ,  ('N','N','Y','N')
    ,  ('N','N','N','Y')
    ,  ('N','N','Y','Y')

SELECT *
    , IsValid = IIF(LEN(REPLACE(CONCAT(s.Attribute1, s.Attribute2, s.Attribute3, s.Attribute4),'Y','')) >= 3, 'Valid', 'Invalid')
FROM #Sample s

Returns:
| Attribute1 | Attribute2 | Attribute3 | Attribute4 | IsValid |
|------------|------------|------------|------------|---------|
| Y          | N          | N          | N          | Valid   |
| N          | Y          | N          | N          | Valid   |
| N          | N          | Y          | N          | Valid   |
| N          | N          | N          | Y          | Valid   |
| N          | N          | Y          | Y          | Invalid |

The logic is....Take the 4 columns and combine them into a single string, so Y,N,N,N becomes YNNN. Then replace all instances of the letter 'Y' and get the length of the result. Since you know the original length was 4, now you know how many Y's were removed.
This is a classic trick for counting the number of times a string occurs in another string.
In my example, I treat zero or one Y's as valid.
Answer: Try This:
DECLARE @Attr TABLE(A1 CHAR,
A2 CHAR,
A3 CHAR,
A4 CHAR)

insert Into @Attr  VALUES('Y','N','N','N')
insert Into @Attr  VALUES('N','Y','N','N')
insert Into @Attr  VALUES('N','N','Y','N')
insert Into @Attr  VALUES('N','N','N','Y')
insert Into @Attr  VALUES('Y','N','Y','N')

SELECT * FROm @Attr

SELECT * FROM @Attr
WHERE
((A2<>'Y' AND A3<>'Y' AND A4<>'Y' ) OR
(A1<>'Y' AND A3<>'Y' AND A4<>'Y') OR
(A1<>'Y' AND A2<>'Y' AND A4<>'Y') OR
(A1<>'Y' AND A2<>'Y' AND A3<>'Y'))

Answer: In a select query (which seems sufficient for your purposes), then I would recommend:
select t.*
from t cross apply
     (select count(*) as num_ys
      from (values (attribute1), (attribute2), (attribute3), (attribute4)
           ) v(attr)
      where attr = 1
     ) v
where num_ys = 1;

The performance of apply in this case is actually quite good.  More importantly this makes it much simpler to generalize the query -- adding new attributes, or saying at least one "Y" and not more than 2 "N"s or whatever.

Filter records with multiple columns


How do I increase the size of file descriptors on mac

Question: I am getting an error from squid
WARNING! Your cache is running out of filedescriptors

What should i do in my mac to prevent this error?
Answer: I think you can use something similar to:
# sysctl -w kern.maxfiles = nr
# sysctl -w kern.maxfileperproc = nr

To make it persistent edit /etc/sysctl.conf like this
kern.maxfiles=nr
kern.maxfileperproc = nr

Later method needs reboot or reload via sysctl.
You may also need to raise the ulimit settings for regular users:
ulimit -S n nr


php imap retrieve only the oldest email

Question: Goodmorning,
I'm trying to retrieve only the oldest email that matches my imap_search.
So I need to get rid of the foreach loop.
I've already tried just removing it, but that didn't work.
code:
<?php
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = '**';
$password = '**';

/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

/* grab emails, voeg hier extra search opties in bijv: SUBJECT "wat er in het onderwerp moet staan" From "email@example.com" */
$emails = imap_search($inbox,'UNSEEN SUBJECT "Task has succeeded"');

/* if emails are returned, cycle through each... */
if($emails) {

    /* begin output var */
    $output = '';

    /* for every email... */
    if($emails as $email_number) {

        /* get information specific to this email */
        $overview = imap_fetch_overview($inbox,$email_number,0);
        $message = imap_fetchbody($inbox,$email_number,2);

        /* output the email header information */
        $output.= '
seen ? 'read' : 'unread').'">';
        $output.= ''.$overview[0]->subject.' ';
        $output.= ''.$overview[0]->from.'';
        $output.= 'on '.$overview[0]->date.'';
        $output.= '
';

        /* output the email body */
        $output.= '
'.$message.'
';
    }
    echo $output;
}

/* close the connection */
imap_close($inbox);
?>

Kind regards,
Lars Kaptein
Answer: Since imap_search returns an array, you can just use regular array functions:
$emails = imap_search($inbox,'UNSEEN SUBJECT "Task has succeeded"');
$last = array_pop($emails);
$overview = imap_fetch_overview($inbox,$last,0);
$message = imap_fetchbody($inbox,$last,2);
$output = '
seen ? 'read' : 'unread').'">';
$output.= ''.$overview[0]->subject.' ';
$output.= ''.$overview[0]->from.'';
$output.= 'on '.$overview[0]->date.'';
$output.= '
';
$output.= '
'.$message.'
';
echo $output;

Comment: i still had to use `$output = '';`
Comment: but thnx this really helped a lot :D
Comment: You're welcome. I updated the code so that the first $output has just `=`.

php imap retrieve only the oldest email


z-index does not work

Question: I have a question I am trying to use z-index to make the feel of 3D to my design but I can not see any change when I use it
my css is as follow:
 .test1
    {
        background-color:#666;
        opacity:0.4;
        width:500px;
        height:500px;
        z-index:1000px;
        position:absolute;
        top:0;
        left:0;

    }

and the fiddle link is :
http://jsfiddle.net/hminaee/a89Z4/
Can anyone tell me what is the problem?
Answer: z-index takes a number, not a measurement.
z-index : 30;

Also, it doesn't magically make anything 3D; all it does is move that box in front of any other box in the same position as it, which has a lower z-index (or is position:static;).
If you expected scaling or shearing, then you should do research on transform : rotate3d, and its ilk.
Comment: This is the answer @Hamed Minaee
Comment: Thanks,I want to use this div to cover the whole screen and show some progress bar in it and underneath is the body and I dont want to set body as an static or relative but I want this div seems different or a little bit higher so what is your suggestion  ?
Comment: @HamedMinaee the default value for ***every*** element is `position : static;`. You almost never have to type it, unless you're doing something very specific (like adding/removing a class to make a div `fixed`/`static`), and you want `fixed` to be the default...
Answer: For one, z-index should be a unitless number. (e.g. z-index : 1000; not z-index: 1000px;)
But also your jsfiddle only contains one element, so I'm not sure what you expect to happen. It seems like maybe you don't understand what z-index does. You might want to read:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index

z-index does not work


Almost tone deaf when singing

Question: I am a bassist and I try to sing, and I hope to improve my singing.
The thing is, I feel tone deaf when I'm singing live. I always shoot a little sharp or a little flat from what I should. Not enough for a semitone, but enough to be noticed.
My vocals are usually as loud as they can be on the stage monitors, and I almost never notice this on the spot. When I do, I'm always able to reasonably correct the pitch in a short time. When I listen back to my band's live recordings, however, it's pretty bad.
But I've played a fretless 6-string bass for quite some time and my intonation is pretty solid on there, so my ears can't be the main problem here.
Is there a way to improve my pitch recognition for my own voice? Or is it just a matter of improving vocal accuracy?
Comment: Are you sure it's not a monitoring issue? It can be a combination of many factors, and you should be able to hear yourself clearly during performance.
Comment: @Lyd - monitoring wise, it's far more important to be able to hear everything else that's important, to pitch from. 'Hearing me' better than everybody else tends to be a crutch that people who aren't sure of what they're doing use.
Comment: I may be well off the mark here, but it could be that everything is very loud, and that's not helping your pitch accuracy. With volume comes noise, and there's probably a lot of that going on, which makes it difficult for you to sing spot on. Especially in non-gig situations, like rehearsals, turn everything down, so the vox are well on top. Not sure if it's vox solo, or harmonising with others, but turn all instruments (inc. drums!) well down. Your voice shouldn't need to be any louder than anyone elses, and you shouldn't need to force it, which may contribute to the problem.  And - practise!
Answer: It's probably that you need practice focusing on voice intonation and accuracy.

Is there a way to improve my pitch recognition for my own voice? Or is it just a matter of improving vocal accuracy?

I think it's both.
I'd try predictive ear training, which is awesome for your voice intonation, improvisation, and general musicality. The idea is to sing an interval, chord, or scale, and then play it in your instrument to hear how well you did. In your specific case, you can focus in the intervals and melodic scenarios that you are most struggling with (recording yourself is great way of figuring this out).
In the first levels you play a random note on your instrument, and sing all the intervals you can with that note as root. After you sing an interval, check your accuracy by playing that same interval in your instrument. With some practice you should be able to sing all intervals.
Then you move on to more interesting stuff. There's an exercise called "compete the chord" where you play the root and 5th on any instrument, and you sing the 3rd to complete a major or minor chord (and as always, check your accuracy after you sing). You can do this omitting any note from a chord, and the chord can be as complex as you like.
For scales, you should be able to sing all modes of the major scale. Again, listen to any random root, and sing a mode (or all modes!) with that note as root. You can make this as hard as you want to adapt to your level. Some people start by playing one note to introduce the root, and sing the Ionian mode both ways, then when you are back to the root go up one semitone and sing the next mode (Dorian) without listening to any outside reference, and continue until you run out of modes. The exercise ends with the root of the last mode (Locrian), you check on your instrument if that last note is what you sung.
You can adapt all these to your level and to any note dynamic you can think of. Play a note, then sing a triad with that note as root, or maybe the note you play on your instrument is the 5th of a chord now, or the 3rd of harmonic minor, or anything you can think of.
Some examples of predictive ear training by Rick Beato:

And a very useful comment from that video:

Opera singer here. Don't try to "hit the notes". Notes don't like to be hit. Instead, try singing notes with a strong dental consonnant onset and then, the vowel has nowhere to go but on the right note. "D" or "T", with feeling your tongue right behind your upper teeth, then the vowel can even be "uh", as in "Duh"! Also, a strong "B" or "P" onset can help. And I promise you won't sound "all opera", unless your body is meant to.

Some examples by Aimee Nolte (don't mind the title, it's actually about predictive ear training, but through a very interesting story about her experience with jazz scales as a teacher):

If you can though, consult experienced vocal coaches and teachers. Those people know what they are doing, and can do wonders for your voice.
Comment: Para 4 - only don't use a fretless instrument to check your own voice...
Comment: @Tim Good point! Make sure your only intonation worry is your voice.
Answer: If you can play fretless bass in tune, your ear seems OK.
But as has been commented, if your monitor is all 'more me', perhaps you can't hear what you should be singing in tune WITH!
Comment: Intonation in a instrument doesn't directly or automatically translate into vocal intonation and accuracy. What we normally abstract as "ear", is a very complex collection of abilities, with different relationships among them. Both start in your mind, but successfully translating your thought into an accurate note in a fretless bass and your voice are different sets of abilities, that need separate attention.

Almost tone deaf when singing


Multiple pickerviews with multiple textfield inputviews Swift

Question: I've been searching through the forum and nothing has helped.
I am using 4 text fields in one view controller, and for each textfield, I am using a separate pickerView as the inputViews for the textFields (4pickers).
When I click on the first textField, pickerView1 successfully appears and the textfield displays the data, however when I click on the second, third and fourth textfields,the first pickerView appears.
I suspect the error lies in the inputView declarations.
And I would so appreciate it if you could help add a "done" button to the pickerView.
My code:
class ViewController1: UIViewController, UIPickerViewDelegate
{

    @IBOutlet var pickerView1: UIPickerView!
    @IBOutlet var pickerView2: UIPickerView!
    @IBOutlet var pickerView3: UIPickerView!
    @IBOutlet var pickerView4: UIPickerView!

    @IBOutlet var textField1: UITextField!
    @IBOutlet var textField2: UITextField!
    @IBOutlet var textField3: UITextField!
    @IBOutlet var textField4: UITextField!

    var hazards = ["a","b", "c"]
    var reasons = ["d", "e", "f"]
    var site = ["v","h","i","j"]
    var line = ["k", "l","m", "n"]

    override func viewDidLoad() {

        super.viewDidLoad()
        pickerView1 = UIPickerView()
        pickerView2 = UIPickerView()
        pickerView3 = UIPickerView()
        pickerView4 = UIPickerView()
        pickerView1.delegate = self
        pickerView2.delegate = self
        pickerView3.delegate = self
        pickerView4.delegate = self

        self.textField1.inputView = self.pickerView1;
        self.textField2.inputView = self.pickerView2;
        self.textField3.inputView = self.pickerView3;
        self.textField4.inputView = self.pickerView4;
    }

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int  {
        return 1
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if pickerView.tag == 0 {
            return hazards.count
        } else if pickerView.tag == 1 {
            return reasons.count
        } else if pickerView.tag == 2 {
            return  site.count
        } else if  pickerView.tag == 3 {
            return line.count
        }
        return 1
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {

        if pickerView.tag == 0 {
            return hazards[row]
        } else if pickerView.tag == 1 {
            return reasons[row]
        } else if pickerView.tag == 2 {
            return site[row]
        } else if pickerView.tag == 3 {
            return line[row]
        }

        return ""
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)  {

        if pickerView.tag == 0 {
            textField1.text = hazards[row]
        } else if pickerView.tag == 1 {
            textField2.text = reasons[row]
        } else if pickerView.tag == 2 {
            textField3.text = site[row]
        } else if pickerView.tag == 3 {
            textField4.text = line[row]
        }
    }
}

Comment: Here's a place to get started with adding a Done button: http://blog.swierczynski.net/2010/12/how-to-create-uipickerview-with-toolbar-above-it-in-ios/
Answer: You're using the picker views' tag property to decide which array is the data source for a given picker view, but you didn't set the tags initially. The tag defaults to zero, so all four picker views are showing the same data. After instantiating your picker views, add this:
pickerView1.tag = 0
pickerView2.tag = 1
pickerView3.tag = 2
pickerView4.tag = 3

Comment: I've already set the tags for the pickerviews using xcode, i'm sure they display different data as if i remove the inputview calls, and display the pickers on the page, they display different data. Also that tutorial is in objective C, which i dont understand.
Comment: Do you mean you set the tags in your storyboard? When you create new picker views (i.e., with this code: `pickerView1 = UIPickerView()`) none of that setup applies.
Comment: Thank you!!! It worked! I had the tags set in the attribute inspector but not the code.
Comment: Could you help talk me through how to convert the code in that tutorial for the done button in to swift??


Transferring default user picture field to new user picture field

Question: Drupal 7.
I have a site where users can upload a picture of themselves (default Drupal field: user picture.) This field is used in different views.
I would like to use the User Picture Field module and use the field provided by the module instead of the default Drupal user picture field.
Switching fields in the views is a simple operation and it works well with newly uploaded pictures. However, with pictures uploaded before the installation of the module, the pictures displayed are no longer the users' pictures but the default "no photo" image.
Is there a way to have the (older) photos of the default user picture field transferred to (or at least displayed by) the new field?
Thanks. :)
Answer: I think the easiest way would be to do it at the database level. Copy the old field contents into the new field.
Comment: I guess it is done be referring to the file id (fid) and you could try to replace those 1:1


jQuery .hover() performance doubts

Question: While I know some jQuery to simplify front-end manipulation programming, I also aware of some of some "best practices" to level up the performance on browser, like caching through var and always descend from ID selectors. But I have doubts about this piece of code. Could it be done better?
Preamble: This code animates several blocks inside the (already cached) selector through .hover().
The HTML is something like this:

(...)

(...)

(...)

(...)

And the jQuery to animate at hovering inside one of them:
var cached_blocks = jQuery(.block-link);

jQuery(cached_blocks).hover(function(){
    var this_block = jQuery(this),
        this_block_text = jQuery(this_block).children(div.text),
        this_block_image = jQuery(this_block).children(div.image),
        this_block_link = jQuery(this_block).children(div.link),
        this_block_link_icon = jQuery(this_block_link).children(a.icon);

    /* Animate in; show everything */
    jQuery(this_block_text).animate(..);
    jQuery(this_block_image).animate(..);
    jQuery(this_block_link).animate(..);
    jQuery(this_block_link_icon).animate(..);

}, function() {
    var this_block = jQuery(this),
        this_block_text = jQuery(this_block).children(div.text),
        this_block_image = jQuery(this_block).children(div.image),
        this_block_link = jQuery(this_block).children(div.link),
        this_block_link_icon = jQuery(this_block_link).children(a.icon);

    /* Animate out; put everything where they belong */
    jQuery(this_block_text).animate(..);
    jQuery(this_block_image).animate(..);
    jQuery(this_block_link).animate(..);
    jQuery(this_block_link_icon).animate(..);
});

I'm seeing that I am declaring variables again after hover, but I don't know any technique to not doing again. Anyway, even that way it works like a charm.
Update: Fixed Code #1
var cached_blocks = jQuery(.block-link);

jQuery(cached_blocks).on('mouseenter mouseleave', function(){
    var this_block = jQuery(this),
        this_block_text = jQuery(this_block).children(div.text),
        this_block_image = jQuery(this_block).children(div.image),
        this_block_link = jQuery(this_block).children(div.link),
        this_block_link_icon = jQuery(this_block_link).children(a.icon);

    /* Animate in; show everything */
    this_block_text.animate(e.eventType(...));
    this_block_image.animate(e.eventType(...));
    this_block_link.animate(e.eventType(...));
    this_block_link_icon.animate(e.eventType(...));
});

Note 1: Yes, i'm using cached_blocks in other part of the code.
Comment: To be fair, I don't think you'll get significant performance by caching this painstakingly. What you want to avoid is re-running queries over the entire document, or re-running the same query every time the event is triggered, compared to just once. (I.e. you want to reduce the complexity by an order of magnitude, not by a few calls over a small scope.)
Comment: `hover()` is soon [gonna be deprecated](http://bugs.jquery.com/ticket/11731). I suggest you use `on()` with both mouse events.
Comment: Well, at least the very beginning of event handler is easily optimized: why wrap `this_block` with `jQuery` call when it's already a jQuery-wrapped object? The same with most of these wrapper calls.
Comment: @elclanrs That would be this: `.on({ mouseenter: fn1, mouseleave: fn2 });`, right?
Answer: You seem to be repeating code for no good reason?
var cached_blocks = jQuery('.block-link');

cached_blocks.on('mouseenter mouseleave', function(e) {
    var this_block = jQuery(this),
        this_block_text = this_block.children('div.text'),
        this_block_image = this_block.children('div.image'),
        this_block_link = this_block.children('div.link'),
        this_block_link_icon = this_block.children('a.icon');

    this_block_text.animate({something: (e.type==='mouseenter' ? 0 : 400)});
    this_block_image.animate({top: (e.type==='mouseenter' ? 10 : 200)});
    this_block_link.animate({left: (e.type==='mouseenter' ? 300 : 40)});
    this_block_link_icon.animate({right: (e.type==='mouseenter' ? 0 : 1400)});
});

Unless you are using the variables containing the text/image/link... elements somewhere else aswell, caching them just to use with animate() on the next line is a waste of space.
Answer: I think you can bind mouseout and mouseover with the same callback closure ($element.on("mouseout mouseover", callback)), and detect which event is inside the closure with something like e.type == "mouseout".
In your code you are doing
this_block_text = jQuery(this_block).children(div.text)

and then
jQuery(this_block_text).animate(..);

why not this?
this_block_text.animate(..)

this_block_text is already a jQuery object
Comment: Also, the suggestion that @raina77ow did, relate with the final of my answer
Answer: jQuery(this_block_text).animate(..);
jQuery(this_block_image).animate(..);
jQuery(this_block_link).animate(..);
jQuery(this_block_link_icon).animate(..);

there is no need to write them as jQuery(...) because this_block_text, this_block_image etc. are already jQuery objects.
this_block_text.animate()

will run.
Also using $.() instead of jQuery() is better and cleaner.
And $('div.block-link') is faster than $('.block-link')
Answer: The thing which stands out the most in this code is how often you are calling jQuery. If you already have a jQuery object, there is no need to call jQuery again.
This:
var cached_blocks = jQuery(".block-link");
jQuery(cached_blocks).hover(...);

does the same thing as:
var cached_blocks = jQuery(".block-link");
cached_blocks.hover(...);

If you're not going to reuse cached_blocks there's not going to be any performance improvement from having it, so you could simplify the code to just:
jQuery(".block-link").hover(...);

If the elements are already on the page, I'd simplify the code down to:
var links = jQuery(".block-link");

var parts = {
    text: links.children("div.text"),
    image: links.children("div.image"),
    link: links.children("div.link"),
    icon: links.children("a.icon")
};

links.hover(function() {
    parts.text.animate(..);
    parts.image.animate(..);
    parts.link.animate(..);
    parts.icon.animate(..);
}, function() {
    parts.text.animate(..);
    parts.image.animate(..);
    parts.link.animate(..);
    parts.icon.animate(..);
});

Without knowing what sort of animations you want to do, I can't simplify it any more, but I suspect you won't need so many calls to animate either.
Comment: The problem with your code is, if I do that, every block-link is affected with the animation, instead of only happening with only one where the hover is.

jQuery .hover() performance doubts


How can create a download counter?

Question: How can tracks downloads of private files attached to nodes via the core upload or contributed filefield modules for custom content type, I created a file field and I simply want to count the number of times have been downloaded this file and display this count number in node template?
My Project purpose:

Upload a file as Admin, or any authenticated user
Store the file in a private directory (But accessible by public
users)
Allow the all people or anonymous users to download the files.

These are some details about my content type module.

Module name: My Module
Content type name: My Content
Field Type: File
Display Format: URL to file (or Generic)
Field name: field_file

I know that there are some module like:

File download count
Download Count
AJAX Download Counter

For drupal 7, but seem  none of them work in drupal 8.
Thanks for any help.
Answer: The only Drupal-centric of doing this is by making sure your content type is utilizing the Private files directory for your file field. Otherwise, downloads are served by the web server.
When private file storage is utilized, this enables Drupal as the file download gatekeeper through its /system/files/{filepath} route. When the controller for the download route is called, it evokes hook_file_download() which can be used to store your ongoing file download count.
For example a custom module could implement:
/**
 * Implements hook_file_download().
 */
function MYMDOULE_file_download($uri) {
  // @TODO: Store/Increment count for unique $uri.
}

Then reference the count when building variables for your node template:
/**
 * Implements hook_preprocess_node().
 */
function MYTHEME_preprocess_node(array &$variables) {
  if (isset($variables['node']->field_MYFILE_FIELD)) {
    $uri =  $variables['node']->field_MYFILE_FIELD->entity->getFileUri();
  } else {
    $uri = '';
  }
  // @TOOD: lookup count for $uri and inject it into
  // $variables['field_MYFILE_FIELD_count'] for display
}

Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackexchange.com/rooms/46224/discussion-on-answer-by-shawn-conn-how-can-create-a-download-counter).

How can create a download counter?


Help with tuplets

Question: Hi I have trouble with tuplets. There is a tuplet that has different note values under the same beam ( 16 th. And 8th.) There are 4 16th notes and 1 8th note at the end. There is a number 6 under the beam. I think it is a sextuplet. I don't understand how the tuplet works and how I play it. Thanks.!
Here is a pic. It is the beam where there is a 6 under
Comment: play it like a triplet where 2 of the 8th notes are divided in 16th.
Answer: OK.  You have not given us an image (which would really help) but lets try to analyse this.
So there are four 16th notes and one 8th note.  The 8th note is worth two 16th notes isn't it.  So you have a total of six 16th note lengths in all.  Same length as three 8th notes.
So you are correct that it is a sextuplet, or to think of it another way, a triplet where two of the three notes have each been further subdivided into two notes.
The whole thing should add up to the length of a quarter note.
I am going to make the assumption that the beat is a quarter note:  you need to divide this beat into three and further divide two of those three in half.
I know it sound complicated but its quite straightforward when you get it.
If it helps (and it might not, but I'll say it anyway) it is the same pattern as a bar of 3/4 where the first four notes are 8ths and the last one is a quarter.
Hope that helps
Answer: just play them like triplets whereby two of the 8th notes are divided in 16th: instead of da-da-da you  play da-daba-daba, (or daba-daba-da) ...
Comment: But there isn't 2 8th noted there is only 1 8th note. But still that is some good advice. Thanks.
Comment: the triplets of 8th notes are three 8th notes: I say: there is only one 8th note and the two others are divided in four 16th notes. That means: two 16th notes are corresponding to one 8th note. daba stands four two 16th notes = > 1/8 (da)

Help with tuplets


Python Overridden __add__ Doesn't Work for a += b

Question: I've been working on a Vector object class to allow me to solve math problems quickly using Python.
For Example:
If we set vector = Vector(1, 2, 3) and we run vector *= 2, then vector will be equal to <2, 4, 6>
The Issue: Whenever I run vector += 2, it errors saying
Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\Math\matrices.py", line 149, in <module>
    main()
  File "C:\Users\User\PycharmProjects\Math\matrices.py", line 139, in main
    vector += 2
TypeError: 'int' object is not iterable

Process finished with exit code 1

Here is my Vector class
class Vector(list):
    def __init__(self, *args):
        super().__init__()
        for arg in args:
            self.append(arg)

    def __mul__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row * other for row in self])

    def __truediv__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row / other for row in self])

    def __add__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        print(type(other))
        return Vector(*[row + other for row in self])

    def __sub__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row - other for row in self])

    def __str__(self):
        return "<" + ", ".join([str(e) for e in self]) + ">"

Here is my main function
def main():
    vector = Vector(1, 2, 3)
    vector *= 2
    print(vector)
    vector += 2
    print(vector)

What I've done to find the solution:

I've tried to do vector = vector + 2 and that works, but I would
rather understand why it's not working and be able to fix it.
I've tried googling how operator overloading works in Python
I've tried looking through operator overloading threads on StackOverflow, but I don't see any that answer my question. They're all about how a = a + b, not a += b.
I've tried using iadd, but it doesn't work.
Comment: `__iadd__` should work... You can even just write `__iadd__ = __add__`
Answer: Just add the line __iadd__ = __add__:
class Vector(list):
    def __init__(self, *args):
        super().__init__()
        for arg in args:
            self.append(arg)

    def __mul__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row * other for row in self])

    def __truediv__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row / other for row in self])

    def __add__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        print(type(other))
        return Vector(*[row + other for row in self])

    __iadd__ = __add__

    def __sub__(self, other):
        assert isinstance(other, float) or isinstance(other, int)
        return Vector(*[row - other for row in self])

    def __str__(self):
        return "<" + ", ".join([str(e) for e in self]) + ">"

vector = Vector(1, 2, 3)
vector *= 2
print(vector)
vector += 2
print(vector)

Prints:
<2, 4, 6>
<class 'int'>
<4, 6, 8>

Comment: Actually you were right, I was just running an old version of the file. THANK YOU SO MUCH!


customize oauth2 login page

Question: We are trying to do azure oauth2 authentication for our app (Using code grant flow).
As per requirement we needed to show a customized page with our own branding to the user and not the standard azure login page.
Are there any solutions available to customize oauth2 authorize endpoint login page.
Comment: https://learn.microsoft.com/en-us/azure/active-directory/customize-branding
Comment: Other than those things, no. B2C allows you to customize it more. You are using federated auth, so you can't always expect the provider to support customization, same like you can't customize Google's login page if you use Google auth.
Answer: https://learn.microsoft.com/en-us/azure/active-directory/customize-branding
Other than those things, no. B2C allows you to customize it more. You are using federated auth, so you can't always expect the provider to support customization

customize oauth2 login page


RDLC re-initializes static data in assembly

Question: I have an ASP.NET app with RDLC reports. The magic happens in a separate assembly that I reference in the main ASP app. I have some static data in this assembly, which I want to reference in my objects after they have been serialized and de-serialized by the RDLC report system.
What I have found is the static fields are re-initialized during the RDLC report run, perhaps RDLC is loading up a new copy of the assembly. Thus my objects are hitting null refs on the static data, where I am expecting the data previously set.
What's going on here? Is there a way to ensure only one copy of an assembly gets loaded?
Answer: The reason seems to be that the RDLC ReportViewer operates within a separate AppDomain, and thus does not share memory with the main app.
I spent several hours refactoring my DB classes so they could be serialized and then de-serialized, all for the benefit of RDLC, only to find that after de-serializing they were not able to assign the correct DB provider because that was sitting in a static class that RDLC cannot see because it is runs in a different AppDomain.
This is the first I've really heard about AppDomains so I was not able to search for these related questions that shed light on the problem:

Does ReportViewer run in a separate AppDomain?
.NET LocalReport / .rdlc AppDomain issues
What happens to the static data in a class if it is accessed across app domains?
Sharing data between AppDomains

I found tips on forcing the report to run in the current AppDomain, which is obsolete and requires enabling CAS, but I could not get this to work in my project (I only tried for a short while):

https://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.localreport.executereportincurrentappdomain.aspx
https://learn.microsoft.com/en-us/dotnet/framework/misc/code-access-security-policy-compatibility-and-migration

Finally, I have decided that the correct solution is not to do code gymnastics to trick ReportViewer to work with my data - but rather to provide the report with a simple POCO that serializes and de-serializes easily, and has no complicated dependencies.
This is a good reason why DB objects should be simple and easily serializable, and the business logic should be in a separate object/wrapper on top of the DB object. These complicated "God objects" of mine have been bugging me for a while now!


How do I remove  from output?

Question: I'm trying to theme the output of a Drupal 8 view to use via a token for email recipients of a YAML form. I'm on the latest Drupal 8 core release and using a Bootstrap subtheme.
I have successfully removed all of the other views markup with the following TWIG theme override templates:
views-view-fields--ts--page_1.html
views-view--ts--page_1.html
views-view-unformatted--ts--page_1.html
For some reason, I keep getting the following markup added:

I have tried using the views UI options to strip HTML and/or customize the markup output and this does nothing. I've also tried using the TWIG filters like striptags, but this either removes the entire views output (a comma separated list of email addresses) or doesn't work at all.
How do I remove
?
Answer: Okay, I figured it out. After setting the services.yml file debug to "true" and enabling comments in my Firefox console, I was able to get the theme output for the particular set of divs that was adding the unwanted markup (I tried this earlier, but I think I forgot to rename default.services.yml to services.yml).
Anyway, I found that the markup was coming from Bootstrap's container.html.TWIG template. Of course, this is one of the templates that doesn't come with override suggestions, just the hook theme_container() theme function. So I copied the default function into my [subtheme name].theme file at the top of my subtheme's directory and modified it thus to suit my needs:
<?php
// Implements hook_container().
use Drupal\Core\Template\Attribute;

function vatheme_container($variables) {

  $request = \Drupal::request();

  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
    $title = \Drupal::service('title_resolver')->getTitle($request, $route);
  }

// Special handling for form elements.
$element = $variables['element'];
 // Ensure #attributes is set.
$element += array('#attributes' => array());

        if (isset($element['#array_parents'])) {
            // Assign an html ID.

            if (!isset($element['#attributes']['id'])) {
                $element['#attributes']['id'] = $element['#id'];
            }

            // Add the 'form-wrapper' class.
            $element['#attributes']['class'][] = 'form-wrapper';
        }

        if($title == 'Contact Tech Support'){
            return $element['#children'];
        }
        else{
            return '
' . $element['#children'] . '
';
        }
}

So, that seems to do the trick. This was my first stab at doing theme work in Drupal 8 and there are a lot of not insignificant changes from Drupal 7 here, so I thought I'd go through the details of my solution. Hopefully this helps someone else out there.
Answer: The following approach is a large improvement over Sky Tonnessen's answer and was originally written up in this gist by idiazroncero as it will not negatively affect the javascript wrapper classes functionality
Copy the following into YOURTHEME/templates/form/container.html.twig
{%
  set classes = [
    has_parent ? 'js-form-wrapper',
    has_parent ? 'form-wrapper',
  ]
%}

{# Remove unnecessary
 wrapper #}
{% if attributes.hasClass('views-element-container') %}
  {{ children }}
{% else %}

{{ children }}

{% endif %}

This is the only known workaround at the theme layer, since these classes are added via a preRender function.  For a more sustainable approach, follow and help on #2721899: Move views-element-container to Twig template
Answer: If anyone stumbles here, I found this worked for me. You can override the twig in your theme.
Create this twig here: YOUR_THEME/templates/form/container.html.twig
In the twig file just put:
{{ children }}
Comment: Very very bad approach.
container.html.twig wrapper has important attributes in some places, and some functionality might not work. Been there, believe me..

How do I remove  from output?


Numerical Analysis.

Question: The problem says:

Apply Euler's method with $h=1/4$ to the I.V.P
  \begin{align}
y'_1&=-y_1-y_2,\\
y'_2&=y_1-y_2\end{align}
  in $[0,1]$ with $y_1(0)=1$, $y_2(0)=0$
Verify that $y_1(t)=e^{-t} \cos(t)$ and $y_2(t)=e^{-t}\sin(t)$ is the exact solution.
Find the Global Truncations errors of $y_1$ and $y_2$ in $t=1$

For Euler's method I computed:
\begin{align}
w_{0,1}&=1& &\to& w_{j+1,1}&=1+1/4(-1-0)=3/4\\
w_{0,2}&=0& &\to& w_{j+1,2}&=0+1/4(1-0)=1/4
\end{align}
To check that $y_1$ and $y_2$ are solutions is trivial.
The problem I'm stuck with is to find the Global T. Errors, so if if you can help me with that I'd be grateful.
Also if you noticed any mistake in my procedure, please let me know.
Comment: There is context missing. What is the global truncation error. Are you to find or approximate a constant $C$ so that the global error is approximately $Ch$ or just the difference of your approximation to the exact solution?
Comment: Please add the additional steps, at the moment you only have the step for $j=0$, you need also to compute the steps $j=1,2,3$.
Comment: Sorry, Sauer Numerical Analysis defines the Global Truncation Error: $g_i=|w_i-y_i|$ and Local Truncation Error or one-step error: $e_{i+1}=|w_{i+1}-z(t_{i+1})|$
Answer: Just compute the values, to have something to compare to, compute also values for smaller step sizes.
from math import exp, cos, sin

def y1sol(t): return exp(-t)*cos(t)
def y2sol(t): return exp(-t)*sin(t)

def Euler(N):
    ''' print values at k/4 with N Euler steps in between '''
    h = 0.25/N
    t, y1, y2 = 0.0, 1.0, 0.0
    result = "N=%4d: "%N
    for k in range(4):
        for j in range(N):
            y1, y2 = y1 + h*(-y1-y2), y2+h*(y1-y2)
        t += 0.25
        result += "y(%4.2f) = (%10.7f, %10.7f), err = (%8.3e, %8.3e);  "%(t, y1, y2, y1-y1sol(t), y2-y2sol(t))
    print result

for N in [1,10,100]: Euler(N)

with results
N=   1: y(0.25) = ( 0.7500000,  0.2500000), err = (-4.590e-03, 5.732e-02);  y(0.50) = ( 0.5000000,  0.3750000), err = (-3.228e-02, 8.421e-02);  y(0.75) = ( 0.2812500,  0.4062500), err = (-6.438e-02, 8.427e-02);  y(1.00) = ( 0.1093750,  0.3750000), err = (-8.939e-02, 6.544e-02);
N=  10: y(0.25) = ( 0.7534317,  0.1974906), err = (-1.158e-03, 4.812e-03);  y(0.50) = ( 0.5286568,  0.2975913), err = (-3.624e-03, 6.805e-03);  y(0.75) = ( 0.3395353,  0.3286195), err = (-6.090e-03, 6.636e-03);  y(1.00) = ( 0.1909175,  0.3146473), err = (-7.849e-03, 5.087e-03);
N= 100: y(0.25) = ( 0.7544698,  0.1931510), err = (-1.200e-04, 4.726e-04);  y(0.50) = ( 0.5319173,  0.2914531), err = (-3.634e-04, 6.668e-04);  y(0.75) = ( 0.3450211,  0.3226329), err = (-6.043e-04, 6.496e-04);  y(1.00) = ( 0.1979911,  0.3100579), err = (-7.750e-04, 4.981e-04);

The error progression very neatly demonstrates the convergence/global error order 1.

Numerical Analysis.


Is it possible to have a lower AIC value for the smaller of two nested models?

Question: I am testing the parallel lines assumption of an ordered probit model by running a likelihood-ratio test against a model where the coefficients can vary for each step of the ordinal response variable.
As far as I understand the underlying concept, the ordered probit model can be considered as nested into the latter one by restricting all coefficients belonging the same independent variable to be equal.
Now it turns out that the likelihood-ratio test gives a p-value of 0.014, indicating that the latter model is a significant improvement over the ordered probit model and the parallel lines assumption therefore fails, wheareas the AIC value is lower (difference of 9) for the ordered probit model, indicating that the ordered probit model is preferable.
Since the likelihood-ratio statistic and the AIC seem to be generated similarly, I am wondering if and why these contradicting results are plausible?
Thanks in advance for any help
Markus
Comment: LR result --> the restrictions do not hold in population. AIC result --> the restrictions reduce the estimation imprecision so greatly that even if they do not hold, they help predict outcomes better due to the reduced estimation imprecision.
Answer: Ok, think the math is fine (having a difference of 28 degrees of freedom (DF)):
$ \Delta AIC = AIC_S - AIC_B = -2 log \mathcal{L}(\hat{\theta})_S + 2 DF_S -(-2 log \mathcal{L}{(\hat{\theta})}_B + 2 DF_B) = Test Statistic - 2\Delta DF = 47 - 56 = -9$
and $p=Pr(\chi^2_{28}>47)=0.014.$
The interpretation remains still unclear though.


Como o Git identifica a alteração de um arquivo?

Question: Cenário exemplo
Tenho a pasta projetos no servidor.
Em minha máquina local, onde tenho o Git, criei uma pasta empresa, onde copiei todos os arquivos da pasta projetos do servidor.
Fiz o add, commit e push de tudo, para o GitLab.
Dúvidas

Se eu alterar um arquivo no servidor, copiar esse arquivo, e jogar na pasta empresa da minha máquina, o Git vai identificar que foi modificado?

Pela data de modificação ou pelo conteúdo do arquivo?

Dessa forma: copiando do servidor e colando na máquina local para fazer o push, não teria problema algum, correto!?

(sim, entendo que o mais correto seria ter o Git no servidor, mas a pergunta é nesse cenário específico, para quem não tem como ter o Git no servidor)
Answer: Você copiar um arquivo de algum lugar ou editar o arquivo no seu repositório dá na mesma, alteração é alteração não importa como ela foi feita.
Geralmente o Git pega metadados do arquivo para identificar, então o timestamp da modificação é usado. Em alguns casos ele pode fazer algo mais complexo até para evitar condições de corrida. E até onde eu sei é detalhe de implementação. É curioso saber, porém não deve confiar nesta informação para alguma atividade que dependa disso.
Então se copiar com horário mais antigo ele pode não conseguir identificar que foi alterado, depende da forma que vai copiar para saber se o horário será alterado ou não no momento da cópia.
O Git funciona se tudo estiver dentro da normalidade, se fizer brincadeiras ou uso anormal do sistema de arquivo ele pode entrar em parafuso :)


Como colocar imagem no background do Wordpress

Question: Estou criando um template no wordpress, só que agora não estou conseguindo colocar uma imagem de background no fundo do site :

Eu consegui inserir a cor dando um id="bg" pro body, pois quando tentei apenas pegar o elemento body, o css do wordpress reescrevia o meu e então não era possível alterar a cor.
#bg {
    background-color: #f2f2f2;
}

só que quando tento colocar uma imagem como background nada acontece(o diretório está correto.).
#bg {
    background-color: #f2f2f2;
    background-image: url('/assets/images/bg/orange.png');
}

Comment: background-image: url('/assets/images/bg/orange.png') !important; faz o teste...
Comment: já tentei com !important tb e sem sucesso :/
Comment: coloca o estilo direto na tag html, se funcionar o path está certo e tem algum estilo se sobrepondo se não funcionar o path está errado....ex:
Comment: o caminho pra imagem está correto?
Comment: Amigo, de uma olhada na aba netwrok do console dev do browser para ver a ordem de carregamento dos arquivos css.
Comment: Olá! Você pode enviar um link com o código ou copiar o código aqui? Assim ficar mais fácil de ajudar. Obrigada!
Answer: Esses links baseados na raiz podem ser um pouco complicados no wordpress... mas vou tentar explicar:
vc tem o diretório base do WP:
wp-content
wp-includes
wp-admin
*vários arquivos

agora olhe pra url de cada página do wordpress do seu site:
home = www.meusite.com.br/
página1 = www.meusite.com.br/pagina1/
sub página = www.meusite.com.br/página1/subpágina/

se vc se basea na home do seu site... uma opção é:
no diretório base do wordpress, criar uma pasta img, colocar a imagem ali.
Ai no CSS da home ou da página1 vc acrescenta:
#bg {
background-image: url('./img/imagem-de-fundo.png');
}

Porém, a partir de outras páginas, como a sub-página, vc precisa de:
#bg {
background-image: url('../img/imagem-de-fundo.png');
}

repare o ../, o que quer dizer "no diretório pai do qual me encontro", enquanto ./ diz "no diretório em que me encontro".
uma dica para agilizar e botar tudo num só arquivo de CSS:
veja o id de toda página que não seja uma sub-página:
home = 1, página1 = 2, páginaA = 3.....
e acrescente isso:
#bg {
background-image: url('../img/imagem-de-fundo.png');
}
body.page-id-1 #bg, body.page-id-2 #bg, body.page-id-3 #bg {
background-image: url('./img/imagem-de-fundo.png');
}

para cada id de página base, vc adiciona um body.page-id-x #bg, assim ele vai encontrar o caminho correto pras imagens :)
claro q é uma espécie de gambiarra, outra forma talvez seria com algum plugin mais inteligente.
Mas seu o seu site se basea em meia duzia de páginas principais e até uma tonelada de sub-páginas, vc não deveria ter problemas seguindo esse método.
EDIT:
algumas propriedades que podem te ajudar a fazer o setup da sua imagem de fundo:
http://www.w3schools.com/css/css_background.asp


Random Variable with IID always Gaussian?

Question: Is there a case when we assume a random variable $\epsilon$ to be IID and assume its distribution is not gaussian?
Comment: The description i.i.d. applies to *sets* of random variables, not a single random variable. It means the variables are independent and identically distributed. It doesn't imply any particular form for the distributions (Gaussian or otherwise). For example, a series of coin flips would be modeled as a set of i.i.d. Bernoulli variables.
Comment: Welcome to CV! What kind of answer are you looking for? Different distributions have different logical substantiations. While approximate normality can often be argued for, there are few examples where it does makes sense to assume exact normality.
Comment: Thank you Frans. I'm actually curious let's say in the domain of machine learning, is there a case where we assume that the errors follows a distribution other than gaussian?
Comment: Are you familiar with the generalized linear model? For example, for counts you assume a discrete, non-negative error distribution (Poisson, negative binomial), for ratios you assume a binomial error distribution, for time between events you assume a non-negative continuous distribution (exponential, Weibull).
Comment: It happens may times that we assume that the distribution of e is not Gaussian: every time that empirically and/or theoretically that variable is better described by another pdf. For example (but this is just an example!), it may happen that some residuals are skewed (so asymmetric), therefore you want to take into account that asymmetry that is not of a normal. Or that those residuals have fatter/thinner tails than a normal. It depends on the application, and the specific random variable that you are modeling. Many times, it will just be the empirical evidence to suggest a proxy for the pdf.
Comment: Makes more sense now. Thanks everyone.
Comment: Generally it's more productive to think of models for conditional distributions rather than for a mean plus an error term. In that framework, you might like to look into generalized linear models and at survival models which are most typically models for non-Gaussian conditional responses.
Answer: Since you call it $\epsilon$, I assume you mean an error term in some kind of regression. In that case, imagine a classifier that inputs photographs and outputs the classification of dog or cat. The classifier makes some guess, based on the photo. Then there is some error term. Some photos of dogs just look like cat photos, and some cat photos look like dog photos.
Those error terms have Bernoulli distributions, so they are not Gaussian, but I am as content to consider each error independent of the others with an equal chance of making a mistake for each classification, so the error terms are iid.
Comment: Thank you Dave. This is exactly what i'm curious about. Im going over Stanford's CS229. Thanks again.
Answer: IID random variables are not always Gaussian
The acronym IID means "independent and identically distributed".  It refers to a property of a sequence of random variables, whereby those random variables are mutually independent, with a common marginal distribution.  If the sequence $\epsilon_1, \epsilon_2, \epsilon_3, ... \sim \text{IID Dist}$ then we have:
$$\mathbb{P}(\epsilon_1 \leqslant e_1, \epsilon_2 \leqslant e_2, ... , \epsilon_n \leqslant e_n) = \prod_{i=1}^n F(e_i),$$
where $F$ is the (common) marginal distribution function for each of the random variables in the sequence.  The distribution function $F$ can be from a Gaussian distribution, or it can be from any other distribution.  There are various contexts in which we use models with IID Gaussian error terms, and in other models, we might use IID error terms that are not Gaussian.  The latter are common in financial models, where the analyst generally wants to have fat tails in the distribution, in order to avoid underestimating the probability of extreme events.


Android getDir() with MODE_WORLD_WRITEABLE does not work

Question: I want to be able to edit a file stored in the app internal memory accessible via Context.getDir() with any available external text editor by launching Intent.ACTION_VIEW with type "text/plain" and the file URI as the argument. While external editors work well with files on the sdcard, they are not able to access files under Context.getDir().
I am invoking getDir() as Context.getDir("data", Context.MODE_WORLD_WRITEABLE) but I still get access denied error when passing the URI to external editors via the intent.
According to the docs passing MODE_WORLD_WRITEABLE to getDir() should be sufficient to enable other apps access and modify the file but this does not seem to be the case. Or am I missing something?
So the question is how to enable other apps to modify specific files under /data/data/app.package/ without creating a copy of the file on sdcard or resorting to root super powers?
Answer: You can create your own API to achieve that.
For example, you create your own library and which will access your internal file and other application will access that library. You can even use broadcast receiver or other means you feel right for this purpose.
Alternatively you can design a content provider for that too.
Another way would be if you create file using these command Context.getExternalCacheDir()  or Context.getExternalFilesDir(type), file will be created on SD card which you will be able to access using a direct path.
Comment: My question is primarily about why `MODE_WORLD_WRITEABLE` does not work as expected.


Azure Python Function: Underscore are not working in routes

Question: Hello i am creating an "Azure Python Function" with an POST/GET route in the UNC path like http://localhost:7071/api/indicator/sjz_jb_1. I create therefore the following code :
function.json
In the previous version I used {indicator:alpa?}  based on https://learn.microsoft.com/nl-nl/azure/azure-functions/functions-bindings-http-webhook-trigger?tabs=python#customize-the-http-endpoint. But with the alfa datatype the underscores are not working. After searching on the internet I found the stackoverflow post  Underscore in URL not working with attribute routing it was based on c# but the code was still working but still result in a page not found.
{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ],
      "route": "indicator/{indicator:regex(^[a-zA-Z_]+$)}"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    }
  ]
}

init.py
import logging
import json
import azure.functions as func
from shared_code.Metadata import Visualisatieportal_indicatoren

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    ind = req.route_params.get('indicator')
    logging.info(ind)
    indicator1 = Visualisatieportal_indicatoren.getVisualisatieportal_indicatoren(ind)
    result = json.dumps(indicator1.__dict__)
    return func.HttpResponse(str(id))

My question is, what do I need to change so the so underscores can support in the route of the endpoints.
Manny thanks
Erik
Comment: Try this regex `/^\w+$/` where `\w` is equivalent to `[A-Za-z0-9_]`
Comment: Thanks for the reply!   Should the route then be  "route": "indicator/{indicator:regex(/^\w+$/)?}" ?
Comment: Yes, Give a try!
Comment: That don't work page not found error
Answer:
My question is, what do I need to change so the so underscores can
support in the route of the endpoints.

One of the workaround could solve the above issue,
To use underscore you can try with the below :
 "route": "indicator/{indicator:regex(^[a-zA-Z0-9_]*$)}"

Also Based on this MS DOC we can not use following attribute in python function except c# & java.


In Cytoscape.js how can I trigger a node to redraw after its data changes?

Question: Does anyone know how to trigger a node to redraw?  I've got a case where the underlying data object updates its 'label' property and the only ways I can trigger cytoscape to redraw the labels are;

Call some combination of .selectify() then .unselectify() on the node.
Replace the label using .data('label', ...) - I actually replace it with itself.

Both of these feel a bit hacky and I presume I'm missing something obvious in the API.  Can anyone help?
Thanks,
Ryan.
Answer: You don't update anything in the data you provide to Cytoscape without using the Cytoscape APIs.
If you do node.data().foo.bar = 'baz', Cytoscape has no idea you've changed anything.
If you do node.data('foo.bar', 'baz'), Cytoscape knows you've altered the model.
Like most apps, your app probably has some model in a higher layer than Cytoscape.  So just update Cytoscape with a JSON representation of the model when your true model changes.  Assuming your model uses event emitters, just do something like modelObj.on('change', function(){ this.node.data( this.json() ) }).


Android. No Launcher Activity found

Question: I keep getting this message when trying to run the emulator, even though I've put the launcher activity in my manifest.
Does anyone have an idea what I'm doing wrong?
<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.libsdl.app"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="12"
    android:targetSdkVersion="19" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
        android:name="org.libsdl.app.SDLActivity"
        android:label="@string/app_name" >

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

Resolved: After some more mucking around in my files, I found that there were multiple AndroidManifest.mk files and I had put the activity in the wrong one. (I had this in the mk file located in the bin folder, instead of the one in root.)
Comment: Clean and build project and try again to run project and if it is not work than restart your eclipse and try again to run app.
Answer: I was having this same issue, and the OP's edit at the bottom of the post was what fixed it. (I would have upvoted, but I do not have any reputation points at this time).
To clarify for anyone in the future: it appears that Eclipse will automatically create a duplicate of the AndroidManifest.xml in the bin directory. This copy is automatically generated off of the one you are supposed to edit on the root directory.
If you edit the manifest in the bin directory, Eclipse will not give you any warning that you are editing the wrong file. You can even save to it, and run validate to ensure that there are no errors. When you run the program, it will actually be overwritten, but for some reason Eclipse tends not to prompt you that the contents have been overridden while you still have the file open.

Android. No Launcher Activity found


Prove that $n!^{\frac{1}{n}}$ is unbounded

Question: I would like to show that $n!^{\frac{1}{n}}$ is unbounded.  I cannot seem to find a $k(M)$ s.t. $k!^{\frac{1}{k}}>M$ for any $M\in \mathbb{R}$.
Answer: We have
$$
n! = n \cdots (n/2) \cdots 1 \ge (n/2)^{n/2}
$$
Therefore,
$$
({n!})^{1/n} \ge n^{1/2} = \sqrt{n}\to \infty
$$
Comment: See also https://math.stackexchange.com/a/2422708/589.
Answer: Consider
$$A_n=(n!)^{\frac{1}{n}}\implies \log(A_n)={\frac{1}{n}}\log(n!)$$ Now, use Stirling approximation $$\log(n!)=n (\log (n)-1)+\frac{1}{2} \left(\log (2 \pi )+\log
   \left({n}\right)\right)+\frac{1}{12
   n}+O\left(\frac{1}{n^3}\right)$$ which makes $$\log(A_n)=\log (n)-1+O\left(\frac{1}{n}\right)\implies A_n=e^{\log(A_n)} \sim \frac n e+\frac{\log(2\pi n)}{2e}$$
For $n=10$, the "exact" value is $\approx 4.52873$ while the above approximation gives $\approx 4.44039$.


The fundamental group of the Möbius strip

Question: What is the fundamental group of the Möbius strip?
Is it given by $\{-1,1\}$ as the lemma of Synge supposes, or am I wrong and it does not apply there?
Answer: The moebius strip is homotopy-equivalent to the circle, so has the same fundamental group which is $\mathbb Z$.
Comment: Synge only applies if you have a compact manifold with no boundary and positive curvature.  The Mobius band has a boundary (or is not compact), and has no (complete) metric of positive curvature.
Comment: Thank you so so far.So why does the lemma of Synge not apply here? It says that a manifold in even dimension has fundamental group {-1,1}, if it is not orientable.
Comment: Thank you! That helped a lot!
Answer: It is $\mathbb{Z}$. You can prove it via seeing the Möbius strip as a quotient of a square , with sides identified properly. Draw a diagonal dividing this square, and show that the Möbius strip deformation retracts onto this circle .
Comment: Instead of the diagonal, you could use the line through the center of the square and parallel to the unidentified edges.
Answer: The fundamental group of the moebius strip is $\{a,b|a^2=b^2\}$.
Cf. http://www2.math.ou.edu/~forester/5863S14/fsol.pdf
Comment: That is actually the fundamental group of the Klein bottle, although it can be constructed using Mobius bands.


UISplitViewController's detail view suddently stopped being pushed up when keyboard appears

Question: Exactly what the title says. The problem is that at first it was behaving correctly, then I did something with rotation/orientation, and it started to behave this way:
https://www.youtube.com/watch?v=M4rcB8lzcpU
Now I restored the rotation thing and it still misbehaves. Question is: why?
Comment: You have to put your code and not a video link for how it acts!Put some code to understnad what have you done.
Comment: Up until now it behaved correctly. Then I changed the shouldAutorotateToInterfaceOrientation methods to only allow for landscape, and it started to misbehave. Restored them to allow all orientations, and it kept misbehaving.
Answer: You have to resize your DetailViewController scrollview, when keyboard appears. So that it will show you the textField appears to you. You have to add your resize code in textFieldBeginEditing: method and have to resize for old behaviour in textFieldEndEditing: method.
Comment: Here's what baffles me: if I make a new application using the Master-Detail template, make the detail view a UITableViewController, and I put a text field so that it certainly gets hidden by the keyboard, when the keyboard appears the tableview gets correctly managed by the system to move the text field above the keyboard.


Finding taylor series in Real Analysis

Question: In the following question I am trying to find the Taylor series for,
$$f(x)=x^3\sin(x^2)$$
centered at $x=0$.
My first thought was to find the Taylor series for $\sin x$ then derive it to get my series I wanted but I am not quite sure how to do that.
I worked out the Taylor series for $f(x)=\sin(x)$ centered at $x=0$ and got,
$f(x)=\sin x, f(0)=0$
$f'(x)=\cos x, f'(0)=1$
$f"(x)=-\sin x, f''(0)=0$
$f'''(x)=-\cos x, f'''(0)=-1$
$f''''(x)=\sin x, f''''(0)=0$
So the Taylor series for $\sin x$ centered at $x=0$ is,
$\sum_{n=0}^{\infty}(-1)^n\frac{x^{2n+1}}{(2n+1)!}=x-\frac{x^3}{3!}+\frac{x^5}{5!}-\frac{x^7}{7!}...$
But how do I use this to find the Taylor series for $f(x)=x^3\sin(x^2)$
Answer: You can find the Taylor series for $\sin(x^2)$ by plugging $x^2$ into the Taylor series for $\sin$. So $\sin(x^2) = x^2-x^6/3!+x^{10}/5!\ldots.$ Then multiply each term by $x^3$ to get the series for $x^3\sin(x^2).$
Comment: so $x^3\sin(x^2) = x^5-x^9/3!+x^{13}/5!\ldots.$
Comment: @user905 yes that's right
Answer: We have
$$\sin x=\sum_{n=0}^{\infty}(-1)^n\frac{x^{2n+1}}{(2n+1)!}=x-\frac{x^3}{3!}+\frac{x^5}{5!}-\frac{x^7}{7!}...\tag 1$$
This series converges for all $x$ (just use the Ratio Test to verify it). Thus, replacing $x$ by $x^2$ in $(1)$ we get
$$\sin (x^2)=\sum_{n=0}^{\infty}(-1)^n\frac{x^{2{(2n+1)}}}{(2n+1)!}=x^2-\frac{x^6}{3!}+\frac{x^{10}}{5!}-\frac{x^{14}}{7!}...\tag 2$$ Then multiply $x^3$ to $(2)$ we get
$$x^3\sin (x^2)=\sum_{n=0}^{\infty}(-1)^nx^3\frac{x^{2{(2n+1)}}}{(2n+1)!}=x^5-\frac{x^9}{3!}+\frac{x^{13}}{5!}-\frac{x^{17}}{7!}...\tag 3$$ Hence,
$$x^3\sin (x^2)=\sum_{n=0}^{\infty}(-1)^n\frac{x^{4n+5}}{(2n+1)!}=x^5-\frac{x^9}{3!}+\frac{x^{13}}{5!}-\frac{x^{17}}{7!}...\tag 4$$
Answer: HINT:
$$\sin(x^2)=\sum_{k=0}^\infty(-1)^k\frac{x^{2(2k+1)}}{(2k+1)!}$$
Comment: so so $x^3\sin(x^2) = x^5-x^9/3!+x^{13}/5!\ldots.$, but how do i put that in the form that you have?
Comment: @Masacrosso would $$x^3\sin(x^2)=\sum_{n=0}^\infty\frac{(-1)^nx^{4n+5}}{(2n+1)!}$$ be the answer?
Comment: @user905 Yes, that is correct.

Finding taylor series in Real Analysis


Array stores 2 values in one "place"

Question: When I start my program I cannot insert only one number as "number 1" but two.
#include <stdio.h>
#include <stdlib.h>

int main() {
    int sum = 0;
    int array[5] = {};
    for(int i = 0; i < 5; i++) {
        printf("Insert number %d \n", i+1);
        scanf("%d%", &array[i]);
    }
    for(int i = 0; i < 5; i++){
        sum = sum + array[i];
    }

    printf("Sum is %d \n", sum);
    return 0;
}

Comment: I recommend compiling with the `-Werror` flag, which turns compiler warnings into compiler errors. A lot of unexpected behavior can occur in C if you ignore compiler warnings.
Comment: Thanks Im new to C(switching from C++).
Comment: It might also help you in the long-run to use proper indentation so that it's harder to get confused on which closing brackets `}` close what.
Comment: @Wamadeahama and `-Wall` and `-Wextra` to actually get diagnostics...
Answer: Remove the second % in
scanf("%d%", &array[i]);

to be
scanf("%d", &array[i]);

Array stores 2 values in one "place"


Hanoi Algorithm With Different Nodes

Question: http://en.wikipedia.org/wiki/Tower_of_Hanoi
I need help developing a Hanoi algorithm which follows the same rules as the standard game, however the nodes that are transversed is different. In this graph Nodes represent a peg in the Hanoi algorithm. The algorithm must account for an unknown number of disks aka "n".
Given a Graph: G = {V,E}
Where V={Start,Node1,Node2,Node3,Node4,End}
Where E={(Start,Node1),(Node1,Node2),(Node2,Node3),(Node3,Node4),(Node4,End),(Node4,Node1)}

Note: The edges above are one directional. Example: You can move from node1 to node2 but you cannot move from node1 to node4
Using the elements of recursion, create an algorithm that solves the above Hanoi game using the graph above. What is the time complexity? The original Hanoi game has a complexity of: (2^n)-1
Comment: What are these nodes? Do they represent positions of the disks on the pegs? The original Hanoi game has a complexity of $2^n-1$ not as you stated.
Comment: No, the nodes represent pegs. The variable n represents the number of disks. The algorithm must account for all "n" integers given the limited number of nodes "aka" pegs.
Comment: Thanks for the correction regarding the time complexity. :)
Comment: There's some kind of mixup between ToH and the Graph that you're defining. You can think of a solution to ToH as defining a path in the state space of nodes. Now that you've given a graph, why don't you just ask for a path from start to end?
Comment: A path from start to end is only good for when the number of disks is known. A recursive algorithm on the other hand will solve the problem for a different # of disks.
Comment: You lost me, completely ;-(
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/16727/discussion-between-ganesh-and-user127662).
Answer: You can just move the whole stack from Start to 1 to 4 to End in the usual way, using $3(2^n-1)$ steps, so that is an upper bound.  Even without nodes 2 and 3 you have additional freedom.  You can move the whole stack to node 1 $(2^n-1$ moves), then move all but the last back to start $(2^{n-1}-1$ moves), then move the bottom all the way ($2$ moves).  This leads to a recursion $T(n+1)=(2^{n+1}-1)+(2^n-1)+2+T(n)$, but that is no better.  Another approach is to move $m$ disks to node $2$ using $2(2^m-1)$ moves, then move the remaining to 1,4,End using $3(2^{n-m}-1)$ moves, then move the $m$ disks to end using $3(2^m-1)$ moves.  This is a total of $5(2^m-1)+3(2^{n-m}-1)$ moves.  We want $5 \cdot 2^m \approx 3\cdot 2^{n-m}$ or $m+\log_2 5\approx (n-m)+\log_2 3, m \approx \frac 12(n+ \log_2 3-\log_2 5)$.  Ignoring the two logs, we get $8(2^{\frac n2}-1)$ total moves.  I don't know if there is a better strategy.
Comment: Problem, I forgot to address. In the list of Edges they are one directional. You cannot move from Node1 to Node4
Comment: Then I don't think you can do the problem at all for reasonably large $n$.  You will get stuck.  Note that in the usual tower of Hanoi the edges are bidirectional
Comment: Interesting... Well I really only need to solve between 1 to 10 anyway.
Comment: I don't think you can do more than three.  The first disk moves to 3, the second to 2, the third plays through.  If you have a fourth you are done.
Comment: Perhaps you might of drawn the graph wrong? I've updated the original post with the graph.
Comment: Thanks for the help by the way. My professor assigned this problem on the first day of class and it's blowing my mind.
Comment: The drawing is exactly what I was seeing.  I think the statement that more than three disks cannot be moved to end is correct.

Hanoi Algorithm With Different Nodes


Show Google Analytics 30 Day traffic on Highcharts.js

Question: I am building a custom WordPress Google Analytics plugin that will add a /stats page to every page on the site.  It will pull the data using the Google Analytics API and display several different stats.
One of those stats is the Page Visitors for the past 30 days and I would like to show it on a chart/graph using HighCharts.js
I took a demo and modified it the best I could to get it as close to what I need as I can but I need help now.

Here is the Data for the 30 days with the number of visitors on each day.  This JavaScript array is what will need to be used to populate the data on the graph...
My PHP code spits this out on the page where I need it in my JavaScript code...
[
    ["Dec 15", 1],
    ["Dec 16", 0],
    ["Dec 17", 0],
    ["Dec 18", 0],
    ["Dec 19", 0],
    ["Dec 20", 0],
    ["Dec 21", 0],
    ["Dec 22", 0],
    ["Dec 23", 0],
    ["Dec 24", 0],
    ["Dec 25", 1],
    ["Dec 26", 0],
    ["Dec 27", 0],
    ["Dec 28", 0],
    ["Dec 29", 2],
    ["Dec 30", 0],
    ["Dec 31", 0],
    ["Jan 1", 0],
    ["Jan 2", 0],
    ["Jan 3", 0],
    ["Jan 4", 0],
    ["Jan 5", 0],
    ["Jan 6", 0],
    ["Jan 7", 0],
    ["Jan 8", 0],
    ["Jan 9", 1],
    ["Jan 10", 0],
    ["Jan 11", 0],
    ["Jan 12", 1],
    ["Jan 13", 1],
]

My biggest problem with the demo code below is the x Axis along the bottom.  It need to be changed to show the days/date for the past 30 days.  The vertical Y Axis shows the number of visitors, that is set up already.
Below is the code I have from the demo so far....
JSFiddle Demo page - http://jsfiddle.net/g3550h7m/
JavaScript
$(function () {
    $('#container').highcharts({
        chart: {
            type: 'area'
        },
        title: {
            text: '30 Day Traffic Stats'
        },
        subtitle: {
            text: ''
        },
        xAxis: {
            allowDecimals: false,
            labels: {
                formatter: function () {
                    return this.value; // clean, unformatted number for year
                }
            }
        },
        yAxis: {
            title: {
                text: 'Page Traffic Stats'
            },
            labels: {
                formatter: function () {
                    return this.value + ' Visitors';
                }
            }
        },
        tooltip: {
            pointFormat: '{series.name} {point.y:,.0f}
on {point.x}'
        },
        plotOptions: {
            area: {
                pointStart: '15',
                marker: {
                    enabled: false,
                    symbol: 'circle',
                    radius: 2,
                    states: {
                        hover: {
                            enabled: true
                        }
                    }
                }
            }
        },
        series: [{
            name: 'Page Visits',
            data: [
    ["Dec 15", 1],
    ["Dec 16", 0],
    ["Dec 17", 0],
    ["Dec 18", 0],
    ["Dec 19", 0],
    ["Dec 20", 0],
    ["Dec 21", 0],
    ["Dec 22", 0],
    ["Dec 23", 0],
    ["Dec 24", 0],
    ["Dec 25", 1],
    ["Dec 26", 0],
    ["Dec 27", 0],
    ["Dec 28", 0],
    ["Dec 29", 2],
    ["Dec 30", 0],
    ["Dec 31", 0],
    ["Jan 1", 0],
    ["Jan 2", 0],
    ["Jan 3", 0],
    ["Jan 4", 0],
    ["Jan 5", 0],
    ["Jan 6", 0],
    ["Jan 7", 0],
    ["Jan 8", 0],
    ["Jan 9", 1],
    ["Jan 10", 0],
    ["Jan 11", 0],
    ["Jan 12", 1],
    ["Jan 13", 1],
    ]
        }]
    });
});

HTML

Answer: The problem is that your data contains incorrect x values, it should be number or timestamp (for number xAxis type as you have), instead of strings. To convert dates to timestamp you can use Date.UTC() / Date.parse(). Second solution is set xAxis type as category.
Answer: I'm sure there is a better way to accomplish this goal however this code below does the desired output so I am going with it for now!  Might help someone else out as my searches found nothing like this online!

There is lots of small changes but the biggest change is the xAxis to this...
xAxis: {
    type: 'datetime'
},

Also in my Series I have added a pointStart and pointInterval
series: [{
    name: 'Unique Visitors',
    data: <?php echo $chartData['uniquepageviews']; ?>,
    pointStart: Date.UTC(<?php echo $chartData['startdate']; ?>),
    pointInterval: 24 * 3600 * 1000 // one day
},{
    name: 'Page Views',
    data: <?php echo $chartData['pageViews']; ?>,
    pointStart: Date.UTC(<?php echo $chartData['startdate']; ?>),
    pointInterval: 24 * 3600 * 1000 // one day
    },
]

Comment: could you please send the full code including with the query?


Ridge regression and autocorrelation

Question: Im currently working with a strongley balanced data set. I have 15 countries over the period 1990-2017. My dependent variable is CO2 emissions. My independent variables are as follows, GDP per capita, total population, petroeleum prducts used and urban population as a % of total population. All variables are taken in log as I am following the STIRPAT framework.
I had originally tested for my coefficients using fixed effects, however due to the problem of multicollinearrity I chose to use the ridge regression model.
My issue now is, how do I test for the presence of heteroskedascity and autocorrelation? Are using OLS test applicable? If so, if the presence of autocorrelation is found, what are my options for correcting it?
Comment: What do you mean by OLS test?
Comment: diagnositcs test for OLS regression.
Answer:
[H]ow do I test for the presence of heteroskedascity and autocorrelation?

You can use the common tests just as you would when evaluating a regression estimated by OLS. The fact that the model coefficients were estimated with $L_2$ penalty does not affect the testing procedure.

[I]f the prescence of autocorrelation is found, what are my options for correcting it?

You can use the common remedies such as modelling the error term explicitly as an ARMA (or AR or MA) process. This is trivial if estimation is done in two stages (ridge regression first followed by ARMA for the error term) but could be difficult to implement if you choose the more efficient simultaneous estimation.
Comment: Due to how close OLS is to ridge regression are the classical assumptions of OLS applicable to ridge regression?
Comment: @ColmDuggan, please post this as a separate question (but first check if it has been answered before on some other thread).
Comment: I used the first diference correction method to correct for autocorrelation. however, the Rsquared of the model fell to below 20% is this normal when correcting for autocorrelation?
Comment: @ColmDuggan, you have effectively changed the dependent variable, so $R^2$ values are not directly comparable. You could back up the fitted values of the original variable and calculate the $R^2$ manually by taking the squared correlation between the original variable and the corresponding fitted values that you backed up. On another note, unless your dependent variable had a unit root, taking first differences must have introduced a unit root in your residuals, a situation known as overdifferencing.
Answer: In order to omit heteroscedasticity you can use weighted regression, it should help you reduce this effect. If we talk about multicollinearity, you can use PCA before fitting your model. Then you will be able to extract important linear combinations of the variables that will not be related to each other. For autocorrelation, except standard econometrics method, maybe you can try RandomForest. Bagging methods can be very good for models where we are not able to remove autocorrelation (see Lopez de Prado - Advances in Financial Machine Learning)

Ridge regression and autocorrelation


How to convert data from one row to multiple rows base on Date

Question: I wish to convert data from  one row to multiple rows base on start_time and end_time.
INPUT DATA:

ID
Start_Time
End_Time
Down_Mins

ABC123
11/22/2022 12:01
11/29/2022 14:33
10232.47

I need to write SQL for this requirement:
OUTPUT_DATA:

ID
Start_Time
End_Time
Down_Mins

ABC123
11/22/2022 12:01
11/23/2022 7:00
1138.55

ABC123
11/23/2022 7:00
11/24/2022 7:00
1440

ABC123
11/24/2022 7:00
11/25/2022 7:00
1440

ABC123
11/25/2022 7:00
11/26/2022 7:00
1440

ABC123
11/26/2022 7:00
11/27/2022 7:00
1440

ABC123
11/27/2022 7:00
11/28/2022 7:00
1440

ABC123
11/28/2022 7:00
11/29/2022 7:00
1440

ABC123
11/29/2022 7:00
11/29/2022 14:33
453.92

enter image description here
Comment: [Why is "Can someone help me?" not an actual question?](https://meta.stackoverflow.com/q/284236/2029983)
Comment: Please do not spam lots of unnecessary tags. SQL Server and Oracle are two different RDBMS and have different syntaxes. given that your other tags relate to Oracle I've remove SQL Server; if that is incorrect then please [edit] your question and add the correct tags.
Comment: Which dbms are you using? (You've already got one product specific answer - hope you're not wasting someone's time writing an answer for "wrong" dbms.)
Comment: Data type for Start_Time and End_Time columns?
Comment: thanks all for your support, sorry for confusing, its oracle db im using.
Comment: I would not do this in SQL - use a programming language to generate rows of data. This is much cleaner and easier to understand than the clever abomination in the answer below!
Answer: You can use a recursive query to split the data into rows for each 24-hour period starting at 7am:
WITH days (id, start_time, day_end, end_time, day_mins, down_mins) AS (
  SELECT id,
         start_time,
         LEAST(TRUNC(start_time - INTERVAL '7' HOUR) + INTERVAL '31' HOUR, end_time),
         end_time,
         LEAST((LEAST(TRUNC(start_time - INTERVAL '7' HOUR) + INTERVAL '31' HOUR, end_time) - start_time) * 24 * 60, down_mins),
         down_mins - LEAST((LEAST(TRUNC(start_time - INTERVAL '7' HOUR) + INTERVAL '31' HOUR, end_time) - start_time) * 24 * 60, down_mins)
  FROM   table_name
UNION ALL
  SELECT id,
         day_end,
         LEAST(day_end + INTERVAL '24' HOUR, end_time),
         end_time,
         LEAST((LEAST(day_end + INTERVAL '24' HOUR, end_time) - day_end) * 24 * 60, down_mins),
         down_mins - LEAST((LEAST(day_end + INTERVAL '24' HOUR, end_time) - day_end) * 24 * 60, down_mins)
  FROM   days
  WHERE  day_end < end_time
  AND    down_mins > 0
)
SEARCH DEPTH FIRST BY id, start_time SET order_id
SELECT id,
       start_time,
       day_end AS end_time,
       day_mins AS down_mins
FROM   days;

Which, for the sample data:
CREATE TABLE table_name (ID, Start_Time, End_Time, Down_Mins) AS
SELECT 'ABC123',
       DATE '2022-11-23' + INTERVAL '7' HOUR - NUMTODSINTERVAL(1138.55, 'MINUTE'),
       DATE '2022-11-23' + INTERVAL '7' HOUR + NUMTODSINTERVAL(10232.47 - 1138.55, 'MINUTE'),
       10232.47
FROM   DUAL;

Outputs:

ID
START_TIME
END_TIME
DOWN_MINS

ABC123
2022-11-22 12:01:27
2022-11-23 07:00:00
1138.55

ABC123
2022-11-23 07:00:00
2022-11-24 07:00:00
1440

ABC123
2022-11-24 07:00:00
2022-11-25 07:00:00
1440

ABC123
2022-11-25 07:00:00
2022-11-26 07:00:00
1440

ABC123
2022-11-26 07:00:00
2022-11-27 07:00:00
1440

ABC123
2022-11-27 07:00:00
2022-11-28 07:00:00
1440

ABC123
2022-11-28 07:00:00
2022-11-29 07:00:00
1440

ABC123
2022-11-29 07:00:00
2022-11-29 14:33:55
453.916666666666666666666666666666666667

fiddle


Title of page not showing in CodeIgniter

Question: I have this controller in CodeIgniter that loads a header view and another view:
class Add_user extends CI_Controller{
function __construct(){
        parent::__construct();

    }
public function index(){
    $this->load->view('header_view');
    $this->load->view('add_user_view');
}

So,  this page:
 http://localhost/my-project/index.php/add_user is supposed to have the title of add_user_view , but it doesn't and I don't understand why.
Comment: That's the order I have
Comment: change the order: first: add_user_view, sorry
Comment: I fixed it by passing data to the header view, like the answer of @wolfgang suggested
Answer: This is the proper way to done that thing:
class Add_user extends CI_Controller {

            // MVC config
            var $CONTROLLER = 'contoller name';
            var $MODEL = 'model name';
            var $TITLE = 'page title name';
            var $LIST_PAGE_NAME = 'view page name';

            function Add_user() {
                parent::__construct();
                $this->load->model($this->MODEL, 'model');
            }

            public function index(){
              $this->load->view('header_view');
              $this->load->view('add_user_view');
            }
       }

Now in this controller, model or view. If you have to use above global varaible code like this.
<?php echo $this->TITLE; ?>


Powershell: creating functions (or aliases) for system commands

Question: I am trying to make it easier to run certain things with certain users from powershell.
So first I calculate username and domain needed to run a specific command, which is no problem.
But then I want to be able to run a specific command with the calculated credentials, and this fails. I have already tried the following variants:
<code># this does not work yet (the command works, but the alias/function doesn't
# function aduc {"runas /user:$currentUserDomain\$adminUserNameTier0 dsa.msc"}
# function aduc {& "runas /user:$currentUserDomain\$adminUserNameTier0 dsa.msc"}
# function aduc {Invoke-Command -NoNewScope -ScriptBlock {runas /user:$currentUserDomain\$adminUserNameTier0 dsa.msc}}
# function aduc {Invoke-Command -NoNewScope -ScriptBlock {& "runas /user:$currentUserDomain\$adminUserNameTier0 dsa.msc"}}
</code>
Whenever I call "aduc", I get:

aduc : The term 'runas /user:DOMAIN\USER dsa.msc' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:1

(I put DOMAIN\USER in the error message for data protection, of course in reality we are using real, existing values)
Any idea how to get this to work?
Answer: After further experimentation I found this works:
<code>$currentUserDomain = "contoso.com"
$adminUserNameTier0 = "contosodomainadmin"
function aduc {Invoke-Command -NoNewScope -ScriptBlock {runas /netonly /user:$currentUserDomain\$adminUserNameTier0 "mmc dsa.msc"}}
</code>
Now simply calling "aduc" will run the dsa ("Active Directory Users and Computers") mcc console as contoso\contosodomainadmin, asking for the password.
Question can be closed.


Search everythings using django filter

Question: I am trying to search multiple fields and full text Warnings table. I use django filter to search but no returned result. I also refer some code using django filter and follow them but nothing. How do I solve?
Here are some code.
filters.py
import django_filters
from .models import Warnings

class WarningFilter(django_filters.FilterSet):
    title = django_filters.CharFilter(lookup_expr='icontains')
    detail = django_filters.CharFilter(lookup_expr='icontains')
    type = django_filters.CharFilter(lookup_expr='icontains')
    website = django_filters.CharFilter(lookup_expr='icontains')

    class Meta:
        model = Warnings
        fields = ['title', 'detail', 'type', 'website']

views.py
def search(request):
    if request.method == 'GET':
        query = request.GET.get('q')
        result = WarningFilter(query, queryset=Warnings.objects.all())
    context = {'filters': result.qs}
    return render(request, 'pages/history_warning.html', context)

models.py
from django.db import models
from django.contrib.auth.models import User
import uuid

class Website(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200)
    uri = models.CharField(max_length=200)
    def __str__(self):
        return self.name

class Warnings(models.Model):

    TYPE_WARNINGS = (
        ('security', "Cảnh báo bảo mật"),
        ('service', "Cảnh báo dịch vụ")
    )
    title = models.CharField(blank=True, null=True, max_length=255)
    detail = models.TextField(blank=True, null=True)
    date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    type = models.CharField(choices=TYPE_WARNINGS, blank=True, null=True, max_length=255)
    website = models.ForeignKey(Website, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

Answer: Probably you can do it like this using filter.method:
class WarningFilter(django_filters.FilterSet):
    q = django_filters.CharFilter(method='filter_q')

    def filter_q(self, qs, name, value):
        return qs.filter(
            Q(title__icontains=value) | Q(detail__icontains=value) | Q(type__icontains=value) | Q(website__name__icontains=value)
        )

Usage:
if request.method == 'GET':
    result = WarningFilter(request.GET, queryset=Warnings.objects.all())
    context = {'filters': result.qs}
    return render(request, 'pages/history_warning.html', context)
Comment: I tried in Python console, the returned result is incorrect, I think problem is in filters.py

Search everythings using django filter


Minimum tickets required for specified probability of winning lottery

Question: In a lottery, 1/10 of the 50 000 000 tickets give a prize.
What is the minimum amount of tickets one should buy to have at least a 50% chance to win?
Would be very glad if you could explain your methodology when resolving this. Please consider this as homework if you will.
Answer: I should really ask what your thoughts are so far on this. This problem is very closely related to the "birthday problem". The easiest way to do these problems is to count the possible ways of either winning or losing. Usually one is much easier to do than the other, so the key is to find the right one. Before we get into the actual calculation, let's start with some heuristics.

Heuristics: Let $n$ be the total number of tickets and $m$ be the number of winning tickets. In this case $n = 50\,000\,000$ and $m = 5\,000\,000$. When $n$ is very large then purchasing multiple distinguishable tickets is almost the same as sampling with replacement from the population of tickets.
Let's suppose that, instead of having to purchase $k$ separate tickets, we purchased a ticket, looked to see if it was a winner and then returned it to the lottery. We then repeat this procedure where each such draw is independent from all of the previous ones. Then the probability of winning after purchasing $k$ tickets is just
$$
\Pr( \text{we won} \mid \text{purchased $k$ tickets} ) = 1 - \left(\frac{n-m}{n}\right)^k .
$$
For our case then, the right-hand side is $1 - (9/10)^k$ and so we set this equal to $1/2$ and solve for $k$ in order to get the number of tickets.
But, we're actually sampling without replacement. Below, we'll go through the development, with the point being that the heuristics above are more than good enough for the present problem and many similar ones.

There are $50\,000\,000$ tickets. Of these $5\,000\,000$ are winning ones and $45\,000\,000$ are losing ones. We seek
$$
\Pr(\text{we win}) \geq 1/2 \>,
$$
or, equivalently,
$$
\Pr(\text{we lose}) \leq 1/2 .
$$
The probability that we lose is simply the probability that we hold none of the winning tickets. Let $k$ be the number of tickets we purchase. If $k = 1$, then $\Pr(\text{we lose}) = 45\,000\,000 / 50\,000\,000 = 9/10 \geq 1/2$, so that won't do. If we choose two tickets then there are $45\,000\,000 \cdot 44\,999\,999$ ways to choose two losing tickets and there are $50\,000\,000 \cdot 49\,999\,999$ ways to choose any two tickets. So,
$$
\Pr( \text{we lose} ) = \frac{45\,000\,000 \cdot 44\,999\,999}{50\,000\,000 \cdot 49\,999\,999} \approx 0.9^2 = 0.81.
$$
Let's generalize now. Let $m$ be the number of winning tickets and $n$ the total number of tickets, as before. Then, if we purchase $k$ tickets,
$$
\Pr(\text{we lose}) = \frac{(n-m) (n-m-1) \cdots (n-m-k+1)}{n (n-1) \cdots (n-k+1)} .
$$
It would be tedious, but we can now just start plugging in values for $k$ until we get the probability below $1/2$. We can use a "trick", though, to get close to the answer, especially when $n$ is very large and $m$ is relatively small with respect to $n$.
Note that $\frac{n-m-k}{n-k} \leq \frac{n-m}{n}$ for all $k < m < n$. Hence
$$
\Pr(\text{we lose}) = \frac{(n-m) (n-m-1) \cdots (n-m-k+1)}{n (n-1) \cdots (n-k+1)} \leq \left(1 - \frac{m}{n} \right)^k ,
$$
and so we need to solve the equation $\left(1 - \frac{m}{n} \right)^k = \frac{1}{2}$ for $k$. But,
$$
k = \frac{\log \frac{1}{2}}{\log (1 - \frac{m}{n})} \>,
$$
and so when $m/n = 1/10$, we get $k \approx 6.58$.
So, $k = 7$ tickets ought to do the trick. If you plug it in to the exact equation above, you'll get that
$$
\Pr( \text{we win} \mid \text{k=7} ) \approx 52.2\%
$$
Comment: Very detailed. I loved it. Thank you and I'll consider it as an answer unless someone comes up with something else.