does javascript's this object refer to newly created object in the way i think

Question: So, when we create constructor function for creating new object the new keyword does 3 things
I'am going to explain it but please correct me if I'am wrong i want to be sure I'am correct
first i will create a constructor function
function ObjectCreate(){
    this.a = "a";
    this.b = "b";

    ObjectCreate.prototype.show = function(){
        alert(this.a+" "+this.b);
    }
}

obj1 = new ObjectCreate();

now the first thing new keyword does is create new object and set its secret link to its constructor's prototype and pass it to the constructor function where now the this can refer to it and please note this does not refer to obj1 at this point because once constructor finished creating object only then it returns the newly created object to obj1 variable. i ask this question because some people say that this refer to the obj1 object in this case. so am i right here.
Comment: but trying the code could probably answer your question, right?
Comment: Is there some reason why you can't just try it yourself?
Comment: did you understand my question ?
Comment: its not about trying the code i am just asking something
Comment: its not about code correcting issue i am correcting my concept
Answer: Your phrasing is a bit confusing, but I'll do my best. First, you should note that your curly braces are a bit off. Your code should look like this:
function ObjectCreate(){
   this.a = "a";
   this.b = "b";
}

ObjectCreate.prototype.show = function(){
     alert(this.a+" "+this.b);
}

obj1 = new ObjectCreate();

You need to define your constructor, then attach things to its prototype.
When you call the constructor, the this keyword does basically refer to the new object being created. This is important because, for example, you could write a constructor like:
function ObjectCreate(x,y){
   this.a = x*x;
   this.b = y*x+4;
}
obj1 = new ObjectCreate(10,20);

Here, as in all constructors, this refers to the instance being created (obj1, in this case).
I think you suggested that this refers to the object's prototype, but that would make this.a and this.b static variables, which would be useless in a constructor like the one here, since every time you initialized a new object you would change the vale of this.a and this.b for all previously existing objects, and that just isn't useful.
I hope that answered your question. If not, please go ahead and leave comments for further clarification.
Comment: i said that this refers to newly created object not to obj1 at the time of creation once the constructor finished executing only then the object is returned to obj1. am i right here
Comment: `obj1` *is* the newly created object. What's the difference?
Comment: You are in the process of defining it. Are you asking whether or not the object is *called* `obj1` during the creation process? That seems like a question of pure semantics.
Comment: i am  asking whether or not the object is called obj1 during the creation process?
Comment: Again, that's a question of semantics. The object doesn't *really* exist at all until the function is finished, at which point it is immediately "called" `obj1`. During the construction process, it isn't really "called" anything, because it doesn't exist as a fully formed object.
Answer: In this example, during constructor invocation, obj1 is undefined. Value is assigned to obj1 variable after ObjectCreate function returns.
You can check yourself:
function ObjectCreate(){
    this.a = "a";
    this.b = "b";

    alert(obj1); // yields "undefined"
    ObjectCreate.prototype.show = function(){
        alert(this.a+" "+this.b);
    }
}

var obj1 = new ObjectCreate(); // note "var"

Comment: what do u say about above answer someone posted is it write because it says that objectCreate cant contain objectCreate.prototype ? is right thing
Comment: You can assign functions to object prototype in constructor, but it will be executed every time constructor is run. So, it's better to assign method functions to object's prototype once, outside constructor function.
Answer: It seems nobody mentioned that this refers to the invoking object.
window.sayHi=function(){
  console.log(this.name);
}
window.name="Window"
window.sayHi();//=Window

var obj={
  name:"obj"
}
obj.fn=window.sayHi;

obj.fn();//=obj

The code above shows that when passing functions around the this context will change. If you don't want that then you can pass a closure instead of the function or use call, apply or bind:
//closure example
obj.fn=(function(w){//w is available because the returned function is a closure
  return function(){
    w.sayHi();
  }
}(window));

obj.fn();//=Window
//using call
obj.fn.call(window);//=Window
//using apply
obj.fn.apply(window);//=Window
//using bind
var boundFn=obj.fn.bind(window);
boundFn();//=Window

That was when you pass a function as a parameter on another object. When you use constructor functions then this within the function body will refer to the object to be created.
But when you pass around it's functions it may not be:
var obj={
  name:"obj"
}
var Test=function(){
  this.name="Test";
}
Test.prototype.sayHi=function(){
  console.log(this.name);
};

var t=new Test();
obj.fn=t.sayHi
t.sayHi();//=Test
obj.fn();//=obj

This is a pitfall most people fall in when passing object instance functions to setTimeout or event handlers:
someButton.onclick=t.sayHi;//when button is clicked this will be the button clicked
setTimeout(t.sayHi,100);//when sayHi is executed 'this' will be window

To answer your question about obj1 existing within the constructor function's body; I'd say no (not in Firefox at least). I don't have a link to the specs but obj1 would be set to this when the constructor function returns:
//clean up window.t
delete window.t;
var Test=function(){
  this.name="Test";
  console.log("and window.t is:",window.t);//undefined
}
Test.prototype.sayHi=function(){
  console.log(this.name);
};

window.t=new Test();

More on constructor functions, prototype, inheritance, overriding and calling super here.


Is This Set a Group? Ring?

Question: If we consider the set of linear functions that map reals to reals: $$G = \ \{ \ f(x)=mx+b \mid m,b \in \mathbb{R} \}$$
Is $\langle G, + \rangle$ a group under function addition?
Is $\langle G, +, * \rangle$ a ring under function addition and function multiplication?
I am sure that the answer to the first question is yes, but I am unsure if this set comprises a ring? From looking at the ring axioms I would say no, but any hints or solutions would be appreciated.
Comment: What happens when you multiply two linear functions together? Is the result another linear function?
Comment: you get something of a degree greater than one meaning its not closed. This was my initial thought as well. Thank you.
Answer: Your set is not a ring since it is not closed under multiplication.  Note, for example,
$$
(x) * (x) = (x^2) \notin G
$$
If you change $*$ to composition rather than multiplication, then $G$ is closed under $*$, but is not a ring since it fails the distributive property.
Comment: Note that $(G, \circ)$ is not even a group because $m=0$, i.e. $f(x)\equiv b$ has no inverse.
Comment: Why do we care if a ring is a group under its multiplication?
Answer: The multiplicaton operation has to that $G \mapsto G$, so we can't have a group if we define
$$
(f_1 \circ f_2) (x) = f_1(x) f_2(x) $$
since the right side is not linear.
Instead, let's try
$$f_1 \circ f_2  = f_1( f_2(x) )$$
Now multiplication is closed, and there is an identity, namely $f(x) = x$.
Now there are multiple functions, not just the additive identity $f(x) = 0$, that have no multiplicative inverse:
If
$f(x) = k$, then there is no function $g(x)$ such that for all $x$, $g(k)=x$. But that does not disqualify $G$ from being a ring, since there is no need for multiplicative inverses.
But consider associativity.  Does
$$
m_1(m_2+m_3)x + b_2+b_3) +b_1 \stackrel{?}{=}(m_1+m_2)(m_xx+b_3) + (b_1+b_2)
$$
Of course not, just look at the terms that have only $b_i$ in them.  On the left you have $b_1$, on the right you have $(b_1+b_2)$.
So this does not form a ring.
Answer: Take $f,g\in G$ defined by $f(x)=m_1x+b_1$ and $g(x)=m_2x+b_2$.
$(f\cdot g)(x)=(m_1x+b_1)(m_2x+b_2)=m_1m_2x^2+(m_1+m_2)x+m_1m_2\notin G$
Then $G$ is not closed under multiplication.
Comment: You mean $(G, \cdot)$ is not a group, since $(G, +)$ _is_ a group.

Is This Set a Group? Ring?


Keeping count in a solo trill

Question: I am working towards my clarinet Grade 8 and have a few occasions where I have to play an unaccompanied long trill (we're talking a bar or 2). I have always struggled to count trills, however all the ones I have had to play before have a piano accompaniment that helps me to count (quavers in the bass or something similar) or I can pick out a few notes in the accompaniment which alert me to the end of the trill. However I am struggling to count accurately when the piano accompaniment either plays a long held note under my trill or stops entirely.
I find that tapping my foot or playing with a metronome just results in my trill turning into quavers or semiquavers instead, which doesn't quite sound right. I can count the length of the note just fine regardless of accompaniment if I don't trill, the trill seems to throw off my 'internal rhythm'.
Are there any other techniques I can use to try and keep count during a solo trill?
Comment: @CarlWitthoft That is not what I'm asking, nor are there any answers which help in that question... I am after advice on how to hold a steady internal beat whilst playing a trill
Comment: Possible duplicate of [How many notes in a trill?](https://music.stackexchange.com/questions/78701/how-many-notes-in-a-trill)
Answer: Very best of luck with the exam!
Last resort would be have a chat with your accompanist. They may be able to "conduct" you with their subtle head movements.
Also, have you tried doing those conducting movements yourself as you perform? When I do a long trill (I'm a trumpet player), I might actually move my bell subtly in a 4/4 beat pattern or whatever. I find this helpful.
I'd also suggest practising trills with a metronome. It may be that you're concentrating on trilling as fast as you physically can, so all your mental effort is going on that. It also means you're treating the trill as arhythmic. But if you're able to consider the trill motion as a fast rhythm, you'll be better able to keep track of where in the bar you are. It also helps you prepare if you have any decoration at the end of the trill before you hit the held note.
Comment: My accompanist is my teacher and she is trying to encourage me to learn to count it properly, rather than relying on her, so I don't think she would agree to the first one! I might try the subtle conducting, although she has also been trying to stop me doing that in other parts of music where it makes things sound a bit stilted! I will try again with a metronome and see if I can try and stop ending up just playing semiquavers. Thanks :)
Answer: Internalizing the beat in non-trivial situations is actually one of the most difficult things that a musician has to acquire.
It's also seen that different individuals develop different internal strategies to achieve that. For example, some people say they feel the beat as a pulse in their stomach, for others it's a sort of visual projection, as if they were visualizing rhythmic movements or some conductor, and still others can hear internally something like a metronome tick.
And to make things worse, there isn't a well established, reliable way of teaching that, and as a result, bar a few tips, most musicians are more or less left to figure it out for themselves.
I have actually spent quite some time studying this very issue, with a view to possibly designing a training system for this kind of skill, and could talk a lot more about it, but in order to be as useful as possible to you in the shortest time possible I'll give you two points to consider, hoping you can get something useful from them.
1
Realize that you can only pay attention to music in one way at a time. There are many ways to pay attention to music (follow the rhythm, follow the melody, follow the harmony, follow the mechanics of play, etc.) but you can only do one at a time, and whenever you switch your focus to one (e.g. the mechanics of playing a trill) inevitably you lose most of you conscious attention to anything else.
In your specific case this means that you have essentially two main ways of achieving your goal:
A) Keep your attention on the trill, after having internalized the beat to such a strong degree that you don't lose it if even if you don't pay attention to it. Essentially, this is as if you had a metronome ticking vividly in your head, and even if you don't pay attention to it consciously, you can rely on its presence implicitly.
B) Keep your attention on the beat, counting the beat inside, and perform the trill with indirect attention. This requires that your have practiced the mechanics of the trill enough that you can do it with only a fraction of your total attention.
Borrowing a concept from the mechanics of vision, where we have focused vision and peripheral vision, the two alternatives above correspond to putting one aspect at the center of the vision (either the mechanics of playing or the keeping of the beat), and managing the other aspect with the peripheral vision, so to speak.
Both approaches are possible and both can work well with some practice. Which one works best depends on the individual and the specific situation.
2
To improve your ability in mode A above (i.e. focus on the playing and feel the beat with your peripheral awareness) I find that the following exercise can give good results.
The exercise consists in listening to the music you need to play on (in this case it would be just the piano) and keep time by hitting a surface with a stick, pen, drumstick, or something like that. You want to reach the point where you can keep the time effortlessly and very precisely, without using your full attention. In other words, after enough practice, you could be looking around the room, petting your cat, sipping a drink, and your hand should be effortlessly keeping the beat with very good precision.
Obviously, pay as much attention as you need, especially in the beginning, but the goal of the exercise is to eventually be able do keep precise time with little or no direct attention. (And it's important that your movement produces a sharp tick, which you can clearly hear as being either precise or not. Waving a finger in the air or tapping a foot is not sharp enough.)
Once you reach that point, when you will again play your instrument over that accompaniment, you will find that you will have a much stronger sense of the beat running internally. It may feel like a ticking sound, or it may feel like a kinetic pulse of some kind, or some other way -- there's no single best and right way -- but you will definitely feel the beat much more vividly than before.
Hopefully this will help you solve this particular challenge to a satisfactory degree, but in any case I think that it will also be quite helpful in playing in general, and in rhythmically difficult situations in particular.
Comment: And if down the line you'd like to let us know how it worked out for you, we'd love to read that :)
Comment: This was really interesting to read and hopefully I can put some of into practice :)
Answer: Ideally, you should be able to trill and simultaneously listen to the accompaniment, and know the piano part well enough to know what is being played at the end of your trill.  That's a lot to deal with, but I recommend you try doing so, as it is a great skill (listening to other parts) in any ensemble.
BTW,  you may have seen chamber music players using electronic tablets to display the music. This allows them to see all the parts at once, making it easier to coordinate just as you are trying to do here.
Comment: Ahhh,  in that case it's the accompanist's job to follow **your** transition out of the trill.  Even if you hold it a beat too long or too short, the piano must follow the soloist.
Comment: I can play a trill fine when there is an accompaniment. However, as stated in the initial quesiton, the piano is just holding a long note underneath my trill, or stopping entirely, and I need to be able to count correctly to end the trill as the piano begins playing again
Comment: Whilst that is true in general performing, that won't help in an exam where the examiner will mark you down for letting the beat slip (especially in a Grade 8 exam)
Answer: I have a song that uses 8 beat trill about 5 times with a fast tempo and a quarter note at the end, so it is very important to internalize the beats in the song with the trill. I have found that the best way to do this is to get a steady tempo and find a beat on the trill to accompany tapping my toe and my internal beat. I am only in my second year of playing, so I might be saying everything wrong. However, I find that internalizing the beat helps me out the most

