Query based on bearing movements - How many shifts they worked?

Question: Im working in a company where the colleagues in manufacturing are working in shifts. The shifting-system could be every month different. So its possible that the guys work one week only at Night, but next week Early, Late and Night.
Now I have a database, where i can see, what the colleagues have produced each and every day. Basically, i can see just the bearing movements. Theoretically, i can now say "ok, on 2017-04-27 they worked in 3 shifts, because there weare bearing movements in between 6:00am - 2:00pm, 2:00pm - 10:00pm and 10:00pm - 6:00am this day". There are hundreds of bearing movements each hour.
What i want to do now is: I want to find out, how many shifts the guys have been working each Month. So best result would be if i can get a query, which gives me the Monthnumber and next column the amounts of shifts for this month.
I guess the query has to check each day of the Month and check if there are entry for each possible shift, if so, than count a counter or something.
Table-Schema:
TABLE_NAME lb
COLUMN_NAME      DATA_TYPE
id               int
date_            datetime
time_            time
doc              varchar
pgroup           int
piece            varchar
amount           decimal
name1            varchar
name2            varchar
name3            varchar
storage_location int
bs               varchar
hash             varchar
inserted         datetime
edited           datetime

Sample Data (only from Column ID, date_, time_)
ID   date_                      time_
1   2017-02-06 00:00:00.000    10:05:34.0000000
2   2017-02-02 00:00:00.000    09:15:31.0000000
3   2017-02-02 00:00:00.000    16:19:12.0000000
4   2017-01-30 00:00:00.000    14:15:01.0000000
5   2017-01-30 00:00:00.000    21:35:10.0000000
6   2017-01-31 00:00:00.000    05:33:20.0000000
7   2017-01-31 00:00:00.000    05:36:07.0000000
8   2017-01-31 00:00:00.000    14:33:56.0000000
9   2017-01-30 00:00:00.000    06:25:25.0000000
10  2017-01-30 00:00:00.000    10:05:29.0000000
11  2017-01-30 00:00:00.000    15:25:26.0000000
12  2017-01-30 00:00:00.000    17:35:29.0000000
13  2017-01-30 00:00:00.000    21:05:26.0000000
14  2017-01-31 00:00:00.000    00:45:44.0000000
15  2017-01-30 00:00:00.000    08:15:25.0000000
16  2017-01-30 00:00:00.000    10:05:32.0000000
17  2017-01-30 00:00:00.000    15:25:29.0000000
18  2017-01-30 00:00:00.000    17:35:32.0000000
19  2017-01-30 00:00:00.000    21:05:30.0000000
20  2017-01-31 00:00:00.000    00:45:53.0000000

Output based on the sample data:
month   shifts
2       3
1       4

Is this possible?
Comment: show table schema.. also sample data and desired output
Comment: It all depend upon table structure and some data.how you storing Shift,datetime and other details ?system must have Shift Master and ShiftID must be store in attendance table.so this query is easy.
Comment: Added some more informations
Comment: How would you determine the number of shifts? Are all employees in a shit checking in and out at exactly the same time?
Comment: No, this doesnt matter. This data has nothing to do with the checking in of the employees.

I just need a counter which does the Following

---> for every day of the month

go through all day of that month, look up, if there is at least one entry which is inbetween 6am and 2pm, then count+1, if there is at least one entry which is between 2pm and 10pm, then count+1, if there is at least one entry which is between 10pm and 6am, then count+1. Do this for every day of the Month. Print out the Month number and the Counter.
Comment: Does the shift that starts Jan 31 at 10 and end on Feb 1 at 6 count for both months?
Comment: @GuillaumeCR No, it counts for that month when the shift starts, so in this example the shift starts Jan 31 at 10, so it counts for Jan
Answer: You can try something like this.
SELECT monthday AS "month", COUNT(monthday) AS "shifts" FROM
  (SELECT date_trunc( 'month', date ) FROM
    (SELECT DISTINCT date FROM lb
       WHERE '06:00:00'::time <= time AND time < '14:00:00'::time
     UNION ALL
     SELECT DISTINCT date FROM lb
       WHERE '14:00:00'::time <= time AND time < '22:00:00'::time
     UNION ALL
     SELECT DISTINCT date FROM lb
       WHERE '22:00:00'::time <= time AND time < '06:00:00'::time
    ) shiftdays
  ) monthdays (monthday) GROUP BY monthday;

(i did not have to time to check if it is syntactically correct, for mobile reasons).
Also, this is PostgreSQL Syntax, adapt it to your SQL Dialect.
How does it work?
This piece selects all days during the first shift. Each day only once (DISTINCT).
SELECT DISTINCT date FROM lb
  WHERE '06:00:00'::time <= time AND time < '14:00:00'::time

The same for the other shifts.
Then the days of these three shifts are thrown into the same bowl.
If you throw the same day in twice, it's in the bowl twice too (UNION ALL; i don't want to say group, because the GROUP already has a different meaning in SQL).
Now we have days for all possible days of the year (or at least all days rows in the table). Each day appears 0 <= n <= 3 times to count at most 3 shifts per day represented by 3 days in the temporary table.
Now we go from the days like '2017-01-15' to the month (with day = 01 each) by using date_trunc( 'month', date ).
We can only do this now, because if we try it earlier, then we cannot prevent more than three shifts per day, which are represented by at most three DAYS in the imaginary bowl.
And finally, now that we have the days aligned to months, we can group by and use count(*) = shifts.
The table aliases shiftdays and monthdays are required, lest the DBMS complaineth.
Use date_trunc( 'day', date ) to get rid of any seconds in your datetime (if necessary, not shown above; if you have milliseconds not 0000 in your datetime).
Use date_trunc( 'month', date ) to reduce all days to their month, then count them.
Make sure you have an index on columns (time, date) (in this order; time needs to be used with ranges <= and <; and datetime on the same index to be INDEX ONLY SCAN because you don't want the DMBS to go load tuples with 10 columns from the heap).
Three index only scans for the three shifts should be fine.
A full table scan will probably be not acceptable.
You can also mix in some WHERE clauses to just get the shifts-count for a single month, i.e. WHERE '2017-01-01' <= date AND date < '2017-02-01'. With an index on (date, time) that should be quite quick.
Note also the left inclusive ranges above (l <= date AND date < without = r).
So yeah, it's possible. Adapt it, and you're good to go.
Comment: Thanks! Will test it after the weekend1
Comment: Thank you! Changed it a bit and its working like charm!


On click slider next and previous button i get $curr[action] is not a function

Question: I am following this Js fiddle
http://jsfiddle.net/ryt3nu1v/10/
My Result:

I am making a slider that display age as I have an array that following ages
15,25,35,45,55
I am trying to display them in slider
expected behavior is to see the next age when i click on next button
Code that I used from fiddle according to my need is
          //Age slider
          $('div.result-age:gt(0)').hide(); //Hide all but the first one

var $allSlides = $('div.result-age'),
    traverseDefault = "first", //set the defaults
    actionDefault ="arrow-next";

$('.arrow-next,.selected-arrow-left-pointer').click(function(){

    var traverse = traverseDefault,
        action = actionDefault;

    if($(this).is('.selected-arrow-left-pointer')){ //if action is prev
        traverse = "last"; //set traverse to last in case nothing is available
        action = "selected-arrow-left-pointer"; //set action to prev
    }

    var $curr = $allSlides.filter(':visible'), //get the visible slide
        $nxtTarget =  $curr[action](".result-age"); //get the next target based on the action.

    $curr.stop(true, true).fadeIn(1000).hide(); //hide current one

    if (!$nxtTarget.length){ //if no next
        $nxtTarget = $allSlides[traverse](); //based on traverse pick the next one
    }

    $nxtTarget.stop(true, true).fadeIn(1000); //show the target

});
          //age slider end

And this is my HTML

ALL ages here currently being display all at once

My current style is that age will be displayed in center with left and right sides having next and previous button
What am I missing?
Comment: Can you make your code runnable ?
Comment: runnable as in?
If you are asking whether it is even functional or not, then it and i am editing the question to show picture
Comment: What I can see is that, in the jsfiddle you have attached on the top of the question, all the slides are predefined, so the next item is easily fetchable, but in your code, the data are not predefined. I mean only one slide is there, that could be the problem
Comment: add ```overflow:hidden``` css property and then let me know if it works
Comment: Uzair its not working
And Abin Thaha yes my data is not predefined as i am getting values from array
Comment: ok can you add runnable code snippet in the question because I tried running your code in jsfiddle its not displaying the slider
Answer: Your v-for is creating mutliple h4 tag but you need create result div for each numbers so move your v-for inside your div tag .Then , you are using wrong values for actionDefault and action it should be next & prev where next refer to next slide and prev refer to previous slide not the classnames .
Demo Code :

$('div.result-age:gt(0)').hide();
var $allSlides = $('div.result-age'),
  traverseDefault = "first",
  actionDefault = "next"; //use next ..refer next node

$('.arrow-next,.selected-arrow-left-pointer').click(function() {
  var traverse = traverseDefault,
    action = actionDefault;
  if ($(this).is('.selected-arrow-left-pointer')) {
    traverse = "last";
    action = "prev"; //use prev..refer prev..
  }

  var $curr = $allSlides.filter(':visible');
  $nxtTarget = $curr[action](".result-age");

  $curr.stop(true, true).fadeIn(1000).hide();
  if (!$nxtTarget.length) {
    $nxtTarget = $allSlides[traverse]();
  }

  $nxtTarget.stop(true, true).fadeIn(1000);
});
span.next,
span.prev {
  cursor: pointer;
}

    <<

1

2

3

 >>

Comment: I changed div class from h4's class to div in which it was inside and now it is working.
Thank you
Comment: Glad i was able to help you :)
Comment: Thank you swati but i have tried  loopin result-age div and the result is in column form as in my picture output that I gave in question
Comment: See html generated code if the divs are repeated . Also , put your entire code inside `$(document).ready(function(){ //all code inside ... })`
Answer: I found the issue, you were using arrow-next instead of next, and selected-arrow-left-pointer instead of prev.  Check the below working snippet. The data can be provided dynamically as you wish, currently I have given static data.
The next and prev are reserved keywords and hence the $curr[action] was expecting a function in return, while in your case it was `$curr['arrow-next'] instead of $curr['next'], which was returning undefined, and hence the error occurred.

//Age slider
      $("div.result-age:gt(0)").hide(); //Hide all but the first one

      var $allSlides = $("div.result-age"),
        traverseDefault = "first", //set the defaults
        actionDefault = "next";

      $(".next,.prev").click(function () {
        var traverse = traverseDefault,
          action = actionDefault;

        if ($(this).is(".prev")) {
          //if action is prev
          traverse = "last"; //set traverse to last in case nothing is available
          action = "prev"; //set action to prev
        }
        var currentData = $allSlides.filter(":visible"), //get the visible slide
          $nxtTarget = currentData[action](".result-age"); //get the next target based on the action.

        currentData.stop(true, true).fadeIn(1000).hide(); //hide current one

        if (!$nxtTarget.length) {
          //if no next
          $nxtTarget = $allSlides[traverse](); //based on traverse pick the next one
        }

        $nxtTarget.stop(true, true).fadeIn(1000); //show the target
      });
.next, .prev {
  cursor: pointer;
}

<

ALL ages here currently being display all at once

2

3

4

5

>

Comment: Currently the numbers are not being displayed as per the image, instead, only one slide will be active at a time. If that is what you are trying to achieve, you need to update styles using css
Comment: With the code you are trying it is not possible to achieve it. As per the current JS code provided, only one item will be visible in the UI at a time. You will require another js code to have a functionality as per the image, also you will require to do some css stylings as well.
Comment: Thanks Abin that solved my error but i am still getting the display as in my picture
Comment: You mean the css ?
Comment: Thank you it solved my error and i placed class of parent div in jquery code


Mixing personal (SMTP/POP) and business (Exchange) mail in Outlook

Question: Although I haven't done it, I'm pretty sure that you can set up Outlook (2010) to work with both SMTP/POP email and with Exchange simultaneously.
Here is the scenario: I work with a group of independent contractors and we want to have joint email, calendar and contacts for the work we do together - so we're thinking of using a hosted Exchange solution for this purpose.  At the same time, we want to maintain our own individual  personal/professional email/calendar/contacts using our respective SMTP/POP accounts.
If we are using Outlook, is it possible for these two to coincide peacefully?  Are there any pitfalls or compromises involved here?  Will Outlook happily show combined personal and exchange mail/contacts/calendars while keeping the personal stuff hidden from other Exchange users?  Or will it be a matter of having distinct mail accounts and calendars that have to be selected one at a time on the left hand side, without any integrated view of inbox/calendar/contacts?
Answer: Yes, multiple accounts can coexist well in Outlook. Even accounts of differing types, like Exchange, IMAP and POP3. By default, recent versions of Outlook will show each account under its own folder structure in the left pane of the main Window. A quick look on my Mac's Outlook 2011 shows that there's an option to allow a unified mailbox that groups items from all of the accounts into one view. Outlook 2010 doesn't have this, and it appears to require a bit of a hack to work this way.
Comment: The calendars will display in one window in layers. You can show the combined information or each account at a time. The calendar view is well-integrated.
Comment: Thanks for the answer and the link.  I could live with having two different inboxes if I had to.  The real problem would be two calendars.
Answer: I do this myself.
I have my work-exchange, my personal Google Apps and iCloud all syncing to the same Outlook on my Outlook - Work laptop, it works without any problems.
This is how my calendar looks:

I think you can consolidate them into one view, rather then x separate panels.
Comment: Thanks Bart.  In your setup, do you have one calendar with events from multiple accounts or do you have to select and view multiple calendars one after the other?
Comment: @JoelBrown Updated above ;-)


Live sum(value) data visualization in Grafana using InfluxQL

Question: I have a table that has many rows that follow this structure:
time                acknowledgement crit current_attempt downtime_depth execution_time hostname latency max_check_attempts metric reachable service state state_type value warn
----                --------------- ---- --------------- -------------- -------------- -------- ------- ------------------ ------ --------- ------- ----- ---------- ----- ----
1507171563000000000                 999                                                a01-pdu                             kw               pdu                      14.94 999
1507171621000000000                 999                                                a01-pdu                             kw               pdu                      14.92 999
1507171678000000000                 999                                                a01-pdu                             kw               pdu                      14.45 999
1507171736000000000                 999                                                a01-pdu                             kw               pdu                      14.93 999
1507171793000000000                 999                                                a01-pdu                             kw               pdu                      14.88 999
1507171852000000000                 999                                                a01-pdu                             kw               pdu                      14.92 999
1507171909000000000                 999                                                a01-pdu                             kw               pdu                      14.9  999
1507171995000000000                 999                                                a01-pdu                             kw               pdu                      14.91 999
1507171999000000000                 999                                                a02-pdu                             kw               pdu                      13.41 999

My goal is to get the last entry where hostname =~ /a01-pdu|a02-pdu/ and sum their value column
For exammple if I run:
SELECT last(value) AS last INTO pdu_abcd12 FROM pdu WHERE hostname =~ /a01-pdu/;
SELECT last(value) AS last INTO pdu_abcd12 FROM pdu WHERE hostname =~ /a02-pdu/;

SELECT sum(last) FROM (SELECT * FROM pdu_abcd12 ORDER BY DESC LIMIT 8)

time sum
---- ---
0    105.97

I am able to get the sum of those two values, but that requires me to run the influxQL commands above every time I want to see the data. Is there a way to have the commands run periodically so I can visualize the live data in Grafana?
Answer: Create continuous queries, for example:
CREATE CONTINUOUS QUERY last_sum ON <db name>
BEGIN
  SELECT last(value) AS last INTO pdu_abcd12
  FROM pdu
  WHERE hostname =~ /a01-pdu/
  GROUP BY time(1h), hostname
END

Note that CQs require a group by. Hostname is also included in group by above to account for multiple hostnames being matched by the regex. Their values would otherwise be selected together.
There are, however, several drawbacks to CQs, such as they are periodic meaning they only run once within the group by interval, they will not contain intermediate data between intervals, will not run if the DB is down leading to gaps in data, will generate unique fields when wildcard aggregations are used and so forth, see documentation.
Another option is Kapacitor and its more flexible, but also more involved, stream processing syntax.


Combinatorics (Yahtzee)

Question: Well I am trying to solve some math problems and I am stuck, I really need some help. Here are the problems, please feel free to help me out.
How many of the outcomes on a single "Yahtzee Throw" have:

four of a kind? (Example: 44446)
three of a kind? (Example: 44456)
two pairs? (Example1: 22334, Example2: 62565)
a full house? (Example1: 33322, Example2: 11666)
a large straight(There are two possible outcomes I think, 12345 or 23456)
yatzy? (Example1: 11111, Example2: 66666)

I am looking for clear and comprehensive explanations, otherwise I probably won't understand, I would greatly appreciate if you guys could take your time to really explain this to me like you would explain something to a child because I am having a hard time understanding this.
Regards!
Comment: There are a lot of questions here. Why don't you just ask one and see if the answer to that one gives you some insight into the rest? What are your thoughts on the number of yahtzees?
Comment: Also some people here have no idea what Yahtzee is and little inclination to look it up. I am guessing that you roll 5 fair dice, each with faces 1-6. Is that correct? So are you saying you have no ideas about how to solve 1. You have just shown 1 possibility. Can you think of any others? If all else fails, try writing them all down and counting them. There are not that many.
Answer: I wrote a blog post, Yahtzee probability, explaining in some detail how to calculate this.
For a single throw of five dice:
AAAAA      6     0.0772 %
AAAAB    150     1.929
AAABB    300     3.858
AAABC   1200    15.432
AABBC   1800    23.148
AABCD   3600    46.296
ABCDE    720     9.259  %

The left column is the dice pattern, so for example AABBC is two pair and AAABB is full house.  The middle column is the number of ways of rolling that pattern out of the 7776 possible rolls.  The right column is the chance of rolling the pattern, as a percentage.
Note that pattern ABCDE includes the large straights, which you may want to remove and count separately, and similarly some small straights are AABCD and some are ABCDE.
This tiny web application performs similar calculations for any number of dice.
Answer: "I am guessing that you roll 5 fair dice, each with faces 1-6. Is that correct?"
Yes, that is correct. My problem is that I can't seem to find a pattern.
I would do it like this: (Since order matter in yahtzee, meaning, picking 3 and 2 is not the same as 2 and 3)

P(6, 2) to get the different combinations of numbers. Then you can choose the dices for the first element in C(5, 4) ways and for the last one in C(1, 1) way. If you do this you get the correct answer wich is 150.
P(6, 3) to get the different combinations of numbers. Then you can choose the dices for the first element in C(5, 3) ways, for the second one in C(2, 1) ways and for the last one in C(1, 1) way. If you do this you get a wrong answer, the answer I am getting is 2400 which is not accurate.

I could go on but you can clearly see that I don't have an understanding of this and need some help.
I also read the link that the above poster posted but it didn't seem to help really :(. It did to some extent but not so I got a grasp around it. And you also brought the poker game up in the blog, I seem to understand that one fine because the order in poker doesn't matter. An example would be, that you have a "King Diamond" there would be no way that another "King Diamond" would show up in play. But in Yahtzee if one of the dices is showing a number 6 that doesn't mean that another one can't show the same number.
Comment: You seem to know a different type of Yahtzee than I do: In the version I know, the order doesn't matter (indeed, you throw all five dice at once, and they are indistinguishable, therefore there's no way to even establish an order).
Comment: A large straight is "2-3-4-5-6". But it does *not* matter which of the dice is 2, which is 3, which is 4, and so on. It just matters that each of those numbers appears. The same is true for all others. In no single case does the score depend on the order.
Comment: Ofcourse the order matters in Yahtzee? How many outcomes are there in Yahtzee? 6^5=7776, which means that 61111 is not the same as 11116. Where in poker D6-D2-D3-D4-D5 = D2-D4-D6-D5-D3, D standing for Diamond. So regarding to the dices, the order matters or not? Because one dice getting number 6 is not the same as another dice getting number 6?

Combinatorics (Yahtzee)


Is it possible to pass arguments to std::make_unique() when allocating an array?

Question: In the code below, is there any way that I can pass an argument to the demo constructor when using std::make_unique() to allocate a demo[] array?
class demo{
public:
    int info;
    demo():info(-99){} // default value
    demo(int info): info(info){}
};
int main(){
    // ok below code creates default constructor, totally fine, no problem
    std::unique_ptr<demo> pt1 = std::make_unique<demo>();

    // and this line creates argument constructor, totally fine, no problem
    std::unique_ptr<demo> pt2 = std::make_unique<demo>(1800);

    // But now, look at this below line

    // it creates 5 object of demo class with default constructor

    std::unique_ptr<demo[]> pt3 = std::make_unique<demo[]>(5);

    // but I need here to pass second constructor argument, something like this : -

    //std::unique_ptr<demo[]> pt3 = std::make_unique<demo[]>(5, 200);
    return 0;
}

Comment: Use `std::vector` instead.
Comment: Aside: from the title, I was expecting `std::unique_ptr[]`, not `std::unique_ptr`
Answer: std:::make_unique<T[]>() does not support passing arguments to the constructor of array elements.  It always invokes the default constructor only.  You would have to construct the array manually, eg:
std::unique_ptr<demo[]> pt3(new demo[5]{200,200,200,200,200});

Which is obviously not going to be useful if you have a large number of elements to create.  You could do something like this instead, if you don't mind re-initializing them after constructing them:
std::unique_ptr<demo[]> pt3 = std::make_unique<demo[]>(5);
std::fill_n(pt3.get(), 5, 200);

Otherwise, just use std::vector instead:
std::vector<demo> pt3(5, 200);


How to write a .Net UDP Scalable server

Question: I need to write a very high load UDP server. I'm using .Net. How do I use the Socket class to achieve this?
I am familiar with the winsock API, and completion ports, and what i would do there, is to use several threads to accept sockets using a completion port, and also to receive in the same manner.
My server needs to process a LOT of small UDP packets very quickly, and i want to receive them asynchronously, how do i do this using .net?
I thought of calling BeginReceive several times, but that kinda seems silly...
If anyone has a good .net example for this it would of course help a lot.
Answer: What I have found to minimize dropped packets is to read from the socket asynchronously as you mentioned, but to put the bytes read into a thread safe queue, then have another thread read off the queue and process the bytes.  If you are using .Net 4.0 you could use ConcurrentQueue:
<code>public class SomeClass {
    ConcurrentQueue<IList<Byte>> _Queue;
    Byte[] _Buffer;
    ManualResetEvent _StopEvent;
    AutoResetEvent _QueueEvent;
    private void ReceiveCallback(IAsyncResult ar) {
        Socket socket = ar.AsyncState as Socket;
        Int32 bytesRead = socket.EndReceive(ar);
        List<Byte> bufferCopy = new List<byte>(_Buffer);
        _Queue.Enqueue(bufferCopy);
        _QueueEvent.Set();
        if(!_StopEvent.WaitOne(0)) socket.BeginReceive(...);
        return;
    }
    private void ReadReceiveQueue() {
        WaitHandle[] handles = new WaitHandle[] { _StopEvent, _QueueEvent };
        Boolean loop = true;
        while (loop) {
            Int32 index = WaitHandle.WaitAny(handles);
            switch (index) {
                case 0:
                    loop = false;
                    break;
                case 1:
                    // Dequeue logic here
                    break;
                default:
                    break;
            }
        }
    }
}
</code>
Note: the _StopEvent is a ManualResetEvent so that both the ReceiveCallback and ReadReceiveQueue methods can use the same event to shut down cleanly.
Comment: It's a problematic approach, I gives no benifit if you have a constant high load, and is very difficult to manage the queue correctly(reading from the socket is a lot faster the processing).
Answer: If you only have a single socket and you can process UDP packets independently of each other, then the best approach would actually be to use a thread pool where each thread invokes a blocking Receive. The OS will take care of waking up one of the waiting threads to receive/process the packet. That way you can avoid any overhead introduced by the async-I/O routines.
Comment: this is a valid approach for medium load scenarios. but the overhead induced by creating a lot of threads will hamper your performance and scalability.
Comment: But you wouldn't be creating lots of threads - the size of the thread pool would roughly depend on the number of CPU cores.

How to write a .Net UDP Scalable server


Active Directory Delegation Help

Question: I am trying to get a junior team mate setup with rights on AD to create accounts, change passwords and create emails on exchange. What would be the best way to do this?
I tried half assing a delegation but I am not sure how to do it, so I stopped and backed out.
Can someone point me to an answer if they know the best way.
Thanks
Answer:
Survey the different collections of management tasks you need in AD.
Create AD Security groups to represent these tasks.
Delegate permissions, on OUs, to these groups based on role requirements.
Populate groups with users that will perform management tasks.

In our K12 domain, we've delegated out separate groups for managing staff user accounts, student user accounts, building computers and multiple server management groups.
Comment: +1 - You said the magic words re: using groups.
Answer: You're on the right track. Right click the domain, container, or OU  where you want to give the junior admin delegated rights and select Delegate Control, click Next, add the user and click OK, click Next, select the first three checkboxes, click Next, then click Finish. The junior admin will now be able to create and manage user accounts, reset passwords, and read all user account information. You can get as granular with Delegated Control as you want or need but this should at least get you what you need for the time being.
Comment: I'd give you a +1, but I have one beef. Never, ever, ever, ever, ever, ever, ever name individual users in permissin delegations. Create a group for the purposes of the delgation, name the group in the delegation, and put the appropriate user in the group. All permissions should be assigned to groups for very nearly any kind of resource. (User home directories are the only exception in my world...)  Using groups lets you easily replicate permissions for new users / turnover / etc.
Comment: @Evan: There are no absolutes in life or IT. You're right though, I should have recommended using a group.
Answer: The definitive guide on this topic is available from Microsoft here:
Best Practices for Delegating Active Directory Administration
Answer: There's an article on this issue:
Active Directory Delegation.
It explains a scope of activity of a third party solution, I should admit.
Thank you.

Active Directory Delegation Help


Duvida com relacionamento de tabelas MySQL

Question: Seguinte galera, tenho essas tabelas ai, estou estudando relacionamento de tabelas aqui...
Esse projeto não tem intenção nenhuma, a não ser praticar e estudar!
Eu relacionei a tabela categories e types a products como 1 para muitos...
Onde um produto pode ter apenas uma categoria e tipo...
já tipo e categoria pode ter vários produtos..
Como produto nesses 2 caso ficou no lado de vários, então pelo q aprendi a chave estrangeira fica no lado do vários!
e na tabela addeds e deletions é apenas um complemento pra tabela products.. onde ficou no relacionamento 1 para 1...
a minha duvida é como relacionar de forma correta a tabela updates com a tabela products!
Já q um produto pode ter vários updates, e tabela updates pode ter updates de varios produtos..
Fiquei meio confuso, com esse cenário... Alguém poderia me falar como ficaria? e tentar fazer um resumo pra que eu possa entender um pouco melhor..
obrigado a todos desde já!
Answer: Porque não uma relação de 1-M? O mesmo produto pode ser alterado varias vezes, por isso as entradas da tabela updates terão um referência para a entrada na tabela products à qual a alteração se refer.
Em modo desafio, o mesmo objectivo pode ser tratar as inscrições, remoções e alterações sempre na mesma tabela (actions, por exemplo) e diferenciar entre as várias acções por um campo.
Comment: isso mesmo, eu tinha chegado nessa conclusão tbm, acabei fazendo relacionamento de 1 para m!

E mudei algumas coisas..
Andei estudando mais sobre modelagem..
E cheguei na conclusão que algumas coisas estavam fora de convenção..

No mais, muito obrigado, agradeço pela atenção e pela ajuda..


Melhor algoritmo possível

Question: Venho novamente com uma dúvida voltada para a área de Complexidade de Algoritmos, mas desta vez como escolher o algoritmo mais eficiente, para isto vamos considerar as duas expressões abaixo:
Algoritmo 1: f1(n) = 2n² +5n operações
Algoritmo 2: f2(n) = 500n + 4000 operações
Visto que o algoritmo 1 possui O(n²) e o algoritmo 2 O(n), o algoritmo 1 é dado como o pior caso possível para esta solução, tendo o segundo como a solução mais eficaz e plausível.
A minha dúvida é saber se a escolha de um algoritmo mais eficiente é feita desta forma, pois estou progredindo na matéria, porém dúvidas são recorrentes.
Espero que possam me ajudar, e que eu tenha sido objetivo o suficiente, agradeço desde já.
Obrigado.
Comment: Quais os parâmetros usados para a comparação?
Comment: @MagicHat - Apenas análise assintótica
Comment: @MagicHat - Primeiro, eu achei este exemplo na internet enquanto procurava conteúdos para estudo, segundo, esta é a minha dúvida, não sei ao certo definir um melhor ou pior :/
Comment: Julguei também que o primeiro eu utilizo n² passos, e como uma funçao quadrática é maior que uma singular n... pensando bem, o crescimento de n² seria mais rápido, mas não sei o melhor
Comment: Por exemplo: Ao meu ver em se tratando de algo que será processado, em cada uma das das instruções são realizadas operações internas, então a 1º opção indica que há 4 operações e na 2º  apenas 3...Entretanto em outro cenário pode ser o contrário...
Comment: @MagicHat, "então a 1º opção indica que há 4 operações e na 2º apenas 3", como você chegou a conclusão que na primeira haveria 4 operações e no segundo 3?
Comment: 1º - Potência 2º 2xmultiplicação 3º adição... Ex: seu eu fizer 1+1+1+1+1+1+1 = 7 é pior que 7=7...
Comment: @MagicHat: Neste caso você faz os cálculos de quantas operações são feitas com base na quantidade de operações apresentadas na expressão? como o algoritmo 12n² +5n, possui 2 multiplicações, uma soma e uma potência, sendo assim 4 operações, esta era uma dúvida minha, foi sanada até o momento.
Comment: @MagicHat - então a última dúvida, o melhor algoritmo ali seria o segundo? e o pior caso o primeiro?
Comment: @MagicHat - Eu classificaria assim mesmo, primeiro como pior, eu não sei muito sobre isso
Comment: @MagicHat - Certo então, para estes comentários não se estenderem mais e sermos alertados (não sei como funciona), estarei encerrando aqui, com o que foi apresentado acho que posso tirar um bom proveito, você me ajudou bastante, muito obrigado.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/55583/discussion-between-felix-and-magichat).
Answer: Calculando o comportamento dos algoritmos
A análise da complexidade de um algoritmo demonstra qual seria o seu desempenho com entradas de tamanho tendendo ao infinito. No entanto, para um número razoável de elementos, isso pode não ser o caso.
Para o seu caso, existe algum número n para o qual, além dele, o algoritmo linear será sempre mais rápido. Entretanto, determinar qual é esse n é um tanto difícil, pois ele pode variar de máquina para máquina e uma operação no algoritmo f1 pode demorar um tempo diferente do que uma operação no algoritmo f2.
Assim sendo, até um determinado ponto, o algoritmo f2 deve ser mais rápido, sendo então alcançado e ultrapassado por f1 deste ponto em diante.
Supondo que os dois algoritmos tenham operações com as mesmas velocidades e rodem na mesma máquina sob as mesmas condições (o que provavelmente não é uma suposição válida no mundo real, mas vamos presumir isso para facilitar o cálculo), podemos encontrar o valor de n onde um algoritmo ultrapassa o outro assim:

f1(n) = f2(n)
  2n² + 5n = 500n + 4000
  2n² - 495n - 4000 = 0
  n = (495 ± sqrt(495² - 4 * 2 * - 4000)) / (2 * 2) [aplicação da fórmula de Bhaskara]
  n = (495 ± sqrt(245025 + 32000)) / 4
  n = (495 ± sqrt(245025 + 32000)) / 4
  n = (495 ± sqrt(277025)) / 4
  n = (495 ± 526.33) / 4
  n = (495 + 526.33) / 4 OU n = (495 - 526.33) / 4
  n = 1021.33 / 4 OU n = -31.33 / 4
  n = 255.33 OU n = -7.83

Como n < 0 não faz sentido (o tamanho da entrada não tem como ser menor que zero), então:

n = 255.33

Ou seja, para um n ≤ 255, o algoritmo f1 é mais rápido. Para n ≥ 256, o algoritmo f2 será mais rápido. Prova disso é que:

f1(255) < f2(255) → 131325 < 131500
  f1(256) > f2(256) → 132352 > 132000

Por que usa-se apenas o termo de maior grau e despreza-se as constantes?
Novamente, friso que a análise de complexidade é dada com um n tendendo ao infinito. Neste caso, numa expressão do tipo 2n² + 5n, o fator 5n rapidamente se tornará desprezível perto do 2n², e portanto pode ser deixado de lado. Semelhantemente, numa expressão 500n + 4000, o fator 500n crescerá tanto de modo que o 4000 se tornará desprezível. Por isso é que apenas o termo de maior grau é considerado na análise de complexidade.
Quanto às constantes multiplicativas, ao comparar-se expressões com diferentes graus quando n tende ao infinito, a constante também acaba por ser irrelevante. Por exemplo, sejam p e g duas constantes, onde p é muito pequena e g é muito grande. Ao comparar-se pn² com gn tendo n tendendo ao infinito, haverá algum ponto onde o fator pn² crescerá de tal modo que ultrapassará o valor de gn (tal como fiz no cálculo acima), e portanto a expressão de maior grau sempre vai ultrapassar a de menor grau, independente das constantes utilizadas. Desta forma, quando n tende ao infinito, faz sentido apenas de falar-se do termo de maior grau, desprezando-se os coeficientes e os termos de menor grau.
Uma outra consequência da eliminação das constantes é que se você tem dois algoritmos A e B com complexidades de tempo de graus diferentes, não importa qual seja a máquina mais rápida, mesmo que uma delas execute instruções 10 vezes mais rapidamente que a outra (ou 100 vezes, ou um milhão de vezes), sempre haverá algum ponto n onde o algoritmo com a complexidade de maior grau será mais lento que o de menor grau (é verdade que é possível que este ponto seja para um tamanho de entrada monstruoso e para um tempo absurdo e fora do aceitável no mundo real, mas mesmo assim esse ponto existe).
Por outro lado, se os dois algoritmos C e D têm complexidades com o mesmo grau, mas o C é mais 2 vezes mais lento, basta eu conseguir uma máquina que seja mais do que 2 vezes mais rápida e então o algoritmo C ultrapassará o D. Os termos de menor grau não irão interferir nisso para um n suficientemente grande porque ao conseguir uma máquina mais rápida, eu estarei multiplicando/dividindo os tempos dos termos de maior grau também, de forma que para um valor suficiente de n a diferença de desempenho obtida com os termos de maior grau irá superar qualquer deficiência referente aos termos de menor grau.
Exemplos concretos
Um exemplo concreto onde algo assim acontece é na multiplicação de números: o algoritmo aprendido na escola é O(n2), enquanto que o algoritmo de Karatsuba é bem mais complexo (e portanto tem constantes multiplicativas maiores), mas é O(n(log2 3)). Para números grandes, o algoritmo de Karatsuba é mais rápido. Para números pequenos, usa-se o algoritmo aprendido na escola.
Aliás, há também o algoritmo de Schönhage–Strassen que bate o algoritmo de Karatsuba em números bem grandes, com dezenas de milhares de casas decimais, tendo ele uma complexidade O(n log(n) log(log(n))).
Assim sendo, para números pequenos, o algoritmo mais rápido é o da escola. Para os números de tamanho médio, o Karatsuba mostra-se mais rápido. Para os números bem grandes, usa-se o Schönhage–Strassen.
Finalmente, o algoritmo de Fürer em teoria bate o Schönhage–Strassen tendo complexidade O(n log(n) 23 log*(n)), mas suas constantes multiplicativas são tão altas que ele teoricamente só supera o Schönhage–Strassen em números com dezenas de quintilhões de dígitos (e por esse motivo ele é mais uma curiosidade teórica do que algo que você usaria na prática).
Ah, e eu nem entrei no mérito do algoritmo de Toom-Cook que é uma generalização do algoritmo da escola e do Karatsuba.
Um outro caso é o algoritmo Timsort que é um algoritmo que utiliza internamente, de forma seletiva e dinâmica, o merge sort ou o insertion sort em diferentes partes dos dados dependendo de como eles estão organizados, tentando aproveitar o melhor de cada algoritmo onde for conveniente e tentando se aproveitar de ordenações parciais já existentes.
Ou seja, se você quiser perguntar "qual o algoritmo mais eficiente?", deve-se perguntar primeiro "quais são os tamanhos da entrada que me interessam?" - esse detalhe pode mudar tudo.
O uso de O, Ω e Θ
Além disso, a análise com o O se refere ao pior caso, não ao caso médio ou ao melhor caso. Por exemplo, o quicksort para entradas aleatórias tem um caso médio bem melhor que merge sort. Apesar de ambos terem casos médios O(n log n), o quicksort tem constantes multiplicativas menores. Entretanto, o pior caso do quicksort é O(n2), enquanto que o do merge sort sempre é O(n log n).
A notação O significa um limite superior. Ou seja, um algoritmo com complexidade O(n²) nunca vai levar um tempo pior do que quadrático para executar. Entretanto, esse limite pode ser frouxo, tal como é no quicksort, onde embora ele execute no máximo em tempo quadrático, ele pode em vários casos executar em um tempo bem menor do que isso.
Também há o limite inferior, que é dado por Ω. O algoritmo quicksort é Ω(n log n) porque ele nunca roda em tempo menor do que n log n. Ou seja, enquanto que o O diz qual é o pior caso, o Ω diz qual é o melhor. O uso de Ω não é muito comum, mas serve para se definir um ponto a partir do qual seria impossível uma melhoria que não se restrinja apenas às constantes multiplicativas ou aos termos de menor grau. Por exemplo, é sabido que Ω(n log n) é o limite inferior para algoritmos de ordenação de elementos baseados em comparação, e portanto sabe-se que não existe e que é algo impossível ter-se um algoritmo de ordenação de elementos com tempo melhor do que n log n.
E quando o melhor e o pior caso coincidem, surge o Θ. Um algoritmo pode ser dito Θ(k) se ele sempre executar em tempo k, tanto no melhor quanto no pior caso. Por exemplo, o merge sort é Θ(n log n), pois em todos os casos ele tem um tempo proporcional a n log n.

Melhor algoritmo possível


Hidden Markov model thresholding

Question: I have developed a proof of concept system for sound recognition using mfcc and hidden markov models. It gives promising results when I test the system on known sounds. Although the system, when an unknown sound is inputted returns the result with the closest match and the score is not that distinct to devise it is an unknown sound e.g.:
I have trained 3 hidden markov models one for speech, one for water coming out of water tap and one for knocking on the desk. Then I test them on unseen data and get following results:
input: speech
HMM\knocking:  -1213.8911146444477
HMM\speech:  -617.8735676792728
HMM\watertap:  -1504.4735097322673

So highest score speech which is correct

input: watertap
HMM\knocking:  -3715.7246152783955
HMM\speech:  -4302.67960438553
HMM\watertap:  -1965.6149147201534

So highest score watertap which is correct

input: knocking
HMM\filler  -806.7248912250212
HMM\knocking:  -756.4428782636676
HMM\speech:  -1201.686687761133
HMM\watertap:  -3025.181144273698

So highest score knocking which is correct

input: unknown
HMM\knocking:  -4369.1702184688975
HMM\speech:  -5090.37122832872
HMM\watertap:  -7717.501505674925
Here the input is an unknown sound but it still returns the closest match as there is no system for thresholding/garbage filtering.

I know that in keyword spotting an OOV (out of vocabulary) sound can be filtered out using a garbage or filler model but it says it is trained using a finite set of unknown words where this can't be applied to my system as I don't know all the sounds that the system may record.
How is a similar problem solved in speech recognition system? And how can I solve my problem to avoid false positives?
Answer: This is somewhat common in the field of gesture recognition. The answer is to create a threshold model as described in the paper by Lee and Kim (1999)
It plays the same role as a filler or garbage model, but it doesn't need to be trained separately as you says. You can create a threshold model by connecting all self-transition states from your other models and initializing the transition with uniform probabilities, fully connecting those states. Please take a look on the paper to see how it can actually be done.
Even if your library does not support ergodic models, it shouldn't prevent you from manually creating a model of the required size and setting the states accordingly. If you would really want a library for that, then implementations for hidden Markov model classifiers including support for threshold models are available in the Accord.NET Framework, for example.
Disclaimer: I am the author of this library.
Comment: Not quite... perhaps I was a bit loose on my description. The diagonal elements of your transition matrix for the threshold model receives the original self-transition probabilities from your other models. The transitions from a state to other states are initialized with uniform probabilities. I know it may seems lazy to point it out to the code, but sometimes [code is easier to understand than formulas](https://code.google.com/p/accord/source/browse/trunk/Sources/Accord.Statistics/Models/Markov/Learning/HiddenMarkovClassifierLearning.cs#162).
Comment: Right I can manually create a threshold model. So lets say for example I have two hmm models named: sound1 and sound2. Both have 2 states. Then I create a threshold model with 4 states. Each state has the same initial value which is 0.25. Then I set uniform distribution for all possible transitions so all possible state transitions (0,0), (0,1), (1,0), (1,1), (1,2), (2,1), (2,2), etc. get an uniform distribution of 0.0625. Then for state 1 and 2 of the threshold model I set the opdf of state 1 and 2 from sound1 and for state 3 and 4 of the threshold I set the opdf of state 1 and 2 from sound2.
Comment: Is the approach described above correct?
Comment: By the way, if you have read the paper by Lee and Kim and have interpreted it differently, or believes my implementation is incorrect, please let me know.
Answer: Very good question!
As you mention, the only way to get the HMM to give you an "I don't know" (let's call it OOV) answer is to give it a special state because it always outputs the states with the highest likelihood under your model. So you have to ensure that OOV has higher likelihood under every input that is not speech, watertap or knocking.
The short answer is that this is not possible. Because an HMM is not an absolute pattern recognizer. It only compares the likelihood of the outputs under your model, and in the context it was trained.
Think about an input that would be speech and knocking at the same time. Most likely the HMM will "hesitate" between these two states because this input has features of each. In the end it would output one of those, but it is quite unlikely that it would output OOV. In the case of keyword spotting, my guess is that you could find clever inputs that would consistently fool their HMM. However, the authors probably know what input to expect and they have chosen their finite list of unknown words so that these poisonous inputs are uncommon.
I advise that you do the same. Think about the situations that you will use the HMM and train an OOV state on the most common inputs you wish to eliminate. You can even think of having several OOV states.
Comment: But how about an hmm based threshold model for gesture recognition described here : http://herin.kaist.ac.kr/Publication/PS/hklee_PAMI_i09611.pdf . They create a threshold model which is an ergodic hmm that has states of each hmm combined together. "The threshold model acts as a base-line. A candidate gesture is found when a specific gesture model rises above the threshold" But my problem is that I am using java and jahmm library and I don't think it has the option for ergodic hmm.
Comment: Like it says in the title, this is an HMM-based algorithm, so it is not an HMM. It seems to me that a pure HMM does not fit your needs, and that a threshold-based classifier is indeed better suited.
Answer: So what I have done is: I created my simplified version of a filler model. Each hmm representing watertap sound, knocking sound and speech sound is a seperate 6 state hmm trained by sounds from training set of 30, 50, 90 sounds respectively of various lengths 0.3 sec to 10 seconds. Then I created a filler model which is a 1 state hmm consisting od all the training set sounds for knocking, watertap and speech. So if the hmm model score is greater for a given sound than the filler's score - sound is recognized otherwise it is an unknown sound. I don't really have large data but I have perfoormed a following test for false positives rejection and true positives rejection on unseen sounds.
true positives rejection
knocking 1/11 = 90% accuracy
watertap 1/9 = 89% accuracy
speech 0/14 = 100% accuracy

false positives rejection
Tested 7 unknown sounds
6/7 = 86% accuracy

So from this quick test I can conclude that this approach gives reasonable results although I have a strange feeling it may not be enough.
Comment: +1 This is very interesting. If you have not forgotten about this work already, did this approach work in the end? Was it enough as a 'filler / other' model? If not, did you implement something else eventually?

Hidden Markov model thresholding


Which type of time series is my data? Random Walk? MA? White Noise?

Question: I am given a time series data. I read that there are several types of such a data, namely, Random Walk, Moving Averages and the White Noise. This I discovered here.
Before doing any analysis, should I first to determine the type of time series or is it sufficient to check for (weak) stationarity?
At the end, I have to do spectral analysis.
Answer: I dont know much about spectral analysis, but judging from this source (https://www.stat.ncsu.edu/people/bloomfield/courses/st730/slides/sns-04-2.pdf) you can derive the spectral density function by figuring out what type of data generating process could underlie your time series. To explore this, just testing for stationarity is insufficient. For example, both an AR(1) with coefficient lower than 1 in absolute terms and a white noise process are (weakly) stationary processes. However, their autocorrelation structure differs.
I would advise you to inspect the autocorrelation functions and partial autocorrelation functions to determine what kind of arima(p,i,q) fits your time series best. Here is a link to a nice post that explores this topic more indepth Estimate ARMA coefficients through ACF and PACF inspection. Without additional information of your time series it is impossible for us to determine what kind of process might have generated it.
Comment: Thank you for your response. This will help me a lot.


Problems creating a custom volume control for HTML5 Video

Question: I have a fairly complex project in the works that requires a custom volume slider to control an HTML5 video element.  I've boiled the volume control down to a very simple example and I see no reason why it should not be working.  I would love any insight regarding the following code:
jQuery:

HTML:
<video id="video" controls="controls">
    <source src="http://dev.domain.com/media/16514.m4v">
</video>

<input id="volume" type="range" min="0" max="100" value="100" />

It should be noted that every aspect of this appears to work except an audible change in volume on the video clip.  Even the console.log result is returning the correct value (0 through 1.00)  I have also tried the strictly Javascript version of this, i.e. videoElement.volume = newvolume
If it's significant, I am testing in Safari 5.1.2.
Answer: Instead of $('#video').attr("volume", newvolume);, try this:
$('#video')[0].volume = newvolume;

If memory serves, volume is not an attribute of video in HTML5, it is only accesible via the DOM element itself.


page.tpl.php override for Panels Pages?

Question: I want to use a specific tpl.php file for all Panels Custom pages.
I get some formatting issues if I try to use "Panels Everywhere" module, so would like an alternative.
Answer: You can use a template_preprocess_page function to add your custom tpl for Panels page. Here's how:
<code>/**
 * Implements template_preprocess_page().
 */
 function MODULEORTHEMENAME_preprocess_page(&$variables) {
    if (module_exists('page_manager') && count(page_manager_get_current_page())) {
        $variables['theme_hook_suggestions'][] = 'page__panels';
    }
 }
</code>
Then create a page--panels.tpl.php for your custom Panels page.
Answer: @arshacn answer is correct, as the question is to affect all panel pages, but if you need a separete tpl, or only affect a few, for any contentype do this:
<code>// ads theme-hook-nodetype-suggestions
      function MYMODULEORMYTHEME_preprocess_page(&$vars, $hook) {
        if (isset($vars['node']->type)) {
        $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
        }
    }
</code>
this will add "page--yourcontentype.tpl.php" suggestion, then create a page--yourcontentype.tpl.php for every contentype needed, place tpl file in your subtheme template folder.

page.tpl.php override for Panels Pages?


Disable ScriptManager on certain pages

Question: I have a script manager on my Master page. There are one or 2 content pages that I need to remove the webresourse.axd from, as it is causing issues with other javascript on the page
How can I disable the script manager on these pages?
The ScriptManager object doesnt appear to have any properties that would seem like they would do the job
Is this possible?
Answer: Move your <asp:ScriptManager /> to a custom control e.g. MyScriptManager.ascx - the only code in the .ascx file will be the ScriptManager tag - then you can set the Visible property on your custom control to control whether the ScriptManager gets rendered.
<foo:MyScriptManager id="scriptManager" runat="server" Visible="false" />

You could maybe even add a Property to your MasterPage which you could use in your content pages to show / hide the ScriptManager:
// In your master page
public bool ShowScriptManager {get; set;}

// In your master page's Page_Load
private void Page_Load(object sender, EventArgs e) {
    ...
    scriptManager.Visible = ShowScriptManager;
    ...
}

As most of your pages require the ScriptManager, it might be an idea to make it default to true - I think you can do this in your Master Page's constructor of Page_Init method:
public SiteMaster() {
    ...
    ShowScriptManager = true;
    ...
}

// Or alternatively
private void Page_Init(object sender, EventArgs e) {
    ...
    ShowScriptManager = true;
    ...
}

Then, if you've set the MasterType in your content pages:
<%@ MasterType VirtualPath="~/path/to/master/page" %>

You just need to do something like this in content page's Page_Load:
Master.ShowScriptManager = false;

Comment: Atta boy. Nice solution. I just spent 4 hours experimenting to come up with the same solution. I should have come here first!
Comment: If a ScriptManager is present in my iframe, I always get a "page dispose" javascript error when I try to load a PDF file in the iframe. Your technique allows me to do it smoothly and avoid the error. Thanks!
Answer: You could also put the script manager into a ContentPlaceHolder,
<asp:ContentPlaceHolder ID="cph_ScriptManager" runat="server"></asp:ContentPlaceHolder>
    <asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>
</asp:ContentPlaceHolder>

and on the pages you want to remove it , have a asp:Content tag point at it, and it will remove it from the page:
<asp:Content ID="content_SM_Overrride" ContentPlaceHolderID="cph_ScriptManager" runat="server">

</asp:Content>

Answer: For anyone who ends up here and still can't get it to work with a UserControl...
If you are using .Net 4.0 you can use the new AjaxFrameworkMode property and set it to Disabled.
ScriptManager.AjaxFrameworkMode Property
Hope that helps someone!
Comment: Thanks, this should be the answer!
Answer: I would use nested master pages.  A base master that has your markup with an extra content place holder where the script manager would be.  Then two versions of the nested master, one with a script manager and one without.  And your pages use the appropriate nested master page.
I'm leaving in the text below so the comments make sense, but this doesn't work...
How about this:
-Put an appsetting in your webconfig with a list of URI's that you don't want to have a script manager.
-In the page_init event handler of the master, get that collection and test to see if the current page request is in the list.  If so, remove the scriptmanager from the controls collection of the master.
ie, in the master page code behind:
Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    If DirectCast(Page, System.Web.UI.Page).AppRelativeVirtualPath = "~/Test.aspx" Then
        Me.Controls.Remove(Me.FindControl("ScriptManager1"))
    End If
End Sub

Note: There is a lot of danger in what you're doing.  If your master page has any update panels, or any of the pages you are removing the manager on have them, they will bomb out.  You could loop through the control collection of the master and the page in the masters init and check for any update panels as well.  Although, I'm not sure what you would do if you found them.  Removing them would likely remove any content in them.  At best, you could either 1) not remove the Script Manager if an update panel is found, or 2) Customize the error.
Comment: agreed, on pages that you plan on removing the script manager, you should not have a update panel.  but that problem is inherit in his question: in other words, it is a problem with any page that removes the script manager, and that's what he's asking to do.
Comment: yes - I am looking how to remove the script manager.
I havwe tried the following
ScriptManager sm = (ScriptManager)Master.FindControl("sm");
            sm.Visible = false;

but that gives an error :
The method or operation is not implemented.

So the question is simply:
How do you remove the script manager from a page
There are no update panels or anything like that on the pages in question
Comment: thanks for that.
It still renders the scriptrersource.axd
I also tried

            Master.Controls.Remove(Master.FindControl("sm"));

but that didnt help either
hmmmm...back to the drawing board I think
Comment: I see what you mean.  I tried ScriptManager1.Scripts.Clear() in init, load, and pre_render and couldn't get the script to not show up on the page.  I'll add another method above

Disable ScriptManager on certain pages


c++ how to make lock free stack push atomic

Question: I need to write a void push(const T& val) implementation for lock free stack.
The problem is that compare_exchange_weak expects non atomic node* but I must use std::atomic<node*> next field instead of regular node* next.
I tried to solve this problem by doing this
void push(const T& val) {
    node* new_node = new node(val);
    node* local_next = new_node->next.load();
    while (!head.compare_exchange_weak(local_next, new_node));
}

But creating if local_next makes things even worse. I tested 2 variants of code. The first one has non-atomic field node* next and I lost about 20-30 elements in the test code below. And using the second variant I got a deadlock.
Test code:
#include <iostream>
#include <thread>
#include <atomic>
#include "lock_free_stack.h"

using namespace std;

void test(lock_free_stack<int>& st, atomic<int>& sum) {
    st.push(1);
    shared_ptr<int> val(st.pop());
    while (val == nullptr) { }
    sum.store(sum.load() + *val);
}

int main(int argc, const char * argv[]) {
    atomic<int> sum;
    sum.store(0);
    for (int i = 0; i < 100; ++i) {
        lock_free_stack<int> st;
        thread t1(test, ref(st), ref(sum));
        thread t2(test, ref(st), ref(sum));
        thread t3(test, ref(st), ref(sum));
        thread t4(test, ref(st), ref(sum));
        thread t5(test, ref(st), ref(sum));
        thread t6(test, ref(st), ref(sum));
        thread t7(test, ref(st), ref(sum));
        thread t8(test, ref(st), ref(sum));
        t1.join();
        t2.join();
        t3.join();
        t4.join();
        t5.join();
        t6.join();
        t7.join();
        t8.join();
    }
    if (sum.load() == 800) {
        cout << "CORRECT" << endl;
    } else {
        cout << "TIME TO REWRITE STACK " << sum << endl;
    }
    return 0;
}

And the code of my lock free stack (first variant):
#ifndef lock_free_stack_hard_lock_free_stack_h
#define lock_free_stack_hard_lock_free_stack_h

template <typename T>
class lock_free_stack {
private:
    struct node {
        node* next;
        std::shared_ptr<T> value;
        node (const T& val) : value(std::make_shared<T>(val)) { }
    };
    std::atomic<node*> head;
    std::shared_ptr<T> default_value;

public:
    lock_free_stack() : head(nullptr), default_value(std::make_shared<T>()) { }

    void push(const T& val) {
        node* new_node = new node(val);
        new_node->next = head.load();
        while (!head.compare_exchange_weak(new_node->next, new_node));
    }

    std::shared_ptr<T> pop() {
        node* old_head = head.load();
        while (old_head && !head.compare_exchange_weak(old_head, old_head->next));
        if (old_head) {
            return old_head->value;
        } else {
            return std::shared_ptr<T>();
        }
    }
};

#endif

And the second variant:
#ifndef lock_free_stack_hard_lock_free_stack_h
    #define lock_free_stack_hard_lock_free_stack_h

    template <typename T>
    class lock_free_stack {
    private:
        struct node {
            std::atomic<node*> next;
            std::shared_ptr<T> value;
            node (const T& val) : value(std::make_shared<T>(val)) { }
        };
        std::atomic<node*> head;
        std::shared_ptr<T> default_value;

    public:
        lock_free_stack() : head(nullptr), default_value(std::make_shared<T>()) { }

        void push(const T& val) {
            node* new_node = new node(val);
            new_node->next = head.load();
            node* local_next = new_node->next.load();
            while (!head.compare_exchange_weak(local_next, new_node));
        }

        std::shared_ptr<T> pop() {
            node* old_head = head.load();
            while (old_head && !head.compare_exchange_weak(old_head, old_head->next));
            if (old_head) {
                return old_head->value;
            } else {
                return std::shared_ptr<T>();
            }
        }
    };

    #endif

So the final question is how to create that local_next correctly?
Thank you.
Comment: The example for [`compare_exchange_weak`](http://en.cppreference.com/w/cpp/atomic/atomic/compare_exchange) actually implements a lock free `stack::push`.
Comment: @Barry, field `node* next` actually should look like `std::atomic next`
Comment: you may be hitting a compiler bug: [msvc](https://connect.microsoft.com/VisualStudio/feedback/details/819819/std-atomic-compare-exchange-weak-has-spurious-write-which-can-cause-race-conditions), [clang](http://lists.cs.uiuc.edu/pipermail/llvmbugs/2014-February/032833.html), and [gcc](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60272) all had problems compiling compare_exchange_* correctly. See [example](http://en.cppreference.com/w/cpp/atomic/atomic/compare_exchange) from cppreference.com.
Comment: @programmerjake compare_exchange really can't take the first argument if it's an atomic. It's not a bug
Comment: Unless there's something you're not telling us, start by making next non-atomic.
Comment: @Cubbi Like in the first variant? And what is the next step?
Comment: @Maksim given that your first example appears to be lifted straight from Listing 7.3 of Concurrency in Action, debug
Answer: One problem with the test is the line sum.store(sum.load() + *val);
Use atomic ops, such as sum += *val;
Comment: Thank you, but still, how to implement this with `std::atomic` next?
Answer: The first variant is garbage, because you can't guarantee atomicity on stores to node::next pointer. It would possible to use memory fence/barrier with non-atomic next-pointers, but I wouldn't trust such implementation.
Your second variant is more close to correct implementation.
However you forgot the most important thing from the push() CAS-loop:
void push(const T& val) {
    node* new_node = new node(val);
    new_node->next = head.load();
    node* local_next = new_node->next.load();
    while (!head.compare_exchange_weak(local_next, new_node));
}

Here the code allocates new node, loads and stores head pointer to new_node->next. Next, code saves already known stack head pointer value to local_next. (unnecessary step) Then code tries update stack head to new_node without updating new_node->next. This would be fine you were on singe core machine running single thread without pre-emption and the CAS would succeed 100% of time. ;)
When the CAS fails, it loads current fresh value of head into local_next and the code is stuck in infinite loop, because new_node will never be equal to local_next. So you got the last part wrong.
To make a functional CAS-loop the failing thread must reload and recompute what ever data it was trying to update. This means you must update new_node->next from head before re-trying the CAS.
This does not solve the ABA problem of CAS-loops, but I leave it out from my answer. I suggest reading more about CAS-operation and its pitfalls.
Because CAS operation does a load operation the fix is very simple, just store local_next to new_node->next after failing CAS.
Here is more valid (untested) version:
node* new_node = new node(val);
node* local_head = head.load();
new_node->next.store(local_head);
while(!head.compare_exchange_weak(local_head, new_node) {
    new_node->next.store(local_head);
}

You'll to do similiar thing to your pop() implementation.


GoDaddy domain (randomly) not resolving to GitHub Pages

Question: I have added a CNAME file to the root level of my GitHub Pages repository, which contains my domain (_____.com).
My DNS settings on the GoDaddy website look like this: DNS Settings. On the "Manage My Domains" page, it says

________.com is just sitting there. Put it to work.

But I just assumed since I'm manually changing the DNS settings, that its fine.
I set this all up following GitHub's instructions on their website, and going to my domain correctly shows my GitHub Pages website - sometimes. At other (seemingly random) times, a GoDaddy page will pop up: GoDaddy Pop-up
When this first started happening, I chalked it up to the domain being newly registered, assuming that things would fix themselves in a few days. It's been over a week now though, and sometimes my website will show up, and sometimes the GoDaddy page will show up.
I'm not sure if this is related, but resetting my internet connection or clearing my web browser cache seems to fix it sometimes, but not all the time. I've asked friends to load my domain name, and on some days they are able to see the website, on other days they see the GoDaddy page.
Should I just give it a couple more weeks and see if things start working properly? Or is it an issue with GoDaddy/GitHub? I'm completely open to switching to a different domain name registrar or website host (or both) in order to get this to work.
Comment: What is the domain name?
Comment: @MichaelHampton Sorry for the late response - the domain name is kristinedomingo.com
Answer: You have three IP addresses registered for the apex of your domain:
<code>kristinedomingo.com has address 220.127.116.11
kristinedomingo.com has address 22.214.171.124
kristinedomingo.com has address 184.108.40.206
</code>
Two of these belong to GitHub, and one belongs to GoDaddy. Because DNS is round-robin, about 2/3 of the time you will go to the right place, and the rest of the time you end up at GoDaddy's parking page.
To fix the problem, remove the GoDaddy IP address.
Comment: This helped me quickly and easily diagnose this exact issue, thanks a lot.


Alterar posição dos cursores do Lightbox

Question: Estou utilizando um plugin para fazer o efeito de lightbox(Segue o link abaixo desse texto), e preciso fazer algumas mudanças no visual, como o visual dos cursores e seus posicionamentos. Eu mudei o close dele para o topo e mudei as cores das setas, agora
estou tentando deixá-los para fora da imagem.
LightBox: The original lightbox script
Consegui fazer isso com o cursor next, mas não com o prev. Eu tirei o float:left dos 2 cursores e no next eu coloquei uma margin-left e deu certo, já pro prev(cursor pra voltar)a margem não resolve nada, ela permanece no mesmo lugar.
Imagem de como estou vendo
HTML

CSS
.lb-nav {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  z-index: 10;
}

.lb-container > .nav {
  left: 0;
}

.lb-nav a {
  outline: none;
  background-image: url('data:image/gif;base64,R0lGODlhAQABAPAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==');
}

.lb-prev, .lb-next {
  height: 100%;
  cursor: pointer;
  display: block;
}

.lb-nav a.lb-prev {
  width: 34%;
  left: 0;
  /*float: left;*/
  background: url(../images/prev.png) left 48% no-repeat;
  filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
  opacity: 0.5;
  -webkit-transition: opacity 0.6s;
  -moz-transition: opacity 0.6s;
  -o-transition: opacity 0.6s;
  transition: opacity 0.6s;
  margin-right: 10px !important;
}

.lb-nav a.lb-next {
  width: 64%;
  right: 0;
  /*float: right;*/
  background: url(../images/next.png) right 48% no-repeat;
  filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
  opacity: 0.5;
  -webkit-transition: opacity 0.6s;
  -moz-transition: opacity 0.6s;
  -o-transition: opacity 0.6s;
  transition: opacity 0.6s;
  margin-left: 44% !important;
}

Answer: Resolução
Finalmente eu consegui a resposta !. Eu tirei a parte de margin que tinha feito e mudei a parte de right e left.
Código
Colocarei aqui só o que eu adicionei.
.lb-prev, .lb-next {
    width: 50%;
    position:absolute;
    top: 0;
}

.lb-prev{
    left:-60px;
}

.lb-next {
    right:-60px;
}

Comment: Resposta alterada. Obrigado pelo "toque" @Andrey.
Comment: Esta é a solução para o problema? Se sim, edite sua resposta e deixe isso claro para quem pesquisar por isso futuramente. Se não, edite sua própria pergunta para adicionar informações.
Comment: Allan, considere marcar sua resposta como correta, clicando à esquerda, abaixo da pontuação.


Finding the general formula for the powers of a matrix

Question:
Let $A=\begin{bmatrix}0&1\\1&0\end{bmatrix}$. Find the formula for $A^n$ and prove it.

The way I tried to solve it is like this:
If we find $A^2$, $A^3$ and so on you will notice this patern: If $n$ is odd $A^n=\begin{bmatrix}0&1\\1&0\end{bmatrix}$. If $n$ is even then $A^n=I$.
To prove this I used mathematical induction.
We see that the base case is $A^1$ and $A^2$.
Now we suppose the statement holds for a natural number $n$. If $n+1$ is odd then this means that n is even and we see that the matrix $A^{n+1}=A^nA=\begin{bmatrix}0&1\\1&0\end{bmatrix}$, so the statement holds in this case. If $n+1$ is even then this means that $n$ is odd and we see that the matrix $A^{n+1}=A^nA=I$, so the statement holds in this case also. As a consequence the statement holds for all natural numbers.
I want to know if this proof is right or not? Can someone help me?
Comment: Yes, you are perfectly fine.
Comment: Easy by induction that $A^{2n}=I$ and $A^{2n+1}=A$
Answer: This looks absolutely correct. Another way to view it is that matrix multiplication corresponds to function composition. In particular, this is the map $T:\mathbb R^2 \to \mathbb R^2$ given by $(x,y) \mapsto (y,x)$, which is a reflection about the line $y=x$, so $T \circ T=Id$, which in turn implies that  $T \circ \dots\circ T=T^{2n+1}=T \circ T^{2n}=T$, and  $T^{2n}=Id$
Answer: Yes.
Another approach is by diagonalising the (symmetric) matrix $A$
$$
A = V D V^T
$$
where $D$ is the diagonal matrix of eigenvalues $(\pm1)$ and $V$ is the matrix formed from eigenvectors of $A$
Then
$$
A^n = V D^n V^T
$$
so it depends on $$D^n=\left( \begin{array}{cc}1 &0 \\
0& -1
\end{array} \right)^n$$
A key thing is that to compute a diagonal matrix to a power you raise the diagonal elements to that power.

If n is even then $D^n=I$, so $A^n=V I V^T = I $ due to orthogonality of $V$.
If n is odd then $D^n=D$, so $A^n=V D V^T = A $


Como saber se é click do mouse ou do Robot?

Question: Queria saber se tem como diferenciar o click do java.awt.Robot do click do mouse...
Preciso saber se foi o Robot que clicou ou se foi o mouse.
Comment: a que nivel você está falando, um bot que controla o mouse, ou um programa que manda requests automaticamente ?, pode descrever onde você quer usar isso e com qual finalidade ?
Comment: A sua pergunta tinha originalmente "Java" no título e "javascript" na tag. Como você está falando de Robot, que não tem sentido em javascript, eu editei a sua pergunta e arrumei a tag para evitar de confundir os demais usuários.
Comment: Talvez teria que partir de alguns princípios que somente um usuário faria, um robot apenas pega o elemento DOM por código e clica nele, já um usuário passa o mouse por cima (hover, move) e dá o click, uma validação de eventos combinados.
Comment: Qual o motivo dessa verificação? Talvez exista alguma alternativa melhor.
Comment: Quero que quando o robot clique faça uma ação diferente de quando é click do mouse
Answer: Não tenho plena certeza disso, mas a classe java.awt.Robot deve inserir eventos de clique na fila do sistema operacional. Tanto que você pode utilizá-lo para clicar em outros programas, arrastar-e-soltar na área de trabalho ou qualquer coisa assim. Com isso, a única forma de poder diferenciar isso seria se você fuçasse nas entranhas do sistema operacional, e portanto não espere que o código seja portável.
Mas não dá para tentar mesmo assim usando apenas código java? Bem, eu tentei e cheguei a conclusão que não dá, pelo menos não com 100% de certeza. Eis o código do que tentei:
import java.awt.AWTException;
import java.awt.EventQueue;
import java.awt.MouseInfo;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
 * @author Victor
 */
public class DetectRobot {
    public static void main(String[] args) {
        EventQueue.invokeLater(DetectRobot::go);
    }

    private static void go() {
        try {
            Mouser m = new Mouser();
            Robot r = new Robot();
            JFrame jf = new JFrame("Teste");
            JButton jb = new JButton("Clique aqui");
            jb.addActionListener(DetectRobot::clicked);
            jb.addMouseListener(m);
            jb.addMouseWheelListener(m);
            jb.addMouseMotionListener(m);
            jf.add(jb);
            jf.setBounds(10, 10, 250, 250);
            jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            jf.setVisible(true);
            Thread t = new Thread(() -> clicker(jf, r));
            t.start();
        } catch (AWTException e) {
            throw new RuntimeException(e);
        }
    }

    private static void clicker(JFrame jf, Robot r) {
        Thread t = Thread.currentThread();
        try {
            while (!Thread.interrupted()) {
                Thread.sleep(5000);
                System.out.println("Robo clicando");
                EventQueue.invokeAndWait(() -> {
                    if (jf.isDisplayable()) {
                        r.mouseMove(150, 150);
                        r.mousePress(InputEvent.BUTTON1_DOWN_MASK);
                    } else {
                        t.interrupt();
                    }
                });
                Thread.sleep(50);
                EventQueue.invokeAndWait(() -> {
                    r.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
                    if (!jf.isDisplayable()) t.interrupt();
                });
                Thread.sleep(50);
                System.out.println("Robo terminou");
            }
        } catch (InterruptedException e) {
            // Ignora e deixa a Thread morrer naturalmente.
        } catch (InvocationTargetException ex) {
            ex.printStackTrace();
        }
    }

    private static void clicked(ActionEvent e) {
        log(e);
    }

    // Para simplificar a saída do log. Não precisamos mostrar no System.out qual foi o JButton clicado, apenas os eventos.
    private static void log(Object x) {
        String a = x.toString();
        int i = a.indexOf(" on javax.swing.JButton[");
        System.out.println(a.substring(0, i));
    }

    private static class Mouser implements MouseListener, MouseMotionListener, MouseWheelListener {

        @Override
        public void mouseClicked(MouseEvent e) {
            log(e);
        }

        @Override
        public void mousePressed(MouseEvent e) {
            log(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            log(e);
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            log(e);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            log(e);
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            log(e);
        }

        @Override
        public void mouseMoved(MouseEvent e) {
            log(e);
        }

        @Override
        public void mouseWheelMoved(MouseWheelEvent e) {
            log(e);
        }
    }
}

Eis o resultado:
Robo clicando
java.awt.event.MouseEvent[MOUSE_ENTERED,(132,109),absolute(150,150),button=0,clickCount=0]
java.awt.event.MouseEvent[MOUSE_MOVED,(132,109),absolute(150,150),clickCount=0]
java.awt.event.MouseEvent[MOUSE_PRESSED,(132,109),absolute(150,150),button=1,modifiers=Button1,extModifiers=Button1,clickCount=1]
java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=Clique aqui,when=1424373236982,modifiers=Button1]
java.awt.event.MouseEvent[MOUSE_RELEASED,(132,109),absolute(150,150),button=1,modifiers=Button1,clickCount=1]
java.awt.event.MouseEvent[MOUSE_CLICKED,(132,109),absolute(150,150),button=1,modifiers=Button1,clickCount=1]
Robo terminou
Robo clicando
java.awt.event.MouseEvent[MOUSE_PRESSED,(132,109),absolute(150,150),button=1,modifiers=Button1,extModifiers=Button1,clickCount=1]
java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=Clique aqui,when=1424373242084,modifiers=Button1]
java.awt.event.MouseEvent[MOUSE_RELEASED,(132,109),absolute(150,150),button=1,modifiers=Button1,clickCount=1]
java.awt.event.MouseEvent[MOUSE_CLICKED,(132,109),absolute(150,150),button=1,modifiers=Button1,clickCount=1]
Robo terminou
Robo clicando
java.awt.event.MouseEvent[MOUSE_PRESSED,(132,109),absolute(150,150),button=1,modifiers=Button1,extModifiers=Button1,clickCount=1]
java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=Clique aqui,when=1424373247185,modifiers=Button1]
java.awt.event.MouseEvent[MOUSE_RELEASED,(132,109),absolute(150,150),button=1,modifiers=Button1,clickCount=1]
java.awt.event.MouseEvent[MOUSE_CLICKED,(132,109),absolute(150,150),button=1,modifiers=Button1,clickCount=1]
Robo terminou
java.awt.event.MouseEvent[MOUSE_MOVED,(132,108),absolute(150,149),clickCount=0]

... Mais um monte de eventos MOUSE_MOVED disparados praticamente ao mesmo tempo, a medida que eu ia movendo o mouse ...

java.awt.event.MouseEvent[MOUSE_MOVED,(192,21),absolute(210,62),clickCount=0]
java.awt.event.MouseEvent[MOUSE_PRESSED,(192,21),absolute(210,62),button=1,modifiers=Button1,extModifiers=Button1,clickCount=1]
java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=Clique aqui,when=1424373250075,modifiers=Button1]
java.awt.event.MouseEvent[MOUSE_RELEASED,(192,21),absolute(210,62),button=1,modifiers=Button1,clickCount=1]
java.awt.event.MouseEvent[MOUSE_CLICKED,(192,21),absolute(210,62),button=1,modifiers=Button1,clickCount=1]
java.awt.event.MouseEvent[MOUSE_MOVED,(191,25),absolute(209,66),clickCount=0]

... Mais um monte de eventos MOUSE_MOVED disparados praticamente ao mesmo tempo, a medida que eu ia movendo o mouse ...

java.awt.event.MouseEvent[MOUSE_MOVED,(159,67),absolute(177,108),clickCount=0]
java.awt.event.MouseEvent[MOUSE_PRESSED,(159,67),absolute(177,108),button=1,modifiers=Button1,extModifiers=Button1,clickCount=1]
java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=Clique aqui,when=1424373250629,modifiers=Button1]
java.awt.event.MouseEvent[MOUSE_RELEASED,(159,67),absolute(177,108),button=1,modifiers=Button1,clickCount=1]
java.awt.event.MouseEvent[MOUSE_CLICKED,(159,67),absolute(177,108),button=1,modifiers=Button1,clickCount=1]
java.awt.event.MouseEvent[MOUSE_PRESSED,(159,67),absolute(177,108),button=1,modifiers=Button1,extModifiers=Button1,clickCount=2]
java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=Clique aqui,when=1424373251059,modifiers=Button1]
java.awt.event.MouseEvent[MOUSE_RELEASED,(159,67),absolute(177,108),button=1,modifiers=Button1,clickCount=2]
java.awt.event.MouseEvent[MOUSE_CLICKED,(159,67),absolute(177,108),button=1,modifiers=Button1,clickCount=2]
java.awt.event.MouseEvent[MOUSE_PRESSED,(159,67),absolute(177,108),button=1,modifiers=Button1,extModifiers=Button1,clickCount=3]
java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=Clique aqui,when=1424373251309,modifiers=Button1]
java.awt.event.MouseEvent[MOUSE_RELEASED,(159,67),absolute(177,108),button=1,modifiers=Button1,clickCount=3]
java.awt.event.MouseEvent[MOUSE_CLICKED,(159,67),absolute(177,108),button=1,modifiers=Button1,clickCount=3]
java.awt.event.MouseEvent[MOUSE_MOVED,(160,66),absolute(178,107),clickCount=0]

... Mais um monte de eventos MOUSE_MOVED disparados praticamente ao mesmo tempo, a medida que eu ia movendo o mouse ...

java.awt.event.MouseEvent[MOUSE_MOVED,(228,0),absolute(246,41),clickCount=0]
java.awt.event.MouseEvent[MOUSE_EXITED,(230,-1),absolute(248,40),button=0,clickCount=0]
Robo clicando
java.awt.event.MouseEvent[MOUSE_ENTERED,(132,109),absolute(150,150),button=0,modifiers=Button1,extModifiers=Button1,clickCount=0]
java.awt.event.MouseEvent[MOUSE_MOVED,(132,109),absolute(150,150),clickCount=0]
java.awt.event.MouseEvent[MOUSE_RELEASED,(132,109),absolute(150,150),button=1,modifiers=Button1,clickCount=3]
Robo terminou
java.awt.event.MouseEvent[MOUSE_MOVED,(131,109),absolute(149,150),clickCount=0]

... Mais um monte de eventos MOUSE_MOVED disparados praticamente ao mesmo tempo, a medida que eu ia movendo o mouse ...

java.awt.event.MouseEvent[MOUSE_MOVED,(198,1),absolute(216,42),clickCount=0]
java.awt.event.MouseEvent[MOUSE_EXITED,(199,-1),absolute(217,40),button=0,clickCount=0]

Observe que não há forma simples de distinguir os eventos do Robot dos eventos do usuário. O melhor que acho que dá para fazer é verificar se o mouse está "pulando" e não "andando". Para fazer isso, você pode rastrear a posição do mouse usando java.awt.MouseInfo.getPointerInfo().getLocation(), que fornece a posição do mouse no dispositivo gráfico aonde ele está e java.awt.MouseInfo.getPointerInfo().getDevice() para dizer qual é o dispositivo gráfico aonde ele está (importante se houver mais do que um monitor). Com isso, não é difícil detectar se o mouse está "pulando" e não "andando" e se ele clicar logo após o pulo, provavelmente foi um Robot. Mas obviamente isso não resolve diretamente o problema, pois pode ser contornado por um Robot que faça o mouse andar e não pular e não resolve o caso do mouse ser clicado sem que seja movido.
Também é possível buscar outros padrões de comportamento típicos de robôs, como sempre clicar na exata mesma posição, sempre mover o mouse com um mesmo padrão, sempre ter um mesmo intervalo ou duração de cliques ou qualquer coisa assim. Mas apenas usando o java, sem entrar dentro das entranhas do sistema operacional, não acho que o que você queira é possível com 100% de garantia.
O principal problema aqui é que a intenção do Robot é exatamente a de se passar pelo usuário usando o computador. Ou seja, uma das finalidades dele é exatamente a de ser indistinguível a de um usuário operando o sistema, mas o que você precisa é exatamente distinguí-los!
Entretanto, se você tiver acesso ao código do Robot (ou para ser mais preciso, da classe que controla o Robot), então o problema se torna fácil. Observe aqueles System.out.println("Robo clicando"); e System.out.println("Robo terminou");, se o seu controlador do Robot avisar de alguma forma a sua aplicação que ele vai dar um clique, então a sua aplicação saberá que o clique que logo se seguir veio do Robot e não do usuário.
Comment: A nivel kernel, sei que você pode saber o pid tid do processo que está utilizando uma operação de entrada ou saída em um determinado momento, então não seria possível pesquisar quem estava controlando esse dispositivo nesse intervalo ?
Comment: @IsvaldoFernandes Não sei, mas se você puder elaborar uma resposta em cima disso, siga em frente, eu adoraria saber isso. Talvez dê para "sentir o cheiro de um robô" se você detectar que algum processo inesperado mexeu com o mouse no nível do sistema operacional. :)
Comment: Obrigado por comentar, deve ter dado trabalho para fazer este comentario... mas quero que quando o robot clique faça uma ação diferente de quando é click do mouse
Comment: @paulobr Acrescentei dois parágrafos no final da minha resposta.
Comment: Já consegui arrumar, só mudei as preferencias, acho que consegui, a classe robot editada ta funcionando, agora tenho que fazer o sistema pra detectar...


Get full compilation command in CMake

Question: If you execute vim --version, it will show some information about how it was compiled. On my system, it looks like this:

Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H -DFEAT_GUI_GTK  -pthread -I/usr/include/gtk-2.0 -I/usr/lib/gtk-2.0/include -I/usr/include/pango-1.0 -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/pixman-1 -I/usr/include/libdrm -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/libpng16 -I/usr/include/pango-1.0 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/harfbuzz -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/harfbuzz  -D_FORTIFY_SOURCE=2  -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector-strong --param=ssp-buffer-size=4 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
Linking: gcc   -L. -Wl,-O1,--sort-common,--as-needed,-z,relro -fstack-protector -rdynamic -Wl,-export-dynamic -Wl,-E -Wl,-rpath,/usr/lib/perl5/core_perl/CORE  -Wl,-O1,--sort-common,--as-needed,-z,relro -L/usr/local/lib -Wl,--as-needed -o vim   -lgtk-x11-2.0 -lgdk-x11-2.0 -lpangocairo-1.0 -latk-1.0 -lcairo -lgdk_pixbuf-2.0 -lgio-2.0 -lpangoft2-1.0 -lpango-1.0 -lgobject-2.0 -lglib-2.0 -lfontconfig -lfreetype  -lSM -lICE -lXt -lX11 -lXdmcp -lSM -lICE  -lm -lncurses -lelf -lnsl   -lacl -lattr -lgpm -ldl  -L/usr/lib -llua -Wl,-E -Wl,-rpath,/usr/lib/perl5/core_perl/CORE -Wl,-O1,--sort-common,--as-needed,-z,relro -fstack-protector -L/usr/local/lib  -L/usr/lib/perl5/core_perl/CORE -lperl -lnsl -ldl -lm -lcrypt -lutil -lpthread -lc -L/usr/lib/python2.7/config -lpython2.7 -lpthread -ldl -lutil -lm -Xlinker -export-dynamic   -lruby -lpthread -lgmp -ldl -lcrypt -lm  -L/usr/lib
  ```