Keeping count in a solo trill


Can't convert .py files into .exe files

Question: I want to turn python files into .exe files but I can't. I have installed py2exe
when I run the program setup.py on the windows command prompt with that command line
python setup.py py2exe

I get the following error message:
no module named py2exe

Comment: Is py2exe in your PYTHONPATH?
Answer: To quote the py2exe tutorial:

"py2exe" is a new Distutils command that is added when you import
  py2exe. To use py2exe you need to create a setup.py file to tell
  Distutils and py2exe what you want to do. Here's a setup.py whose
  simplicity is appropriate for our sample program...

So their example setup.py script is:
     from distutils.core import setup
     import py2exe
     setup(console=['hello.py'])

Which can be built with
python setup.py py2exe

So I think you are just missing the import.  Post your full setup.py if this is not the case so we can debug.
Comment: if you are happy with an answer its good practice to accept it by clicking the tick mark :)
Comment: Thanks a lot for your help. I found a video tutorial. I managed to run the script from the command prompt
Comment: Just one Question here - if `hello.py` has been converted to `hello.exe` would be able to run on machine where `python` not installed?
Comment: @PythonLikeYOU if I remember correctly, py2exe has options to tell it whether you want to include the interpreter in the final exe file or not.
Comment: Can I have a bit help on that to make `.exe` file from `.py` file, which can run on any windows machine without `python` installation?

Can't convert .py files into .exe files


Writing 100,000 lines in a csv in fastest way possible

Question: I m trying to create a zip of 100 csv.
I need to write 100,000 lines in a single csv in fastest way possible.
I am using openCSV, ZipEntry method to write to csv.
Some Code used:
ZipEntry zipentry = new ZipEntry(filename);
zos.putNextEntry(entry);
CSVWriter writer = new CsvWriter(new OutputStreamWriter(zos));
writer.writeNext(entries); //entries is single line of csv

Currently its taking 1.5 secs to write a single csv and overall its taking around 120-140secs to create complete zip.
I have debugged the code, and observed that the other computations in the code is not taking time, but the write operation does takes time.
I have tried creating list of 100,000 lines and then writing one one file at a time instead if direct streaming. But still it takes same time.
Please suggest fastest method which takes less time. ;-(
Comment: A hard disc is inherently a slow device.  If you really need speedy IO consider a solid state drive (and yes, I mean in a production system).
Comment: But i want to do it from java perspective. Any suggestions for that?
Comment: Your can run each write asynchronously to speed up the process. Try ten at a time and you should be done in 15 seconds.
Comment: I can't do async, since the data which is getting write is computated first and they r dependent on previous data.
Answer: BufferedOutputStream improves IO performance by a large margin:
see Javadoc: BufferedOutputStream

By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written.

OutputStream out = new BufferedOutputStream(zos, 1<<16);
CSVWriter writer = new CsvWriter(new OutputStreamWriter(out);

Comment: It didn't change anything...need to try something else. :-(
Answer: Try using less aggressive compression level for your ZipOutputStream such as 3:

public void setLevel(int level)
Comment: Dunno if this will work but it seems a cogent idea.


validates specific attribute of associated model

Question: What's the simplest railsy way to validate an attribute of an associated model?
Item
  belongs_to :user
  validates_presence_of :user
  # AND the "is_photographer" column for that user must be true

User
  has_many :items
  # can be a regular user or a photographer

Answer: validate :user_is_photographer, :if => :user

def user_is_photographer
  errors.add(:user, "should be a photographer") unless user.is_photographer
end


Looking for a SEO plugin for Drupal

Question: For my internship I could use some help with the optimization for search engines.
Are there any plugins that will help me increase the SEO performance of the website im trying to optimize? So far I only found a checklist but thats not what im looking for. Wordpress has a Yoast plugin that checks every move I make to optimize it for search engines. Does Drupal have a similar plugin?
Comment: Welcome to Drupal Answers! The question is vague at the moment, and will be pretty biased. Decompose what SEO actually consists of, and search for those modules. That will also help you understand what are you dealing with, instead of installing one "magical" module. See [Global Redirect](https://www.drupal.org/project/globalredirect), [Pathauto](https://www.drupal.org/project/pathauto), [XML Sitemap](https://www.drupal.org/project/xmlsitemap), [Metatag](https://www.drupal.org/project/metatag) and [Page Title](https://www.drupal.org/project/page_title) for a start.
Answer: I thought the following was a bit like Yoast . SEO Compliance Checker - https://www.drupal.org/project/seo_checker
Once downloaded install and enable.
SEO Checklist
Basic SEO Modules
Keyword Rules
Then go to configuration .
Once those modules have been enabled you'll then have a nice set of Sliders to use in the 'Thresholds for the SEO Rules' box.
Set up your sliders depending on what the recommended levels are at the time.
From here you'll then need to visit the Article that you want to optimise .

Click on PREVIEW

The Keywords are taken from 'tags' .

Looking for a SEO plugin for Drupal


php array_merge_recursive is replacing some key strings with numeric keys

Question: I am experiencing unexpected behaviour with the php function array_merge_recursive. Any advice or work-around would be appreciated.
The problem is with unexpected replacement of string keys with numeric key during the array_merge_recursive.
Details:
I have three associative arrays ($birthdays,$custom,$natHolidays), to which these values are programmatically added:
$birthdays['0808'][] = 'John MacLoud';
$birthdays['0819'][] = 'Susan MacLoud';
$birthdays['0903'][] = 'Catherine MacLoud';
$birthdays['1008'][] = 'Daisy Simpson';
$birthdays['1015'][] = 'Phillip MacLoud';
$birthdays['1212'][] = 'Aloysius Simpson';
$natHolidays['0317'][] = 'St. Patrick's Day';
$natHolidays['0317'][] = 'la Saint-Patrick';
$natHolidays['0701'][] = 'Canada Day';
$natHolidays['0701'][] = 'la fête du Canada';
$natHolidays['1031'][] = 'Hallowe'en';
$natHolidays['1031'][] = 'l'Halloween';
$natHolidays['1031'][] = 'Hallowe'en';
$natHolidays['1031'][] = 'l'Halloween';
$natHolidays['1111'][] = 'Remembrance Day';
$natHolidays['1111'][] = 'jour du souvenir';
$natHolidays['1224'][] = 'Christmas Eve';
$natHolidays['1224'][] = 'la vielle de Noël';
$natHolidays['1225'][] = 'Christmas';
$natHolidays['1225'][] = 'Noël';
$natHolidays['1226'][] = 'Boxing Day';
$natHolidays['1226'][] = 'le lendemain de Noël';
$natHolidays['1231'][] = 'New Year's Eve';
$natHolidays['1231'][] = 'vielle du jour de 'an';
$natHolidays['0907'][] = 'Labour Day';
$natHolidays['0907'][] = 'la fête du Travail';
$natHolidays['0922'][] = 'Equinox';
$natHolidays['0922'][] = 'l'equinoxe';
$natHolidays['1012'][] = 'Thanksgiving';
$natHolidays['1012'][] = 'l'action de grace';
$natHolidays['1101'][] = 'Daylight Savings ends';
$natHolidays['1101'][] = 'fall back';
$natHolidays['1221'][] = 'Solstice';
$natHolidays['1221'][] = 'le solstice';
$custom['0922'][] = 'Test value 1';
$custom['1122'][] = 'Test value 2';

I then merge the arrays: $dates = array_merge_recursive($birthdays,$custom,$natHolidays);
The resulting $dates array outputs:
["0808"]=>
  array(1) {
    [0]=>
    string(13) "John MacLoud"
  }
  ["0819"]=>
  array(1) {
    [0]=>
    string(13) "Susan MacLoud"
  }
  ["0903"]=>
  array(1) {
    [0]=>
    string(14) "Catherine MacLoud"
  }
  [0]=>
  array(1) {
    [0]=>
    string(15) "Daisy Simpson"
  }
  [1]=>
  array(1) {
    [0]=>
    string(14) "Phillip MacLoud"
  }
  [2]=>
  array(1) {
    [0]=>
    string(13) "Aloysius Simpson"
  }
  ["0317"]=>
  array(2) {
    [0]=>
    string(22) "St. Patrick's Day"
    [1]=>
    string(16) "la Saint-Patrick"
  }
  ["0701"]=>
  array(2) {
    [0]=>
    string(10) "Canada Day"
    [1]=>
    string(18) "la fête du Canada"
  }
  [3]=>
  array(2) {
    [0]=>
    string(15) "Hallowe'en"
    [1]=>
    string(16) "l'Halloween"
  }
  [4]=>
  array(2) {
    [0]=>
    string(15) "Remembrance Day"
    [1]=>
    string(16) "jour du souvenir"
  }
  [5]=>
  array(2) {
    [0]=>
    string(13) "Christmas Eve"
    [1]=>
    string(18) "la vielle de Noël"
  }
  [6]=>
  array(2) {
    [0]=>
    string(9) "Christmas"
    [1]=>
    string(5) "Noël"
  }
  [7]=>
  array(2) {
    [0]=>
    string(10) "Boxing Day"
    [1]=>
    string(21) "le lendemain de Noël"
  }
  [8]=>
  array(2) {
    [0]=>
    string(19) "New Year's Eve"
    [1]=>
    string(26) "vielle du jour de 'an"
  }
  ["0907"]=>
  array(2) {
    [0]=>
    string(10) "Labour Day"
    [1]=>
    string(19) "la fête du Travail"
  }
  ["0922"]=>
  array(3) {
    [0]=>
    string(14) "Test value 1"
    [1]=>
    string(7) "Equinox"
    [2]=>
    string(15) "l'equinoxe"
  }
  [9]=>
  array(1) {
    [0]=>
    string(15) "Test value 2"
  }
  [10]=>
  array(2) {
    [0]=>
    string(12) "Thanksgiving"
    [1]=>
    string(22) "l'action de grace"
  }
  [11]=>
  array(2) {
    [0]=>
    string(21) "Daylight Savings ends"
    [1]=>
    string(9) "fall back"
  }
  [12]=>
  array(2) {
    [0]=>
    string(8) "Solstice"
    [1]=>
    string(11) "le solstice"
  }

The only pattern I have noticed is that any key string starting with a '0' (i.e. 0130) works as expected, and any key string starting with a '1' (i.e. 1022) replaces the string key with a sequential numeric key.
Thoughts?
Btw:

Creating the new tag 'array-merge-recursive' requires at least 1500
  reputation. Try something from the existing tags list instead.
Answer: PHP is loosely typed, and it is casting your array keys.
You could use integer as keys to avoid the cast:
$arr[10] = 'foo';

and not
$arr["10"] = 'foo';

Updated answer:
The casting is treating keys starting with "0" as strings, and so far so good. The other keys are treated like integers, and array_merge will renumber them starting from 0 (as it is happening here).
I know you are using array_merge_recursive, but it appears to behave the same.
Comment: The MMDD string in the key seemed the easiest way to make connections between the DOY and the data — the alternatives seem to take longer and more elaborate workarounds. I guess that my "delving-deeper" question would be: *"Why is `php` casting the string as an integer in this particular circumstance?* I understand casting, but I don't understand how this example follows those rules.
Comment: Hey @Parapluie, i have updated my answer, maybe it could help you a bit more.
Comment: It took me while to fully grok this, but I now understand what's happening. Your answer helped, as did this question where someone comes at it from a different direction: https://stackoverflow.com/questions/4100488/a-numeric-string-as-array-key-in-php .  I think that prepending my keys with a dummy alpha character should solve the casting problem (`['d0130']`). What a weird one this was!


Restrict users to run 'history -d [arg]' and 'set +o history' commands

Question: We are in the early stages of standardizing our infra. As an immediate step, we want to restrict users from manipulating the history. Have setup some restrictions for the same. But recently found that there are couple of loop holes.

Users can remove the history entry by just running 'history -d '
'set +o history' will stop the history file from being updated.

I am finding ways to restrict users from running this command. I can't think of a way out for this.
Any suggestions will be helpful. Please let me know if something isn't clear. Thanks.
We are using CentOS and our shell is bash
-Ram Kumar
Answer: First need to create an alias for history then use a wrapper to grab the option. this is a simple example but can be expanded.
Create Alias for history command (this can be placed in bashrc)
alias history='/usr/local/bin/myhistory
then in /usr/local/bin/myhistory (you can add more cases as needed and add an else clause to go to the default history funciton):
if [ $username == 'myuser' ]
then
while getopts ":d" opt; do
  case ${opt} in
    d )
      echo "Invalid Option:"
      exit 1
      ;;
  esac
done

fi

You can look into rbash and lshell -- those are more elegant ways to restrict shells. Hope this gives you some idea.


Stopping rule for house selling problem

Question: We have a house to sell. Each day an offer of $X_n$ comes for the house. Each offer costs an amount $k$ to observe. You may think of $k$ as advertisement costs. When you receive an offer you must decide whether to accept the offer or keep waiting for a better one. In case you accept the offer, your actual profit will be $X_n - nk$.
Now we wish to maximize the amount of money we get paid by choosing a proper stopping rule.
P.S. The problem can be found under the title of "job search problem" in economics literature. How many searches should an unemployed person looking for a job undertake, considering each search costs him.
Comment: Won't you need some knowledge of the distribution of $X_i$?
Comment: @hagen-von-eitzen: It would be very nice if there's been any information about the distribution, but apparently not. http://en.wikipedia.org/wiki/Optimal_stopping#House_selling
Answer: The answer to your question depends on what you know about the distribution of the $X_i$. Also, the answer changes whether you are allowed to go back to previously encountered offers. From your question it seems you assume we cannot go back.
1) Suppose you don't know anything about the distribution, not even its support $[\underline{x},\overline{x}]$. Then there may not be a solution. After all, search cost $k$ may be larger than $\overline{x}$, so no matter which offer you get you always make losses by searching, but you only learn of this after searching!
2) Suppose you know the distribution $F(x)$ of the offers, and offers are iid. Now you can compute an optimal stopping rule, because it is possible to trade-off the search costs you incur by searching further with the (expected) benefit. The optimal stopping rule is a threshold rule $\alpha$ which satisfies
$$\int_\alpha^\infty (x-\alpha) dF(x)=c,$$
as shown in Sakaguchi 1961, Dynamic programming of some sequential sampling design, Journal of Mathematical Analysis and Applications. An analogue result if recall is allowed is given in Lippman&McCall 1976, The Economics of Job Search Part I, Economic Inquiry.
3) If I recall correctly, there were some results in the literature which showed that the optimal stopping rule for some classes of the problem even if you don't know the distribution $F$ is also a threshold strategy.