I want to add similar information to the version output of an application that is built using CMake.
I know that there are variables like CMAKE_C_FLAGS, but it depends on other variables if these are actually used. For example, CMAKE_C_FLAGS_RELEASE is used if CMAKE_BUILD_TYPE=Release is specified. Thus it might be error-prone to try to piece this information together from individual CMake variables, and in the end you can't be sure that this is really what CMake uses to compile your sources.
Is there a way to get the actual command CMake uses to compile a source file, similar to the output from vim --version above?
Answer: moreover, CMAKE_C_FLAGS could vary for different source files, directories and targets… so your output can be far from accurate…
and using variables like CMAKE_BUILD_TYPE is pretty stable actually and may give you what you want:
string(TOUPPER "${CMAKE_BUILD_TYPE}" _type_upcase)
# Yeah! CMake can do double expand!
set(_cflags "${CMAKE_C_FLAGS_${_type_upcase}}")

little problem is: make sure CMAKE_BUILD_TYPE is set and valid before get the value!
advanced way:
one may use CMAKE_<lang>_COMPILE_OBJECT variable to get a "compile template". then use directory properties to collect COMPILE_DEFINITIONS and replace a pattern <DEFINES> in the template. then collect INCLUDE_DIRECTORIES and other options depending on build type.
You may look here for inspiration.

Get full compilation command in CMake


iptables: only allow UDP packets that contain a specific string

Question: How do I configure iptables so that only UDP packets that contain a specific string are allowed as an INPUT?
For example, I would like only UDP packets that contain the string version to be allowed.
Comment: normally, you go read `man iptables` then you say "whoa!" and do the things
Answer: You can use a iptables extension for doing this.
Here is a link where you can read about string matching with iptables
from the web
You can of course doing what you expect with this technique.
Good reading !


Nature of equation of line $sz+t\bar z+r=0$, s,t and r are complex numbers

Question: Let $s,t,r$ be non-zero complex numbers and $L$ be the set of solutions $\{(x,y) \in \mathbb R \}$ and $i=\sqrt{-1}$ of the equation :
$$sz+t\bar z+r=0$$
where $\bar z=x-iy$ prove that it has exactly one element then  $|s|\ne |t|$.
I have prove it using
$s=a+ib$, $t=c+id$ and $r=e+if$
Using the equation $sz+t\bar z+r=0$, we get two line equation
(a+c)x+(d-b)y+e=0
(b+d)x+(a-c)y+f=0
For unique solution we have $a^2+b^2 \ne c^2+d^2$ viz.$|s|\ne |t|$(neglecting the negative value)
Can I prove it without using the substituion as outlined above
Answer: Write the equation as
\begin{cases}
sz+t\bar{z}=-r \\[4px]
\bar{t}z+\bar{s}\bar{z}=-\bar{r}
\end{cases}
Considering $z$ and $\bar{z}$ as independent variables, we know that the system has a unique solution if and only if
$$
\det\begin{bmatrix} s & t \\ \bar{t} & \bar{s} \end{bmatrix}=|s|^2-|t|^2\ne0
$$