Stopping rule for house selling problem


Can anyone explain to me the difference between .toSting and .string in Java?

Question: I want to know the difference between .toString and .string , i know the term .toString and have been using it since last 1 year but i recently came upon .string and curious to know about it. Thanks in advance.
Answer: There is no such method named .string() in Java's "standard library".
But, it could some external library and/or framework having .string() in their API. One of this example of such method is the .string() method in the ResponseBody of OkHttp API.
Comment: Yeah thanks , now i get it , it was used in the Response Body of the OkHttp API and i was confused about it. Now  its clear.


importing and transforming many csv files

Question: I am importing and transforming many files in an inefficient way. I was wondering if someone could show me a faster way using purr. The following code is what I tried, and it should give you the general pattern:
data_2013 <- read_csv("data_2013") %>%
clean_names() %>% # using the janitor package
mutate(year = "2013")

data_2014 <- read_csv("data_2014") %>%
clean_names() %>%
mutate(year = "2014")

With the years increasing by 1 (all the way up to 2019). I eventually join all these files, as the key variables are the same. But clearly the importing of the files is inefficient.
Any help would be greatly appreciated
Answer: We can do this in a loop with map.  Loop on the file names, read with read_csv, clean the names, and create the 'year' column
library(dplyr)
library(stringr)
library(purrr)
library(readr)
library(janitor)

files <- paste0("data_", 2013:2019, ".csv")
lst1 <-  files %>%
           map(~ read_csv(.x)) %>%
             clean_names() %>%
             mutate(year = str_extract(., "\\d{4}"))

If the list output needs to be merged into a single dataframe
dat1 <- bind_rows(lst1, .id = 'grp')

In base R, this can be done with lapply
lst1 <- lapply(files, function(x) transform(read.csv(x),
                year = sub("data_(\\d+)\\..*", "\\1", x)))
dat1 <- do.call(rbind, Map(cbind, lst, grp = seq_along(lst1)))


Adding data into a list and keeping the right order

Question: Consider the following piece of code in Java:
final LinkedHashSet<String> alldata = new LinkedHashSet<String>();
for (final String folder: folders) {
    for (final String d: data.get(folder)) {
        allData.add(d);
    }
}

when folders is List<String> and data is Map<String, List<String>>.
Example of data:
{data1=[prepare, echo2, echo1], data2=[prepare, sleep2, check]}

Until now, I didn't care about the order of the allData and it would look:
[prepare, echo1, echo2, sleep2, check]

I have a list dataList which contains the right order of the data (and of course all data):
[prepare, sleep1, echo1, sleep2, echo2, check]

I want to iterate through the data and add into the allData those that are defined in data in the right order.
The output for the previous example should be:
[prepare, echo1, sleep2, echo2, check]

Another example:
data = {data1=[prepare], data2=[prepare, sleep2,sleep1,echo2]}
dataList = [prepare, sleep1, echo1, sleep2, echo2, check]

expected output:
allData = [prepare,sleep1,sleep2,echo2]

Of course, there could be more than two inner data (data1,data2,...,dataN).
I'm not sure that its the right thing to add code into the inner for loop, because by doing I'll have to add another loop to iterate through the dataList, and it does not feel efficient (3 loops).
What good, clean and efficient way should I use?
EDIT: I don't try to sort the collection. But I thought of doing the following algorithm:
Creating a Set of all data and then iterate through the dataList and insert into the LinkedHashSet.
Is it efficient?
EDIT2: What I tried to do:
final Set<String> activeData = new HashSet<String>();
for (final String folder: folders) {
    for (final String d: fubsAndSteps.get(folder)) {
        activeData.add(d);
    }
}

final LinkedHashSet<String> allData = new LinkedHashSet<String>();
for (final String main_data : dataList) {
    for (final String active_data: activeData) {
        if (main_data.equals(active_data)) {
            allData.add(active_data);
        }
    }
}

That works for me, but it does not look really good, I mean 4 for loops. It does not feel clean and efficient. Is there a better algorithm?
Comment: Possible duplicate of [Sorting a LinkedHashSet](https://stackoverflow.com/questions/17370909/sorting-a-linkedhashset)
Answer: One of the solution is
Iterate over datalist and check the element exists in data, then add it to allData which keeps order
    Set<String> tempSet = new HashSet<>();
    folders.forEach(folder -> tempSet.addAll(data.get(folder))); // flattening all the data elements into single set

    //Iterate over dataList where you are already maintaining order. If element exists, add it to allData
    dataList.forEach(item -> {
        if(tempSet.contains(item)){
            allData.add(item);
        }
    });

If you are using Java 7 or below
    Set<String> tempSet = new HashSet<>();
    // flattening all the data elements into single set
    for(String folder:folders) {
        tempSet.addAll(data.get(folder));
    }

    //Iterate over dataList where you are already maintaining order. If element exists, add it to allData
    for(String item:dataList){
        if(tempSet.contains(item)){
            allData.add(item);
        }
    }

Comment: forEach loop is available for java 8 and above
Comment: @TTaJTa4 I missed it while converting the code from forEach loop to for loop :-)


Averaging pixels in image ROI

Question: I have the following image and I would like to apply averaging on each masked region (not the bounding box) in the image.

As you can see, right now, the regions have changing values inside them on the heat map. Some pixels are yellowish, some are purplish. I want this to be not the case inside the masks.
So what I need to do is (I guess):

to find which coordinates correspond to the masks
average the pixels within these coordinates

Here is how the masks are found:
file_names = glob(os.path.join(IMAGE_DIR, "*.jpg"))
masks_prediction = np.zeros((521, 768, len(file_names)))
for i in range(len(file_names)):
    print(i)
    image = skimage.io.imread(file_names[i])
    predictions = model.detect([image],  verbose=1)
    p = predictions[0]
    masks = p['masks']
    merged_mask = np.zeros((masks.shape[0], masks.shape[1]))
    for j in range(masks.shape[2]):
        merged_mask[masks[:,:,j]==True] = True
        masks_prediction[:,:,i] = merged_mask