How do you do your FTP on a web server?

Question: I was just wondering how you do your FTP on your webserver. I've always created a folder in /var/nameofwebsite.com and added a system user with their home directory there.
To me, this looks a bit hackish as files such as .bash_logout are in there and sometimes, the folder permissions don't even work correctly as I set the owner of the folder to <nameofwebsite><tld> and their group to ftp which all accounts intended for FTP are in.
Is what I am doing secure and right? I'm setting up a fresh new web server to host my sites on and wanted to know if this setup would last me long.
Answer: Not a solution to your question, but a suggestion to change your approach. No matter how you setup your server and users, FTP is never secure. FTP transmits your userid and password in plain text. Use secure FTP (SFTP) instead.
Comment: It's also messy to manage the network connections.
Comment: You can use FTP with SSL (FTPS) to avoid transmission of plain text passwords. But yah, depending upon how your network is setup it can be messy. Still, there is a surprisingly big chunk of the corporate world that uses FTP.
Answer: As Vasu says, stop using FTP. There are lots of simple web based file managers you can run on top of HTTPS, but SCP is much preferable.
Leaving the transport aside for the moment, the main thrust of your question is all about network paths and permissions. We'd need to know an awful lot more information about the security model and constraints before any sensible discussion of permissions. At a guess, you might consider setting up a group for each vhost and making that the users default group (and setting umask accordingly). You should definitely consider making the vhost document root something other than the users home directory - a subdirectory is one way to do that.

How do you do your FTP on a web server?


Infinite product of limit elements.

Question: Suppose I have an array of strictly positive elements $\{a_{k}^{m}\}_{k,m\in\mathbb{N}}$ such that

$$ a_k:= \lim_{m\rightarrow\infty}a_{k}^{m}  > 0 $$
$$\lim_{m\rightarrow\infty}\prod_{k=1}^{m}a_{k}^{m} = 0 $$

Is convergence of $a_{k}^{m} \rightarrow a_k$ uniform over $k$ enough to ensure that
$$
\lim_{m\rightarrow\infty}\prod_{k=1}^{m}a_{k} = 0 .
$$
Comment: A sufficient condition would be uniform convergence of $P_{mn} = \prod_{k=1}^na_k^m$ as $n \to \infty$ for all $m \in \mathbb{N}.$  It seems you have moved on here.  Let me know if you want to see how this might work.
Comment: Thank you for the intuition. I think I see how this would work. This gives me hope again!
Answer: Uniform convergence of $a_k^m \to a_k$ is not sufficient. Consider
$$a_k^m = 1 - \frac{1}{\sqrt[3]{k+1}\sqrt{m+1}}.$$
Then $a_k^m \to 1$ uniformly, but
$$\sum_{k = 1}^m \log a_k^m < -\sum_{k = 1}^m \frac{1}{\sqrt[3]{k+1}\sqrt{m+1}} \sim -\frac{3}{2} \cdot \frac{(m+1)^{2/3}}{\sqrt{m+1}} = -\frac{3}{2}(m+1)^{1/6} \to -\infty,$$
so
$$\lim_{m\to\infty} \prod_{k = 1}^m a_k^m = 0.$$
Comment: Thanks a lot for the response! Do you have any intuition about another sufficient condition that might ensure the result?
Comment: There's the rather trivial sufficient condition that $a_k^m \downarrow a_k$. I guess you're not in a situation where that applies. I don't know a nontrivial sufficient condition off the top of my head. Let me think about it for a moment.
Comment: I'm starting to realise that this problem is much harder than I anticipated beforehand. Thank you for your time invested.