Here is the function which applies the masks:
def apply_mask(image, mask, color, alpha=0.5):
    """Apply the given mask to the image.
    """
    for c in range(3):
        image[:, :, c] = np.where(mask == 1,
                                  image[:, :, c] *
                                  (1 - alpha) + alpha * color[c] * 255,
                                  image[:, :, c])
    return image

and in the main file, here is how it is used:
mask = masks[:, :, i]
if show_mask:
     masked_image = apply_mask(masked_image, mask, color)

So I need to make a modification in somewhere here but I don't know where exactly.
Answer: I think the mask you are looking for is provided by the code :
mask = masks[:, :, i]

where i refers to the number of mask you have.
You can obtain the average values of the mask region from the original image using the openCV function mean
Here is how your code should look like:
mask = masks[:, :, i]
avg_masked_value = cv2.mean(original_image,mask)

where original_image is the original image you loaded and avg_masked_value will contain 3x1 array of averaged value.

Averaging pixels in image ROI


SVN ignoring hidden files (.project .pydevproject and . files)

Question: I want to ignore some hidden files (like .project and .pydevproject) in SVN. They are already in our trunk at the moment so I don't want to delete them from the trunk since it may cause more problems for the other developers. So what I tried to do is to run:
svn propset svn:ignore .project .

but right after that when I run svn status, it returns:
M .