Infinite product of limit elements.


PostgreSQL: sequential table scan on Hstore column despite having a GiN index

Question: I have a table with a hstore column and roughly 22 mio records (the ways table from a partial osm-database).
Despite having a GIN index on the hstore column, queries for a specific tag result in a sequential table scan that takes > 60 sec to return a single column.
What i have been doing so far.

I created the GIN index using pgAdminIII.
Executing vacuum analayze
Executing a query of the kind: select id from table where tags->'name'='foo'
Deleting index and starting from 1. again ...
[Edit] As suggested by the user a_horse_with_no_name I updated the table statistics by executing analyze on the table. But that had no effect.

You can see the query plan here. For some reason the explain analyze takes only ~20 sec to complete.
How can I properly index a hstore column on a large table like this, to reduce query execution cost significantly?
Thank you for your help!
Comment: I executed analyze ways, but there are still no improvements in query execution speed
Answer: I see two possible solutions:
If you always query that key value for equality you can use an a B-Tree index on the expression (`tags -> 'name')
create index idx_name on ways ( (tags -> 'name') );

A quick test has shown that Postgres does use the index to find if a key value is present in the hstore column, but apparently not for finding the associated value.
So you could try to add a condition to test for that key value as well:
select id
from ways
where tags ? 'name'
  and tags -> 'name' = 'Wiehbergpark';

If all rows contain that key, it might not help though.
Comment: As i already tried the second one before, i created the btree index on the 'name' tag.
Comment: That finally reduced query cost to 10 ms! Great! Thank you.
Comment: @achingfingers: which of the two alternatives did you use?


Scaling the probability mass function

Question: I have produced a histogram of the frequency of observing some variable, call it $x$. I have then used the following equation:
$$f(x;\mu,\sigma)=\frac{1}{\sqrt{2\pi \sigma^2}}e^{-\frac{(x-\mu)^2}{2\sigma^2}}$$
To estimate the value of the pmf at every observation point, which I then too plotted. This results in two 'bell curves'. However, I need to rescale my pmf so that it 'matches' the frequency plot. How does one actually find that scaling constant?
I have in my notes, that one should use:
$$f(x;\mu,\sigma)=\frac{c}{\sqrt{2\pi \sigma^2}}e^{-\frac{(x-\mu)^2}{2\sigma^2}}$$
But how $c$ is found is never mentioned.
I had an idea of simply turning the frequency histogram into the probability one, so that I have for each observation frequency/total frequency and then rescaling the pmf so that the area under the curve is $1$. Not quire sure what to do next. And I do not think this would be the right way as I would then need to rescale back the pmf so that it matches that original frequency plot.
EDIT:
I got it. That idea was actually useful. That constant is such that the area under the two curves is equivalent.
Answer: The function you gave is actually a PDF of Gaussian distribution:
$$f(x;\mu,\sigma)=\frac{1}{\sqrt{2\pi \sigma^2}}e^{-\frac{(x-\mu)^2}{2\sigma^2}}$$
PMF is for discrete observations. In order to scale you have to integrate PDF within bounds of your bins. For instance you have the following bins: $(-\infty,-10],(-10,10],(10,\infty)$, then you have three PMF values, i.e. one for each bin like follows:
$$PMF_1=\int_{-\infty}^{-10}f(x;\mu,\sigma)dx$$ and so on for other two bins.
That's for theoretical PMF. If you're looking for observed probabilities then you must divide the observed frequencies by total number of observations. For instance, you got the following number of observations in the bins: 20, 65, 15. You observed probabilities would be: 0.2, 0.65 and 0.15.
Now you can compare them with theoretical (when $\mu,\sigma$ are somehow known in advance) or fitted (where $\hat\mu,\hat\sigma$ are estimated from data) PMF that you calculated the way I showed first.

Scaling the probability mass function


jQuery change image position

Question: I'm new to jQuery and I need your help.
I want to build a table has 2 columns labeled X and Y, an input field in each column and a change button, when user click the button it jQuery function would check if the fields are empty, if they are the function would put the default values in the offset({left: x, top:y}) which is defined in jquery header, if the fields are not empty it would take the values from the fields and change the position of the image.
So the position of the image would change each time the user change the values of the fields.
Thanx in advance,
Answer: Here's a JS fiddle with a working version: http://jsfiddle.net/UKRD8/14/
Just make sure you put in the 'px' after you enter the number for the inputs.
Answer:

            X:

                <input id="txtX" type="text" />

            Y:

                <input id="txtY" type="text" />

                <input id="btnUpdate" type="button" value="Update" onclick="updateCords()" />

Comment: thank you but I want three rows, each row would change an image position and just one button, thank you for your help

jQuery change image position