and if I make changes on .project, it still tracks those changes. I also tried global-ignores in /etc/subversion/config, no luck.
What do you think would be the best way to solve this problem?
Thanks.
Answer: svn:ignore works only for the files that haven't been added yet.
Unfortunately you cannot do that in automatic way (at least I don't know any way of doing that).
So all you can do now is:

Delete files from repository with svn rm
Ask developers to store files somewhere before their next svn up
They run svn up and move the deleted files back

Now .project is not tracked by svn and will not appear in svn st
Comment: That's because the svn:ignore property has been set on the "." folder. You have to commit this to apply your ignore configuration.
Comment: Thanks for your reply. What about the "." file? When I set svn:ignore, "." file being modified, I couldn't figure out what should I do about that.


OpenCV real time streaming video capture is slow. How to drop frames or get synced with real time?

Question: Goal and problem
I'd like to set up an opencv system to process either HLS streams or RMTP streams, however, I am running into a strange issue regarding a reduced frame-rate and an accumulating lag. It's as if the video gets further and further behind from where it is supposed to be in the stream.
I'm looking for a way to keep up to date with a live source even if it means dropping frames.
Current approach
import cv2

cap = cv2.VideoCapture()
cap.open('https://videos3.earthcam.com/fecnetwork/9974.flv/chunklist_w1421640637.m3u8')

while (True):
    _, frame = cap.read()
    cv2.imshow("camCapture", frame)
    cv2.waitKey(1)

I've validated the quality of the stream on VLC and it seems to work fine there.
cv2 speed
 .
realistic/expected speed

Questions:

What am I doing wrong here?
Why is it so slow?
How do I sync it to real-time speeds?
Comment: On my machine, I get speeded up video for ~2sec with your code. Then a stop for ~2 sec. repeat. I tried to force the video stream to show the newest frame with cap.set(cv2.CAP_PROP_POS_AVI_RATIO, 1). It seems to work, but I get one frame every  seconds. The FPS from print(cap.get(cv2.CAP_PROP_FPS)) is 180,000.0, which is way too high. But if you could get an accurate FPS, maybe you could do some jiggery pokery with multiple cap.grab() to advance to where you should be in the stream and then a single cap.retrieve to get the frame.
Comment: Also note that your problem could be hardware: memory and data-bus bandwidth, and processor speed.
Comment: use a faster device (more processing power) or use hardware acceleration or optimized code to receive, decode and display the stream. OpenCV might not be the fastest library for receiving, decoding and rendering (but it's very easy to use)
Comment: I see that you have the minimum code to video acquisition in python. So, is impossible improve runtime. Maybe the problem is due to video resolution, if W and H size is long, then buffer reading and showing video frames will be more delayed. A simple solution is decrease the resolution of videos before of reading. Another solution is create an second thread to only video acquisition. Another solution is to read video using C++. I have compared the performance and it is about 3 times faster.
Answer:
My hypothesis is that the jitter is most likely due to network limitations and occurs when a frame packet is dropped. When a frame is dropped, this causes the program to display the last "good" frame which results in the display freezing. This is probably a hardware or bandwidth issue but we can alleviate some of this with software. Here are some possible changes:
1. Set maximum buffer size
We set the cv2.videoCapture() object to have a limited buffer size with the cv2.CAP_PROP_BUFFERSIZE parameter. The idea is that by limiting the buffer, we will always have the latest frame. This can also help to alleviate the problem of frames randomly jumping ahead.
2. Set frame retrieval delay
Currently, I believe the read() is reading too fast even though it is in its own dedicated thread. This may be one reason why all the frames appear to pool up and suddenly burst in the next frame. For instance, say in a one second time interval, it may produce 15 new frames but in the next one second interval, only 3 frames are returned. This may be due to the network packet frame loss so to ensure that we obtain constant frame rates, we simply add a delay in the frame retrieval thread. A delay to obtain roughly ~30 FPS does a good job to "normalize" the frame rate and smooth the transition between frames incase there is packet loss.
Note: We should try to match the frame rate of the stream but I'm not sure what the FPS of the webcam is so I just guessed 30 FPS. Also, there is usually a "direct" stream link instead of going through a intermediate webserver which can greatly improve performance.

If you try using a saved .mp4 video file, you will notice that there is no jitter. This confirms my suspicion that the problem is most likely due to network latency.
from threading import Thread
import cv2, time

class ThreadedCamera(object):
    def __init__(self, src=0):
        self.capture = cv2.VideoCapture(src)
        self.capture.set(cv2.CAP_PROP_BUFFERSIZE, 2)

        # FPS = 1/X
        # X = desired FPS
        self.FPS = 1/30
        self.FPS_MS = int(self.FPS * 1000)

        # Start frame retrieval thread
        self.thread = Thread(target=self.update, args=())
        self.thread.daemon = True
        self.thread.start()

    def update(self):
        while True:
            if self.capture.isOpened():
                (self.status, self.frame) = self.capture.read()
            time.sleep(self.FPS)

    def show_frame(self):
        cv2.imshow('frame', self.frame)
        cv2.waitKey(self.FPS_MS)

if __name__ == '__main__':
    src = 'https://videos3.earthcam.com/fecnetwork/9974.flv/chunklist_w1421640637.m3u8'
    threaded_camera = ThreadedCamera(src)
    while True:
        try:
            threaded_camera.show_frame()
        except AttributeError:
            pass

Related camera/IP/RTSP/streaming, FPS, video, threading, and multiprocessing posts

Python OpenCV streaming from camera - multithreading, timestamps

Video Streaming from IP Camera in Python Using OpenCV cv2.VideoCapture

How to capture multiple camera streams with OpenCV?

OpenCV real time streaming video capture is slow. How to drop frames or get synced with real time?

Storing RTSP stream as video file with OpenCV VideoWriter

OpenCV video saving

Python OpenCV multiprocessing cv2.VideoCapture mp4
Comment: Can you tell me why the waiting (FPS syncing) is needed? Isn't the point of the buffer to capture frames as they come?  It feels like it wouldn't matter what is grabbed from the top of the buffer. Building an artificial delay feels counterintuitive for me. Would that be about resource sharing in threads or something? Or is it that the images don't come in real-time exactly, but as they're able to be reconstructed or re-delivered. Either way, thank you for the detailed response. This works very well.
Comment: @BenZayed For a single camera just setting buffer size and delay should work but if you have multiple cameras running simultaneously you may need to use threading (I use this technique with 8 simultaneous camera streams)
Comment: @Conic The FPS syncing is needed because generally you want to sync with the source. If you are polling too slow, you will have periods where you don't have a new frame so you will be displaying the old frame. If you poll too fast (like before), you will display all the frames instantly. In both cases, this may cause the jitter/freeze so by inserting a delay, you can even out the frame distribution as it is displayed. Since there are two separate threads, once a frame is received, it is immediately displayed so that's another reason why we need a delay.
Comment: Here's an analogy, say you're watching a Youtube video on 2x speed but you are using dial-up internet. The buffer rate will load slower than the video actually playing so eventually, the frames will catch up to the buffer and the video will freeze. This is what happens when the FPS is not synced. If we revert back to 1x speed, then the frames will be evened out and match the speed of the buffer rate so we don't get any freezing/jitter. The video then looks smooth
Comment: OpenCV VideoCapture isn't polling at all. could you explain what you mean?
Comment: @ChristophRackwitz actually it's polling in the `update()` which is called inside started thread: `Thread(target=self.update, args=())`
Comment: yah `capture.read()` inside of infinite loop is polling.
Comment: It's constantly polling. The entire operation of capturing frames is put inside the thread so that if the program is exited, the capture operation will not hang as a zombie process. If we don't set `daemon` to `True`, it will be a zombie process when your main program dies. We set daemon `True` so that when our parent process dies, this will also kill all child processes. See [threading documentation](https://docs.python.org/3/library/threading.html#thread-objects) for more information
Comment: Could you please explain to me why you used a threaded camera. I set a maximum buffer size and a frame retrieval delay as you suggested and that was enough to get a smooth streaming.
Answer: Attempt at threading
I've attempted this solution from nathancy with minor success.
It involves:

creating a separate thread for image capture from the source
using the main thread exclusively for display.

Code:
import cv2
from threading import Thread

class ThreadedCamera(object):
    def __init__(self, source = 0):

        self.capture = cv2.VideoCapture(source)

        self.thread = Thread(target = self.update, args = ())
        self.thread.daemon = True
        self.thread.start()

        self.status = False
        self.frame  = None

    def update(self):
        while True:
            if self.capture.isOpened():
                (self.status, self.frame) = self.capture.read()

    def grab_frame(self):
        if self.status:
            return self.frame
        return None

if __name__ == '__main__':
    stream_link = "https://videos3.earthcam.com/fecnetwork/9974.flv/chunklist_w1421640637.m3u8"
    streamer = ThreadedCamera(stream_link)

    while True:
        frame = streamer.grab_frame()
        if frame is not None:
            cv2.imshow("Context", frame)
        cv2.waitKey(1)

Jittery, but real-time results
 .
The streaming works. It maintains real-time. However, it is as if all the frames pool up and suddenly burst into the video. I would like somebody to explain that.
Room for improvement
The real-time stream can be found here.
https://www.earthcam.com/usa/newyork/timessquare/?cam=tsstreet
This site is scraped for the m3u8 using python's streamlink stream scraper.

import streamlink

streams = streamlink.streams("https://www.earthcam.com/usa/newyork/timessquare/?cam=tsstreet")
print(streams)

which yeilds:
OrderedDict([

('720p',<HLSStream('https://videos3.earthcam.com/fecnetwork/9974.flv/chunklist_w202109066.m3u8')>),

('live', <RTMPStream({'rtmp': 'rtmp://videos3.earthcam.com/fecnetwork/', 'playpath': '9974.flv', 'pageUrl': 'https://www.earthcam.com/usa/newyork/timessquare/?cam=tsstreet','swfUrl': 'http://static.earthcam.com/swf/streaming/stream_viewer_v3.swf', 'live': 'true'}, redirect=False>),

('worst', <HLSStream('https://videos3.earthcam.com/fecnetwork/9974.flv/chunklist_w202109066.m3u8')>),

('best', <RTMPStream({'rtmp': 'rtmp://videos3.earthcam.com/fecnetwork/', 'playpath': '9974.flv', 'pageUrl': 'https://www.earthcam.com/usa/newyork/timessquare/?cam=tsstreet', 'swfUrl': 'http://static.earthcam.com/swf/streaming/stream_viewer_v3.swf', 'live': 'true'}, redirect=False>)

])

The possibility that the streams are being read wrong.
Comment: Did you find a solution to this?
Comment: Yes I did.  It's the answer with the green checkmark next to it from nathancy.
Comment: Oops sorry. Since you said nathancy's answer was a minor success. I thought you meant the answer to this question (didnt check the link). Anyway. Thanks.
Comment: I can see how that might be misleading. I was referring to a different solution of his from another stack overflow post.  He then responded with an updated answer that did FPS syncing. That ended up being the solution that worked for me.
Comment: Yeah. Thanks :)
Answer: I would suggest double checking the compatible video stream codecs with the hardware. I ran into the same issue, frame rate dropped to 5 fps only during streaming, because it was defaulting to a format that is not being streamed so it would convert it then display very lagged (~1s) with lower fps as well.
use Self.capture.set(cv2.CAP_PROP_FOURCC ,cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') ) with the proper codec in place of MJPG and with your cv2.VideoCapture and see if that helps.
Answer: This made a huge difference for me (on Windows 11, using an ELP USB2 camera):
Instead of using self.capture = cv2.VideoCapture(1)
I used self.capture = cv2.VideoCapture(1, cv2.CAP_DSHOW)
This enabled me to use all of the cv2.CAP_PROP_ attributes.


How to verify $0\leq f_n(x) \leq f_{n+1}(x)\leq\dots$

Question: From Mathematical Analysis By Andrew Browder1)

10.6 Lemma. If $f$ is a nonnegative measurable function, then there exists a sequence $(f_n)$ of nonnegative simple measurable functions, such that $0\leq f_n(x) \leq f_{n+1}(x)$ for all $n \in \mathbf{N}$ and all $x \in X$, and such that $\lim f_n(x) = f(x)$ for all $x \in X$.
Proof. It suffices to put
$$ f_n = \sum_{k=1}^{n2^n} \frac{k-1}{2^n} \mathbf{1}_{A_{n,k}} + n\mathbf{1}_{B_n}, $$
where $A_{n,k}=\{x : (k-1)2^{-n} < f(x) \leq k2^{-n} \}$ and $B_n =\{ x : f(x) > n \}$. It is routine to verify that the sequence $(f_n)$ has the desired properties.

Here, I am unable to prove $0\leq f_n(x) \leq f_{n+1}(x)\leq \dots$
I tried like: If $x \in \cup_{k=1}^{n2^n}A_{(n,k)}$,then $x \in A_{(n,j)}$ for some $j$
Then $f_n(x)=\frac{j-1}{2^n}$
now $f_{n+1}=\sum_{k=1}^{(n+1)2^{(n+1)}}\frac{k-1}{2^{n+1}}1_{A_{(n+1,k)}} + (n+1)1_{B_{(n+1)}}$
Here,I can use say,$x \notin B_n$$\implies x \notin B_{(n+1)}\implies x \in (B_{n+1})^c$
Using $(B_n)^c=\cup_{k=1}^{n2^n}A_{(n,k)}$ I have $(B_{n+1})^c=\cup_{k=1}^{(n+1)2^{n+1}}A_{(n+1,k)}$
So,$x \in A_{(n+1,l)}$ for some $l$
so we will have $f_{n+1}(x)=\frac{l-1}{2^{n+1}}$
But,now how should I proceed further to show,$f_n(x) \leq f_{n+1}(x)$.
Thanks in advance.
Comment: You can verify this, but it is not actually necessary: As long as you know that $f_n \to f$ and $f_n \leq f$ always, you can simply take $g_n := \max \{f_1,\dots,f_n\}$. It is then straightforward to check that $g_n \leq g_{n+1}$ and that each $g_n$ is a measurable step function with $g_n \to f$ pointwise.
Answer: Define $\phi : [0, \infty) \to [0, \infty)$ by
$$ \phi(x) = \max\{0, \lceil x \rceil - 1\} = \begin{cases}
n-1, & \text{if $n-1 < x \leq n$ for some $n \in \{1, 2, 3, \dots\}$}; \\
0, & \text{if $x = 0$}.
\end{cases} $$
Then by noting that
$$A_{n,k} = \{ x : \phi(2^n f(x)) = k-1 \} \quad\text{for} \quad k = 1, \dots, n2^n$$
and
$$B_n = \{ x : \phi(2^n f(x)) \geq n 2^n\}, $$
we obtain the following simple representation:
$$ f_n(x) = \min\bigg\{ \frac{\phi(2^n f(x))}{2^n}, n \biggr\} $$
Then the desired conclusion easily follows from the easy observations:

$2\phi(x) \leq \phi(2x)$ holds for all $x \geq 0$.

If $a_1 \leq a_2$ and $b_1 \leq b_2$, then $\min\{a_1, b_1\} \leq \min\{a_2, b_2\}$.
Answer: The main point of this sequence of partitions is that they are nested, the next partition refines the previous. Since on a region $A_{(n,j)}$ we make $f_n$ assume the minimal possible value, refining the partition will make $f_{n+1}$ larger, since $\min A \cup B \le \min (\min A, \min B)$.
More formally, if $x \in A_{(n,j)}$ then $\frac{j-1}{2^n} < f(x) \le \frac{j}{2^n}$ and thus when we look at $n+1$ we see that
$$\frac{2j-2}{2^{n+1}} < f(x) \le \frac{2j}{2^{n+1}}$$ and $x$ must belong to either $A_{(n+1,2j-1)}$ or $A_{(n+1,2j)}$, implying $f_{n+1}(x) = \frac{2j-2}{2^{n+1}}$ or $\frac{2j-1}{2^{n+1}}$.


How to correctly access elements through many-to-many relationships?

Question: There is such a data structure in the database

Model Users:
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    /*
      * Model(Users) with (Group_users)
      * users - group_users
        many-to-many
   */
    public function ingroup() {
        return $this->belongsToMany(Group_user::class, 'group_works');
    }

    /*
    * Model (users) with (Group_works)
        one-to-many
    */
    public function peoples() {
        return $this->hasMany(Group_works::class);
    }
}

Model Group_use:
class Group_user extends Model
{
    use HasFactory;

    protected $fillable = [
        'name_group',
        'user_id',
    ];

    /*
     * Model (Group_user) with (User)
     many-to-one
    */
    public function user() {
        return $this->belongsTo(User::class, 'user_id');
    }

    /*
    * Model (Group_user) with (User)
      many-to-many
    */
    public function ingroup() {
        return $this->belongsToMany(User::class, 'group_works');
    }

    /*
   * Model (Group_users) with (Group_works)
     one-to-many
   */
    public function peoples() {
        return $this->hasMany(Group_works::class);
    }

}

Controller code:
// Editor group
    public function edit(Group_user $group, Request $request) {
        $editor = Auth::user()->id;
        $users = User::query()->get();
        return view('admin.groups.edit', compact('editor', 'group', 'users'));
    }

Blade admin.group.edit:
Name group: {{ $group->name_group }}
Creator group: {{ $group->user->name }}

@foreach($users as $user)
  Code User: {{$user->id}}
  Name User: {{$user->name}}
  <?php if ($user->ingroup->id == $group->id) {?> User in a Group <?}?>
 @endforeach

As a result, the error:

Property [id] does not exist on this collection instance.

How to correctly check if a user belongs to a group using the presented associations?
Tried connecting models through existing links.
Comment: Take a look at the eloquent Docs on the Laravel website or watch one of the excellent video introductions on the web such as Laracasts -  ithink their basic Laravel is free.  Belongs to many will return a Collection not a model.
Comment: By the way it may be easier to contextually understand your diagram if you don't draw the pivot table at all and instead say there's a M:N relationship between users and groups (user member of group?) and another 1:N relationship between users and groups (user owner of group?). When drawn this way the pivot table is an implied consequence of the M:N relationship
Answer: You're trying to access the id property on a collection of users ($user->ingroup). The ingroup relationship is many-to-many, so it returns a collection of users, not a single user.
Name group: {{ $group->name_group }}
Creator group: {{ $group->user->name }}

@foreach($users as $user)
  Code User: {{$user->id}}
  Name User: {{$user->name}}
  <?php if ($user->ingroup->contains('id', $group->id)) {?> User in a Group <?}?>
@endforeach

Comment: @IntegralAL contain is a collection method, you can read it from here
https://laravel.com/docs/8.x/collections#method-contains
Comment: @IntegralAL no issues. i am glad my answer solved your problem
Comment: Where can I read about it in the documentation? I'm about "contains". ingroup->contains('id', $group->id) ... ?>


qual a melhor forma de fazer uma consulta case_sensitive

Question: SELECT * FROM `table_users` WHERE BINARY nome = $nome AND senha = $senha

Isso é correto, ou seria uma má prática?
Comment: Incorreto não é, mas acho que o `LIKE` é melhor
Answer: É um erro usar BINARY para este caso, se estiver armazenando senhas. Aliás, senhas não devem ser armazenadas em DB.
O BINARY ignora completamente o unicode e equivalência de caracteres, então um Á composto sempre será tratado diferente de um Á de caractere simples.
Em resumo: pode acontecer que, dependendo do OS e da aplicação, um usuário digite o mesmo caractere, e ele seja enviado de maneiras diferentes, invalidando um acesso legítimo, e o usuário não vai nem saber o que aconteceu.
É corretissimo se armazenar hashes, por outro lado. Hashes são naturalmente "binários" no sentido de poderem usar qualquer caractere de 0x00 a 0xff. Tenho visto muita gente armazenando os hashes em hexadecimal, mas armazenando direto em binário você gasta metade do espaço.
Nos nomes, inclusive, nem teria razão para ser CS, exceto alguma restrição muito específica da aplicação. Ter dois usuários diferentes chamados "José" e "josé" é um bom princípio de confusão.
Collations
A solução nestes casos é usar as collations corretas em cada coluna do banco, conforme a necessidade.
Pode usar nativamente, especificando na criação da tabela (ou alterando-a), ou pode usar o verbo COLLATE do DB na hora da query.
Por exemplo, em unicode, você tem a utf8_bin, que considera o código dos caracteres em unicode, e não os bytes individuais. Vale notar que ao exibir na tela, pode ser interessante forçar um ORDER BY column COLLATE utf8_general_ci para manter a ordem alfabética esperada, se realmente for usar isto nos nomes.
Em latin, você tem as terminações _ci para _case_insensitive_ e _cs para sensitive.
Entenda melhor aqui:

Qual a diferença entre charset e collation em banco de dados?
Answer: Resposta curta: é correto e não é, depende da necessidade.
No seu caso, tratando de usuário e senha, seria melhor validar a entrada dos dados com um padrão especificado, nomes de usuário geralmente são considerados válidos apenas com caracteres minúsculos números e etc, seguindo este contexto se você sempre validar a entrada dos dados para que tal valor seja de tal maneira (sempre minúsculo por exemplo), não terá a necessidade de aplicar coisas específicas ao fazer queries para o database por exemplo.. Mas se deseja que um nome de usuário possa ter caracteres maiúsculos, aí sim essa implementação faria sentido. Espero que ajude!
Answer: Não é incorreto mas tem consequências.
A palavra chave BINARY faz um cast da string para uma string binária, forçando a comparação byte a byte e não caracter a caracter, tornando comparação case sensitive além de tornar os espaços em branco no inicio na string significativos.
Se você realmente precisa que a comparação para esse campo seja case sensitive, é mais apropriado você tornar a coluna toda BINARY, pois uso da palavra chave BINARY na query anula a utilização do índice caso a essa coluna seja indexada. Isso sim é ruim, e no seu caso, essa coluna obrigatoriamente deveria estar indexada.
No exemplo abaixo perceba que o índice xnome não será utilizado ao se utilizar BINARY:
    mysql> explain select * from tb where xnome = 'a'\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: tb
   partitions: NULL
         type: ref
possible_keys: xnome
          key: xnome
      key_len: 153
          ref: const
         rows: 1
     filtered: 100.00
        Extra: NULL
1 row in set, 1 warning (0,00 sec)

mysql> explain select * from tb where BINARY xnome = 'a'\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: tb
   partitions: NULL
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 3
     filtered: 100.00
        Extra: Using where
1 row in set, 1 warning (0,00 sec)

Isso não ocorre quando você cria a coluna como BINARY, o índice também já é criado de maneira apropriada.
Você pode alterar o tipo da coluna:
ALTER TABLE nome_tabela CHANGE nome_coluna nome_coluna VARCHAR(XX) BINARY NOT NULL;


Separar Item clickable em Layout android

Question: Tenho uma ListView, e um layout do item do adapter que segue a imagem básica dele

Problema é que quando eu clico em qualquer área do item, na lista, todo componente é "selecionado"

Gostaria de obter o efeito de Ação 1, Ação 2 e Descrição separados.
Por exemplo:

Layout XML:
...
<LinearLayout
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/linearLayout"
    android:layout_marginLeft="3dp">

        <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:id="@+id/txtDescricao"
                android:text="Descricao" />

        <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@android:color/darker_gray"/>

        <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:weightSum="100"
                android:orientation="horizontal">

            <LinearLayout android:layout_width="wrap_content"
                          android:layout_weight="50"
                          android:clickable="true"
                          android:layout_height="wrap_content">

                <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:id="@+id/txtAcao1"
                        android:text="Acao 1" />

            </LinearLayout>

            <View
                    android:layout_width="1dp"
                    android:layout_height="match_parent"
                    android:background="@android:color/darker_gray" />

            <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="50"
                    android:gravity="center"
                    android:id="@+id/txtAcao2"
                    android:text="Acao 2" />

        </LinearLayout>

</LinearLayout>

Tentei também adicionar um setOnClickListener no Ação1 e Ação2, mas não funcionou
Segue a classe .java
//ViewHolder
    static class ViewHolderItem {
            public TextView txtAcao1;
            public TextView txtAcao2;
            public View txtDescricao;
        }

//Adapter
 class RoteiroAdapter extends BaseAdapter{

            private Context mContext = null;
            private List<ItemRoteiro> mListaRoteiro = null;

            public RoteiroAdapter(Context context, List<ItemRoteiro> lista){
                this.mContext = context;
                this.mListaRoteiro = lista;
            }

            @Override
            public int getCount() {
                return mListaRoteiro.size();
            }

            @Override
            public Object getItem(int position) {
                return mListaRoteiro.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {

                ViewHolderItem viewHolder;

                if(convertView == null){

                    LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
                    convertView = inflater.inflate(R.layout.item_roteiro, parent, false);

                    viewHolder = new ViewHolderItem();
                    viewHolder.txtAcao1= (TextView) convertView.findViewById(R.id.txtAcao1);
                    viewHolder.txtAcao2= (TextView) convertView.findViewById(R.id.txtAcao2);
                    convertView.setTag(viewHolder);
                }
                else{
                    viewHolder = (ViewHolderItem) convertView.getTag();
                }

                ItemRoteiro item = mListaRoteiro.get(position);

                if(item != null) {

                    viewHolder.txtAcao1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    });
                }
                 return convertView;
            }
        }

Alguém sabe como obter este efeito??
Obrigado!!
Comment: Como você trata isso na activity?
Comment: instancia cada layout(são 2 ações; portanto, 2 layouts diferentes) e dá clickListener no layout.
Comment: @ReginaldoRigo editei e postei o código da activity
Comment: @Mr_Anderson, obrigado pela ajuda, vou testar aqui e aviso o resultado..
Comment: @Mr_Anderson também não funcionou.. Já fiz muitos testes nenhum tive sucesso...
Comment: Estranho, pq se é uma lista customizada, então deveria funcionar, assim como um cardview que contém uma imagem com alguns botoes dentro...
Answer: Da um ID pro seu LinearLayout e usa o click via Java nele.
Exemplo:
XML
<LinearLayout
     android:id="@+id/acao1"
     android:layout_width="wrap_content"
     android:layout_weight="50"
     android:layout_height="wrap_content">

JAVA
LinearLayout acao1 = (LinearLayout) findViewById(R.id.acao1);
acao1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

Em todos os itens no XML inserir:
 android:clickable="false"

E o layout aonde deseja ter o efeito do "click"
 android:clickable="true"
 android:background="?android:attr/selectableItemBackground"

Comment: Obrigado @LeonardoDias, bastou adicionar o `android:background="?android:attr/selectableItemBackground"`, no linearLayout e `android:clickable=true` nos linearLayout e funcinou!!!
Comment: Obrigado @Leonardo Dias pela ajuda, testei aqui, o que ocorre agora, é que quando pressiono em Acao1 ou Acao2 não acontece nada na tela (o onClickListener é chamado normalmente), porém se pressiono na descrição todo item é marcado. Mas já foi um avanço..
Comment: Tenta colocar o **android:clickable="false"** no TextView da descrição
Comment: Testei, tentei também colocar o `android:duplicateParentState="true"`, que achei, mas não está funcionando.. Estou fazendo testes..


Remove unwanted character in string using regex

Question: I'm trying to remove characters that do not match a specific pattern using the example below:
Pattern to match exactly 4 alphabets [a-zA-Z]{4} followed by space(s) \s{1,} then 4 characters starting with an alphabet, last 3 number [a-zA-Z]{1}[0-9]{3}
If I supply ABEH A501; BIOL L340; BIOL Z620; Q799; ABEH A501 it matches all except Q799, now, I need to remove/replace Q799 from the string.
I tried to apply Negated Character Classes but still not getting the desired result.
$mystring = "ABEH A501; BIOL L340; BIOL Z620; Q799; ABEH A501";
$string = preg_replace("/[^a-zA-Z]{4}\s{1,}[a-zA-Z]{1}[0-9]{3}/","",$mystring);

echo $string; //ABEH A501; BIOL L340; BIOL Z; ABEH A501

The desired result should be ABEH A501; BIOL L340; BIOL Z620; ABEH A501
Q799 was removed so also was part of another matching string, not sure if this was due to wrong regEx or wrong application of negated character class.
Comment: `\s{1,0}` what is that means?
Comment: Match at least one or more spaces?
Comment: Since many wrong variations of the pattern you want can occur, wouldn't it be better to extract the patterns that do match with `preg_match()`?
Comment: https://regex101.com/r/KXhIWa/3 as per this your regex is invalid. Use + or {1,}. {1,0} makes no sense ("from 1 to 0 characters")
Comment: for at least one or more use `{1,}` or `+`
`{1,0}` I think this means from 1 to 0
Comment: Fixed regex, but still not getting the desired result.
Comment: you want get `ABEH A501; BIOL L340; BIOL Z620; ABEH A501` in result?
Comment: Yes.............
Answer: In PHP you can define a known good match regex and use PCRE verbs (*SKIP)(*F) to skip these matches in replacement:
$mystring = "ABEH A501; BIOL L340; BIOL Z620; Q799; ABEH A501";
echo preg_replace('/[a-zA-Z]{4}\s+[a-zA-Z]\d{3}(*SKIP)(*F)|\w+\W*/', '', $mystring);

RegEx Demo
Output:
ABEH A501; BIOL L340; BIOL Z620; ABEH A501

PHP Code Demo
Comment: Any specific reason why you used `\s{1,8}` instead of `\s{1,0}`
Comment: Sorry it is fixed. I read `{1,0}` as `{1,8}`. It can simply be `\s+` as in my answer now.
Answer: This is a different approach to the question, but hey, it works
<?php

$mystring = "ABEH A501; BIOL L340; BIOL Z620; Q799; ABEH A501";
preg_match_all("/[a-zA-Z]{4}\s{1,}[a-zA-Z]{1}[0-9]{3};?\s+?/",$mystring, $matches);
$result = "";
foreach($matches[0] as $match) {
    $result = $result.$match;
}
echo $result; //ABEH A501; BIOL L340; BIOL Z620;

?>


Elementary proof of norm convergence of Inverse Fourier Transform for $L^2$ function

Question: Given an $L^2$ function $f(t)$,
define $$\hat{f_n}(s)=\int_{-n}^{n}f(t)e^{-ist}dt$$
It can be easily shown using Plancherel theorem that there is some $g(s) \in L^2$ and $$\lim_{n\rightarrow\infty}\int_{-\infty}^{\infty}(\hat{f_n}(s)-g(s))^2ds=0$$
$$\int_{-\infty}^{\infty}(g(s))^2ds=\int_{-\infty}^{\infty}(f(t))^2dt$$
How to show $$\lim_{n\rightarrow\infty}\int_{-a}^{a}\left(\frac{1}{{2\pi}}\int_{-n}^{n}g(s)e^{ist}ds-f(t)\right)^2dt=0$$  where $a \in R$
Answer: My result doesnt look pretty (looking forward to simpler one) but here is it: first prove it for $f$ with compact support then generalise it to $L^2$ using inequalities.
Proof for  $f(t) $ of compact support and $\in L^2$  :
clearly $f(t) \in L^1$ without loss of generality assume $f(t)=0$ outside $[-\pi,\pi]$ since we can always replace   $f(t)$ with $f(t')$ such as $t=\frac{n}{2\pi} t'$ for $n \in N$ and $t' \in R$.
define $${g}(s)=\lim_{n\to\infty}\int_{-n}^{n}f(t)e^{-ist}dt$$
The relationship between fourier transform and fourier series for $f(t)$ above follows from
$$(1)  \lim_{n\rightarrow\infty}\int_{-\pi}^{\pi}(\frac{1}{\pi}\int_{-\pi}^{\pi}f(t+u)\frac{sin(n+\frac{1}{2})u}{2sin(u/2)}du-\frac{1}{\pi}\int_{-\pi}^{\pi} f(t+u)\frac{sin(n+\frac{1}{2})u}{u}du)^2dt=0$$
which is simply consequence of Riemann-Lebesgue Lemma applied to the function $ f (t+u) k (u) $, where $k(u)=\frac{1}{2sin(u/2)}-\frac{1}{u}$  , using remainder term for the Taylor's series of $sin(u/2)$, it easily seen $k(u) $  is bounded over $[-\pi, \pi]$
$$(2)\frac{1}{2\pi} \int_{-(n+\frac{1}{2})}^{(n+\frac{1}{2})}g(s)e^{ist}ds=\frac{1}{\pi}\int_{-\infty}^{\infty}f(t+u)\frac{sin(n+\frac{1}{2})u}{u}du$$
This can be derived from fubini's theorem and  this theorem : $\mu$ is Lebesgue outer measure, $ A $  is a measurable set with finite measure. For all $n$ ,  $\int_Af_n^2d\mu \le k $ where $ k \in R $ , {$ f_n $} is uniformly integrable
Norm convergence for Fourier series  :
$$(3)  \lim_{n\rightarrow\infty}\int_{-\pi}^{\pi}(\frac{1}{\pi}\int_{-\pi}^{\pi}f(t+u)\frac{sin(n+\frac{1}{2})u}{2sin(u/2)}du-f(t))^2dt=0$$
using Riemann Lebesgue Lemma on (2) we have $$\frac{1}{2\pi} \int_{-(n+\frac{1}{2})}^{(n+\frac{1}{2})}g(s)e^{ist}ds=\frac{1}{\pi}\int_{-\pi}^{\pi}f(t+u)\frac{sin(n+\frac{1}{2})u}{u}du$$
Using Norm convergence of fourier series (3), Riemann-Lebesgue lemma, Cauchy-Schwartz Inequality,$a^2+b^2 \ge 2ab$ and (1) and (2) we have:
$$\lim_{n\rightarrow\infty}\int_{-\pi}^{\pi}\left(\frac{1}{2\pi}\int_{-(n+\frac{1}{2})}^{n+\frac{1}{2}}g(s)e^{ist}ds-f(t)\right)^2dt=0$$
Proof for $f(t) \in L^2$:
define $f_m=f_{[-m,m]}$ where $m \in N$ and its fourier transform is $\hat{f_m}$
$$\lim_{m\rightarrow\infty} f_m=f$$
By Plancherel theorem : $\lim_{m\rightarrow\infty} \hat{f_m}=\lim_{m\rightarrow\infty}\int_{-m}^{m}f(t)e^{-ist}dt=\hat{f}$ in sense of $L^2$
our previous result for function with compact support : $$\lim_{n\to \infty}\int_{-\pi}^{\pi}(\frac{1}{2\pi}\int_{-n}^{n}\hat{f_m}(s)e^{ist}ds-f_m(t))^2dt =0 $$
$$\lim_{n\to \infty}\int_{-\pi}^{\pi}(\frac{1}{2\pi}\int_{-n}^{n}\hat{f_m}(s)e^{ist}ds-f_m(t))^2dt=\lim_{n\to \infty}\int_{-\pi}^{\pi}(\frac{1}{2\pi}\int_{-n}^{n}\hat{f_m}(s)e^{ist}ds-f_m(t)_{[-\pi,\pi]})^2dt =\lim_{n\to \infty}\int_{-\pi}^{\pi}(\frac{1}{2\pi}\int_{-n}^{n}\hat{f_m}(s)e^{ist}ds-f(t))^2dt=\lim_{n\to \infty}\int_{-\pi}^{\pi}(\frac{1}{2\pi}\int_{-n}^{n}\hat{f_n}(s)e^{ist}ds-f(t))^2dt=0 $$
There is a subsequence {$n$} such that $\hat{f_n} \to \hat{f} $ ae. Let's work with such subsequence
$$\lim_{n\to \infty}\int_{-\pi}^{\pi}(\frac{1}{2\pi}\int_{-n}^{n}\hat{f}(s)e^{ist}ds-\frac{1}{2\pi}\int_{-n}^{n}\hat{f_n}(s)e^{ist}ds)^2dt =$$$$\lim_{n\to \infty}\int_{-\pi}^{\pi}(\frac{1}{\pi}\int_{-\infty}^{\infty}(f(t+u)_{[-\infty,-n]}+f(t+u)_{[n,\infty]})\frac{sin(n+\frac{1}{2})u}{u}du)^2dt $$ $$\le 2(||f(u)_{[-\infty,-n]}+f(u)_{[n,\infty]}||_{L^2}+||\frac{sin(n+\frac{1}{2})u}{u}||_{L^2})^{-1/2}$$ by Cauchy-Scwartz ineqaulity
because $a^2+b^2 \ge 2ab$ , it follows from Cauchy-Schwartz inequality that:
$\lim_{n\to \infty}\int_{-\pi}^{\pi}(\frac{1}{2\pi}\int_{-n}^{n}\hat{f}(s)e^{ist}ds-f(t))^2dt\le$
$\lim_{n\to \infty}\int_{-\pi}^{\pi}(|\frac{1}{2\pi}\int_{-n}^{n}\hat{f}(s)e^{ist}ds-f_n(t)|+|f_n(t)-f(t)|)^2dt=0 $
we proved the result for some sequence {$n$} to see the result holds for all $n$ we observe that
$$\lim_{n\to \infty}\int_{-\pi}^{\pi}(\frac{1}{2\pi}\int_{-(n+1)}^{(n+1)}\hat{f}(s)e^{ist}ds-\int_{-n}^{n}\hat{f}(s)e^{ist}ds)^2dt \le$$$$\lim_{n\to \infty}\int_{-\pi}^{\pi}(\frac{1}{2\pi}\int_{-(n+1)}^{(-n)}|\hat{f(s)}|ds+\frac{1}{2\pi}\int_{n}^{(n+1)}|\hat{f(s)}|ds)^2dt \le \lim_{n\to \infty} \frac{1}{2\pi}(||\hat{f}_{[-n-1,-n]}||_{L^2}+||\hat{f}_{[n,n+1]}||_{L^2})^2=0$$ by Hölder's Inequality


How to re-sample particle filter's particles for a 1D door/wall problem

Question: So assuming your implementation of the motion model and sensor model is at a somewhat satisfying level, the question then is how do I stabilize localization with the re-sampling step.
I'm currently dealing with the robot walking down a hallway with 3 doors, and rest wall using a door/wall classifier sensor.
Only when it reaches a door, do the importance weight indicate some good confidence of its location, however as soon as the robot walks past the door it's gone. I then thought it might be because my re-samples only focuses on removing low weight particles and replacing randomly, rather than replacing them randomly but closer to high weight particles.
The particle filter algorithm follows this sort of approach (after randomizing particles during initialization)
1. for particle i to M
2.     x of particle i = x of particle i + velocity + random noise
3.     w of particle i = p_door(x)(sensed_door) + p_wall(x)(sensed_wall)
4. normalize all w

The original implementation for the resampling I ended up thinking made sense but now believe is completely off(because it's too random) was
1. find max w
2. for particle i to M
3.      if w of particle i  < max*0.8
4.             replace particle i with new particle at random position

So I was wondering what is a common way, or a somewhat ideal way to tackle this problem. Current ideas that come to mind are
 1. Getting the top three particles out of N, then randomly replacing new particles around each of the three particles.
 2. Getting the max weight particle, and threshold at 80% of it's importance weight value, then placing new particles around those that surpass the that threshold.
Is this in the right direction for tackling a 1D particle filter problem or am I off?
Comment: @JuhoKokkala, see new edit
Comment: Can you clarify what do you currently do in the resampling step, e.g., add pseudocode of your algorithm?
Comment: @JuhoKokkala, see new edit
Comment: Can you explain the complete particle filter, too? (I suspect you have misunderstood the idea of the resampling step, but it is also possible that you are implementing some different algorithm than what I have in mind)
Comment: What does 'for particle i to M' mean?
Answer: Cliffs: (depending on the meaning of 'at random position' in the resampling algorithm), the resampling algorithm proposed in the question loses information contained in the measurements $y_1,\ldots,y_k$. Instead, the resampled values should be selected from the existing values, using for example multinomial resampling.
Background
This looks like essentially the bootstrap particle filter by Gordon et al., 1993 [1], that is, for $k=1,\ldots$, the particles $x_k$ and weights $w_k$ form an approximation to the distribution of $x_k$ conditional on all measurements. I assume we have $M$ particles. First, the particles are set to some values $x_0^{(i)}$, for $i=1,\ldots,M$ and the weights are set to $w^{(i)} = 1/M$. Then, for each measurement $k$,

For $i = 1,2,...,M$:

Draw $x^{(i)}_k$   from dynamic model $p(x^{(i)}_k \mid x^{(i)}_{k-1})$
Weight based on dynamic model weights: $w^{(i)}_k = w^{(i)}_{k-1}\,p(y_k \mid x^{(i)}_k)$

Normalize weights to sum to $1$.
Possibly resampling: replace the current particles $x^{(1,2,...,M)}_k$ and weights $w^{(1,2,...,M)}_k$ by the result of the resampling algorithm

(The dynamic model and measurement model are not completely clear from the question, but the scope of the question is the resampling step anyway, so I assume there is some dynamic and measurement model, at least implicitly).
Resampling
The purpose of the resampling step is to obtain a new approximation to the filtering distribution, such that the degeneracy problem where one particle gets all weight, is prevented.
The problem with the proposed resampling algorithm is that if the new values of the particle are selected 'randomly' with some arbitrary distribution, they do not take into account the measurements obtained so far. And thus do not form a good approximation to the filtering distribution.
Instead, typically in the resampling step, the particles are selected from the existing particles. The simplest idea, used in [1], is the so-called multinomial resampling:
Input: old particles $x^{(1)}_k,x^{(2)}_k,...,x^{(M)}_k$
Output: new particles $\tilde{x}^{(1)}_k,\tilde{x}^{(2)}_k,...,\tilde{x}^{(M)}_k$.
For $i = 1,..., M$:

Sample a random integer $J_i$ randomly with probabilities $w^{(1)},w^{(2)},...,w^{(M)}$
Set $\tilde{x}_i := x_{J_i}$ (i.e., select the particle from old particles using the weights as probabilities)
Set $\tilde{w}^{(i)}_k := 1/M$

Various other resampling schemes exist, see, e.g., [2].
References
[1] Gordon, N. J., Salmond, D. J., & Smith, A. F. (1993, April). Novel approach to nonlinear/non-Gaussian Bayesian state estimation. In IEE Proceedings F (Radar and Signal Processing) (Vol. 140, No. 2, pp. 107-113). IET Digital Library.
[2] Douc, Randal, and Olivier Cappé. "Comparison of resampling schemes for particle filtering." Image and Signal Processing and Analysis, 2005. ISPA 2005. Proceedings of the 4th International Symposium on. IEEE, 2005.
Comment: Ok, sorry, the notation is somewhat unclear since not everything was defined. I meant a random integer is selected. For example, if you have 3 particles, with weights $0.8$, $0.1$ and $0.1$, $Ji$ is $1$ with probability $0.8$, $Ji$ is $2$ with probability $0.1$ and $Ji$ is $3$ with probability $0.1$.
Comment: Side note, Are you sure this is multinomial resampling and not importance resampling?
Comment: So I'm trying to understand exactly do you mean by selecting random index Ji. what is Ji? and what do you mean by new random index. How many particles to set their x to a new value?
Comment: @TomIancovici: In multinomial resampling, all particles are resampled in principle (some may repeat their old value). I tried to clarify the notation.
Comment: But what I'm confused about is whether resampling is essential sampling the particles again for new weights, or does it involve rejecting the position of low weight, re positioning them near highly weighted particles. Then sampling weights again.
Comment: In essence, if the weight of a particle, e.g., $w^{(2)}$ is low, it is unlikely that   this particle is ever selected in the resampling (that is $J_i$ will not likely be $2$ for any $i$), and thus there will probably be $0$ copies of $x^{(2)}$ in the resampled set. On the other hand, if some particle has a high weight, it will probably get copied multiple times.
Comment: Oh def misunderstood your first comment here. That makes more sense. Essentially a random selection where the weights represent the probability of that index being selected. That's interesting.
Answer: Using a low variance sampling algorithm can improve the performance of the particle filter (both in computational complexity and accuracy). Instead of sampling from a multinomial distribution for each particle, you sample from a uniform distribution once and "stride" through your weighted samples. The technique is called "low variance" because the shape of the resulting distribution varies less from the shape of the distribution you are sampling from. Here is the alorithm:
function [X] = lowVarianceRS(X0, weight, M)
    X = zeros(1,M)                  % Initialize empty set of particles
    r = rand(0, M^-1)               % Select random number between 0-M^-1
    w = weight(1)                   % Initial weight
    i = 1
    j = 1

    for m = 1:M
        U = r + (m - 1)/M           % Index of original sample + size^-1
        while U > w
            i = i + 1
            w = w + weight(i)
        end
        X(j) = X0(i)                % Add selected sample to resampled array
        j = j + 1
    end
end

Where M is the number of particles in your filter. See Section 4.3.4 of [1] for more details.
References
[1] Thrun, S., Burgard, W., Fox, D. Probabalistic Robotics. 2006 Massachussetts Institute of Technology.


How to remove mobile device user's token from Owin server

Question: I have a problem about removing bearer token from Owin server. My plan is when mobile device user clicked Signout button then user token must removing from my owin server. Is there any  solution for this? If your answer no, I can change my idea and i open to different ideas.
Here is my Startup.cs:
<code>    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();

        config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

        ConfigureOAuth(app);
        WebApiConfig.Register(config);
        app.UseWebApi(config);
    }
    public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            TokenEndpointPath = new PathString("/api/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(7),
            AllowInsecureHttp = true,
            Provider = new SimpleAuthorizationServerProvider(),
            RefreshTokenProvider = new SimpleRefreshTokenProvider()
        };
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
</code>
Answer: The issue that you are having with this is that the bearer token lives on the client side so there really isn't much of a way to do it from your end.  The only way to de-authenticate the user in OAuth is to remove the token on the client side.
There are other ways that you could go about it such as creating a custom user session.  Check out this blog post for a more detailed description on how to do so: http://www.nakov.com/blog/2014/12/22/webapi-owin-identity-custom-login-service/
Another method you could go about this is shortening the lifespan of the token to a considerably short time.  This could have close to the same effect but I doubt is what you are looking for.
Comment: Okay. I tried Authentication.SignOut function but it didnt work well. I will try remove the token on the client side or change ExpireTime to shorter. Thanks..
Comment: Sounds good, let me know if it doesn't work and I'll dig into it a little more for you.
Comment: I forgot it sorry. This solution worked for me. Thanks.


Comparação de Horários em aproximação

Question: Como posso fazer um script para se hora atual estiver chegando a hora marcada fazer alguma coisa
  Exemplo

  date_default_timezone_set('America/Sao_Paulo');
  $hora_atual = date('H:i'); //11:45 Hora Atual
  $hora_marcada              // 12:00 hora marcada vem do banco

  se horario atual estiver faltando <= 15 minutos para a hora marcada{

  exemp .echo falta 15 minutos para saida
  }

Comment: Da uma olhada na classe DateTime do `php`
Comment: Ou pode-se usar o `time()` mesmo, ele retorna o timestamp atual, dai voce armazena em uma variável e inicio e acrescenta mais 15 minutos (com `tempo + (15*60)`) e armazena na variável saida, apos isso é so pegar a saida - a entrada e multiplicar por 60 para ter o numero de minutos restantes.
Comment: Funções time e date no PHP dão de mil a zero naquela porcaria de DateTime tanto em performance quanto simplicidade :)
Comment: @lvcs date tb faz :) `echo date('w');`
Comment: Depende de todo o resto do código que vc não colocou na pergunta. Em que variáveis está esse tempo, onde está o script, como vai ser executado, etc. - Normalmente é só um pequeno IF com uma conversão em minutos ou segundos, depende como armazena a data.
Comment: Concordo kk a vantagem o `DateTime` é que faz alguns cálculos automáticos, como dias de semana, etc. Mas pra questões mais simples (como na maioria das vezes) o `date` e `time` são um baile kk
Comment: Essa eu não sabia kk
Answer: Não iria responder pois estou no celular. Mas resolvi responder.
Pode-se usar a classe DateTime (maid recomendável), ou o time():
<?php
    $inicio = time(); #pega o tempo atual em segundos (timestamp)
    $fim = $inicio + (15 * 60); #acrescenta 15 minutos ao tempo anterior

    $x = $fim - $inicio; #pega quanto falta em segundos
    $x = $x / 60; # transforma em minutos

    echo "Faltam {$x} minutos";

    #pode comparar os valores, por exemplo:
    echo ($fim < time()) ? "Foi liberado" : "Ainda nao esta liberado";

     #olho se o numero de segundos do fim é menor que o tempo atual, se sim quer dizer que o tempo em fim ja se tornou passado

É claro que o exemplo sempre va falar que faltam 15 minutos, para funcionar normalmente as variáveis inicio e fim devem ser armazenadas em cookies ou sessão.
Deve funcionar, não testei, foi na mente kk
Editado
Agora sim, com a pergunta mais ou menos claro, assim resolve:
<?php
    date_default_timezone_set('America/Sao_Paulo');

    $fim = '16:30:00';
    $inicio = date("H:i:s", time());
    echo "inicio: {$inicio}
";
    echo "fim: {$fim}
";

    $arrayFim = explode(":", $fim);
    $arrayInicio = explode(":", $inicio);

    $horas = $arrayFim[0] - $arrayInicio[0];
    $minutos = $arrayFim[1] - $arrayInicio[1];
    $segundos = $arrayFim[2] - $arrayInicio[2];
    if($segundos < 0)
    {
        if($minutos > 0)
        {
            $minutos --;
            $segundos = 60 - $arrayInicio[2];
        }
    }
    echo "
horas: {$horas}
";
    echo "minutos: {$minutos}
";
    echo "segundos: {$segundos}
";

    if($horas <= 0 and $minutos <= 0 and $segundos <= 0)
        echo "
Expirado";
    else
        echo "
Nao expirou";

Da próxima, cite claramente qual a dúvida :)
Comment: Acho que tem alguma coisa errada ou eu não to sabendo usar.  sempre me retornando  54000 minitos para qualquer horario que coloque
Comment: Acabei me confundindo, é `$x = $x / 60;`
Comment: Outra confusão foi na comparação, não é `>` e sim `<`
Comment: algo ainda não funciona
Comment: coloquei aqui só pra demostração eu sei que no e para PHP https://jsfiddle.net/a5suy5xa/
Comment: Assim não vai funcionar,o tempo é marcado por segundos, estude sobre timestamp. Respondi o que a pergunta estava perguntando, que é sobre comparação de horas, você não deu detalhe suficiente, edite a pergunta ou faça uma nova.
Comment: Mais eu não mudei nada. só coloquei time zone, pra pegar a hora atual da região  e a minha pergunta é o que eu estou precisando, e não coloquei mais detalhes pois aceitava qualquer exemplo que funciona-se
Comment: Editei a resposta com outro código, da próxima seja mais claro na dúvida.
Comment: OK quase isso... e a questão dos 15 minutos? se eu entendi direito voce colocou... se a horario for igual ao atual --> Expirado senão não expirou
Comment: só comparar a variavel minutos, se ela for igual a 15 ou menor vc fala que falta menos que 15 minutos '-'

Comparação de Horários em aproximação


Is maximum likelihood a method for estimating parameters or estimating a distribution?

Question: I am narrowing down on some more solid idea of what MLE is, and what we use it for.
I keep running across different perspectives from different sources.
Some places, I read that maximum likelihood is a method for estimating parameters of a distribution, given we have some data.
Other places, I read that the maximum likelihood is itself a distribution.
What do we get from this process?  A set of parameters for a distribution we already are trying to fit?  Or do we get a 'new' distribution at the end of the process?  Or both?
Comment: Using a natural (and accurate) analogy that parameters are to distributions as addresses are to houses, one might similarly ask whether the process of looking up somebody's address is merely finding their address or actually finding where their house is. We could press this analogy in some fruitful directions. For instance, although everything that needs to be known about a house's location is in the address, someone who is unfamiliar with that area of the world might learn nothing about the house's neighborhood from its address alone. This is one reason we use "known" distributions for MLE.
Comment: The  key is that the E in MLE means estimation. So, MLE is estimating parameters and that means parameters of a model which means parameters of a distribution, simple or complicated as may be. I don't know that any meaning can be assigned to the idea that "maximum likelihood is itself a distribution"; it's a method that produces certain results (or failure to converge...). Perhaps what you're getting at is that the result is, or should be, a fitted distribution.
Comment: ML is (almost always) for parameters\*\*. But note that if you estimate the parameters of a distribution, you have also estimated the distribution itself (under the assumption of distribution family plus any additional assumptions). $ \quad $ \*\* even with ML there are infinite parametric cases, such as using $\hat F $ to estimate $F$ that correspond directly to estimating a distribution, so the distinction is sometimes not one.
Comment: I think you are right, fitted distribution seems like the correct term.
Comment: May be of some use for you to incorporate the idea of "conditional"? You may think of trying to estimate parameters for a _given_ (assumed) distribution (e.g., the mean assuming a normal population). Or maybe you are asking if, then, you get as result some sort of "distribution" for that parameter (e.g., a confidence interval for the mean)?
Comment: A maximum-likelihood estimate *has* a distribution - could that be what you read?
Comment: @Scortchi: http://stats.stackexchange.com/questions/85682/how-does-maximum-likelihood-estimation-have-an-approximate-normal-distribution
Answer: The Maximum Likelihood Estimator is derived as the argmax of the joint density of the sample, viewed as a function of the parameters (i.e. of the likelihood). Hence, one cannot apply maximum likelihood estimation without previously specifying (or deriving) a joint density, and hence a distribution. After all, this is one of the criticisms that ML estimation has received -that it must specify a distribution -not necessarily one of the "known" ones, but a distribution nevertheless-, increasing the possibility for misspecification.
If one views a distribution with unknown parameters as a family of distributions, then at the end of the process, we get a specifically parametrized incarnation of this family, using the ML estimates of these unknown parameters.
Comment: It depends on how do you understand "new distribution". Before estimation, you had an abstract distribution with unknown parameters, one incarnation of which was "picked up" by the MLE. If that means "new" to you, fine by me.
Comment: After we perform MLE over this suspected distribution, we are left with a set of estimated parameters that are associated with this distribution?  If so, the answer to my question is "both."


How can I preserve share paths when moving a share to a new server?

Question: I have 2 servers and I just moved most of the shares from server1 (SBS 2003 server) to server2 (Server 2003 Standard).
However, in sharepoint there are a lot of links that refer to the old server by name, ie, <code>\\server1\accounts</code>.
How can I have the shares physically on the new (larger) server, while preserving these links and having them still work.
Cheers,
Sam
Answer: Or you can go by the way which ms advising - use File Server Migration Toolkit (whitepaper)
It creates dfs root folder, in which both servers (old and new) are targeted. And than you remove old server fro dfs.
Comment: turns out to 'maintain original UNC paths' it requires server 2003 _enterprise_ or higher, whereas I am using small business server.
Comment: Although more playing shows that creating a DFS root on the original server pointing at the second server works well.
Answer: Are you keeping server1? If not, you can just add a manual DNS-entry in your domain-zone on your AD-server for server1, that points to server2.
Second option might be to rename server1 to something else, and then add a DNS-record for the old name (server1) that points to server2.
Comment: yes we are keeping server1