text:
Q: Get specific series values in order I have a table contains the info of the access time and movements for each employee.
Some employees have shift work hours between two days, I have column determine if this access time belongs to the previous or current day.
I need to collect the access time which belongs to one day, then get the difference between the current access time and the next one and determine the check status of the movement(first or last or during the day movement).
I get the mentioned result if the employee has shift work hours on the same day but I can't get the true result if he has work hours between two days.
Example:
Employee Number 1 has Shift method: 17:00 -> 01:00
Employee Number 2 has Shift method: 08:30 -> 16:30
Total Work Hours: 08:00
   CREATE TABLE My_Table (
  EMP_ID    NUMBER(4) ,
  Timeinout date ,
  flag number(1)

);

INSERT INTO My_Table VALUES (1,to_date('03-07-2018 16:39:44','dd-mm-yyyy hh24:mi:ss'),0);
INSERT INTO My_Table VALUES (1,to_date('04-07-2018 01:14:40','dd-mm-yyyy hh24:mi:ss'),1);
INSERT INTO My_Table VALUES (1,to_date('04-07-2018 01:14:44 ','dd-mm-yyyy hh24:mi:ss'),1);
INSERT INTO My_Table VALUES (1,to_date('04-07-2018 16:14:52','dd-mm-yyyy hh24:mi:ss'),0);
INSERT INTO My_Table VALUES (1,to_date('05-07-2018 01:07:40','dd-mm-yyyy hh24:mi:ss'),1);
INSERT INTO My_Table VALUES (1,to_date('05-07-2018 01:07:44 ','dd-mm-yyyy hh24:mi:ss'),1);
INSERT INTO My_Table VALUES (1,to_date('05-07-2018 16:31:08','dd-mm-yyyy hh24:mi:ss'),0);
INSERT INTO My_Table VALUES (1,to_date('06-07-2018 01:01:48 ','dd-mm-yyyy hh24:mi:ss'),1);
INSERT INTO My_Table VALUES (1,to_date('06-07-2018 01:01:52','dd-mm-yyyy hh24:mi:ss'),1);
INSERT INTO My_Table VALUES (2,to_date('03-07-2018 08:37:40','dd-mm-yyyy hh24:mi:ss'),0);
INSERT INTO My_Table VALUES (2,to_date('03-07-2018 16:27:36','dd-mm-yyyy hh24:mi:ss'),0);
INSERT INTO My_Table VALUES (2,to_date('04-07-2018 08:37:04 ','dd-mm-yyyy hh24:mi:ss'),0);
INSERT INTO My_Table VALUES (2,to_date('04-07-2018 12:58:36','dd-mm-yyyy hh24:mi:ss'),0);
INSERT INTO My_Table VALUES (2,to_date('04-07-2018 13:09:48 ','dd-mm-yyyy hh24:mi:ss'),0);
INSERT INTO My_Table VALUES (2,to_date('04-07-2018 17:15:32 ','dd-mm-yyyy hh24:mi:ss'),0);

COMMIT;

The query I used is for employee number2 return the true result:
   select X.*,
       CASE
         WHEN Previous_Movment IS NULL AND Next_Movment IS NOT NULL THEN
          'First Check'
         WHEN Previous_Movment IS NOT NULL AND Next_Movment IS NULL THEN
          'Last Check'
         when Previous_Movment IS NULL AND Next_Movment IS NULL THEN
          'Do Not have access in this day'
         ELSE
          'During the Day'
       end CHECK_sTATUS
  from (select trunc(a.timeinout) as date_,
               a.timeinout current_movment,
               LEAD(TIMEINOUT) OVER(partition by trunc(TIMEINOUT), Emp_ID ORDER BY TIMEINOUT, Emp_ID) Next_Movment,
               LAG(TIMEINOUT) OVER(partition by trunc(TIMEINOUT), Emp_ID ORDER BY TIMEINOUT, Emp_ID) Previous_Movment,
               trunc(24 *
                     mod(LEAD(TIMEINOUT) OVER(partition by trunc(TIMEINOUT),
                              Emp_ID ORDER BY TIMEINOUT,
                              Emp_ID) - TIMEINOUT,
                         1)) as diff_hours,
               trunc(mod(mod(LEAD(TIMEINOUT)
                             OVER(partition by trunc(TIMEINOUT),
                                  Emp_ID ORDER BY TIMEINOUT,
                                  Emp_ID) - TIMEINOUT,
                             1) * 24,
                         1) * 60) as diff_minus,
               trunc(mod(mod(mod(LEAD(TIMEINOUT)
                                 OVER(partition by trunc(TIMEINOUT),
                                      Emp_ID ORDER BY TIMEINOUT,
                                      Emp_ID) - TIMEINOUT,
                                 1) * 24,
                             1) * 60,
                         1) * 60) as diff_sec,
               Emp_ID,
               FLAG Return_Previous_day_or_not
          from My_table a
         WHERE trunc(a.timeinout) between
               to_Date('03-07-2018', 'dd-mm-yyyy') and
               to_Date('07-07-2018', 'dd-mm-yyyy')
          and a.Emp_ID = 2

        ) X

and the get the below result for employee number2:

But when I switch the query to employee number1 I get the wrong result because the movements between two days:

Note:
I used Trunc(Timeinout) in the LEAD & lAG function for the employee who has work hours on the same day.

A: From Oracle 12, you can use MATCH_RECOGNIZE for this.
Assuming that you want a shift to last for no more than 12 hours (yours appear to be 8 hours and people check in early and leave later) then:
SELECT emp_id,
       timeinout AS current_movement,
       flag,
       CASE
       WHEN cls IN ('FIRST_CHECK', 'DURING_DAY')
       THEN next_timeinout
       END AS next_movement,
       CASE
       WHEN cls IN ('DURING_DAY', 'LAST_CHECK')
       THEN prev_timeinout
       END AS previous_movement,
       CASE
       WHEN cls IN ('FIRST_CHECK', 'DURING_DAY')
       THEN (next_timeinout - timeinout) DAY TO SECOND
       END AS diff,
       cls AS check_status
FROM   my_table
MATCH_RECOGNIZE(
  PARTITION BY emp_id
  ORDER BY timeinout
  MEASURES
    PREV(timeinout) AS prev_timeinout,
    NEXT(timeinout) AS next_timeinout,
    LAST(last_check.timeinout) AS last_timeinout,
    CLASSIFIER() AS cls
  ALL ROWS PER MATCH
  PATTERN (first_check (during_day* last_check)?)
  DEFINE
    during_day AS timeinout < first_check.timeinout + INTERVAL '12' HOUR,
    last_check AS timeinout < first_check.timeinout + INTERVAL '12' HOUR
) m

Which, for your sample data, outputs:

EMP_ID
CURRENT_MOVEMENT
FLAG
NEXT_MOVEMENT
PREVIOUS_MOVEMENT
DIFF
CHECK_STATUS

1
2018-07-03T16:39:44
0
2018-07-04T01:14:40

+00 08:34:56.000000
FIRST_CHECK

1
2018-07-04T01:14:40
1
2018-07-04T01:14:44
2018-07-03T16:39:44
+00 00:00:04.000000
DURING_DAY

1
2018-07-04T01:14:44
1

2018-07-04T01:14:40

LAST_CHECK

1
2018-07-04T16:14:52
0
2018-07-05T01:07:40

+00 08:52:48.000000
FIRST_CHECK

1
2018-07-05T01:07:40
1
2018-07-05T01:07:44
2018-07-04T16:14:52
+00 00:00:04.000000
DURING_DAY

1
2018-07-05T01:07:44
1

2018-07-05T01:07:40

LAST_CHECK

1
2018-07-05T16:31:08
0
2018-07-06T01:01:48

+00 08:30:40.000000
FIRST_CHECK

1
2018-07-06T01:01:48
1
2018-07-06T01:01:52
2018-07-05T16:31:08
+00 00:00:04.000000
DURING_DAY

1
2018-07-06T01:01:52
1

2018-07-06T01:01:48

LAST_CHECK

2
2018-07-03T08:37:40
0
2018-07-03T16:27:36

+00 07:49:56.000000
FIRST_CHECK

2
2018-07-03T16:27:36
0

2018-07-03T08:37:40

LAST_CHECK

2
2018-07-04T08:37:04
0
2018-07-04T12:58:36

+00 04:21:32.000000
FIRST_CHECK

2
2018-07-04T12:58:36
0
2018-07-04T13:09:48
2018-07-04T08:37:04
+00 00:11:12.000000
DURING_DAY

2
2018-07-04T13:09:48
0
2018-07-04T17:15:32
2018-07-04T12:58:36
+00 04:05:44.000000
DURING_DAY

2
2018-07-04T17:15:32
0

2018-07-04T13:09:48

LAST_CHECK

db<>fiddle here

A: From Oracle 11gR2, you can use a recursive sub-query:
WITH ordered_data AS (
  SELECT m.*,
         ROW_NUMBER() OVER (PARTITION BY emp_id ORDER BY timeinout) AS rn,
         LAG(timeinout) OVER (PARTITION BY emp_id ORDER BY timeinout)
           AS previous_movement,
         LEAD(timeinout) OVER (PARTITION BY emp_id ORDER BY timeinout)
           AS next_movement
  FROM   my_table m
),
grouped_data (
  emp_id,
  current_movement,
  flag,
  rn,
  previous_movement,
  next_movement,
  grp,
  check_status,
  first_movement
) AS (
  SELECT emp_id,
         timeinout,
         flag,
         rn,
         NULL,
         next_movement,
         1,
         'FIRST_CHECK',
         timeinout
  FROM   ordered_data
  WHERE  rn = 1
UNION ALL
  SELECT o.emp_id,
         o.timeinout AS current_movement,
         o.flag,
         o.rn,
         CASE
         WHEN o.timeinout < g.first_movement + INTERVAL '12' HOUR
         THEN o.previous_movement
         ELSE NULL
         END,
         CASE
         WHEN o.timeinout < g.first_movement + INTERVAL '12' HOUR
         AND  (  o.next_movement >= g.first_movement + INTERVAL '12' HOUR
              OR o.next_movement IS NULL)
         THEN NULL
         ELSE o.next_movement
         END,
         CASE
         WHEN o.timeinout < g.first_movement + INTERVAL '12' HOUR
         THEN g.grp
         ELSE g.grp + 1
         END,
         CASE
         WHEN o.timeinout < g.first_movement + INTERVAL '12' HOUR
         AND  (  o.next_movement >= g.first_movement + INTERVAL '12' HOUR
              OR o.next_movement IS NULL)
         THEN 'LAST_CHECK'
         WHEN o.timeinout < g.first_movement + INTERVAL '12' HOUR
         THEN 'DURING_DAY'
         ELSE 'FIRST_CHECK'
         END,
         CASE
         WHEN o.timeinout < g.first_movement + INTERVAL '12' HOUR
         THEN g.first_movement
         ELSE o.timeinout
         END
  FROM   ordered_data o
         INNER JOIN grouped_data g
         ON (o.emp_id = g.emp_id AND o.rn = g.rn + 1)
)
SELECT emp_id,
       current_movement,
       flag,
       previous_movement,
       next_movement,
       (next_movement - current_movement) DAY TO SECOND AS diff,
       check_status
FROM   grouped_data
ORDER BY emp_id, current_movement

db<>fiddle here

A: You can use a PIPELINED function:
CREATE TYPE my_table_type AS OBJECT (
  emp_id            NUMBER,
  current_movement  DATE,
  flag              NUMBER,
  previous_movement DATE,
  next_movement     DATE,
  diff              INTERVAL DAY TO SECOND,
  check_status      VARCHAR2(15)
);

CREATE TYPE my_table_tbltype AS TABLE OF my_table_type;

Then:
CREATE FUNCTION parse_my_table RETURN my_table_tbltype PIPELINED
AS
  c_shift_length      CONSTANT INTERVAL DAY TO SECOND := INTERVAL '12' HOUR;
  v_emp_id            MY_TABLE.EMP_ID%TYPE;
  v_first_movement    MY_TABLE.TIMEINOUT%TYPE;
  v_previous_movement MY_TABLE.TIMEINOUT%TYPE;
  v_next_movement     MY_TABLE.TIMEINOUT%TYPE;
  v_check_status      VARCHAR2(15);
BEGIN
  FOR row IN (
    SELECT m.*,
           LAG(timeinout) OVER (PARTITION BY emp_id ORDER BY timeinout)
             AS previous_movement,
           LEAD(timeinout) OVER (PARTITION BY emp_id ORDER BY timeinout)
             AS next_movement
    FROM   my_table m
    ORDER BY m.emp_id, m.timeinout
  )
  LOOP
    IF v_emp_id IS NULL
    OR v_emp_id != row.emp_id
    OR row.timeinout >= v_first_movement + c_shift_length THEN
      v_emp_id            := row.emp_id;
      v_first_movement    := row.timeinout;
      v_previous_movement := NULL;
      v_next_movement     := row.next_movement;
      v_check_status      := 'FIRST_CHECK';
    ELSIF row.next_movement >= v_first_movement + c_shift_length
    OR    row.next_movement IS NULL THEN
      v_previous_movement := row.previous_movement;
      v_next_movement     := NULL;
      v_check_status      := 'LAST_CHECK';
    ELSE
      v_previous_movement := row.previous_movement;
      v_next_movement     := row.next_movement;
      v_check_status      := 'DURING_DAY';
    END IF;
    PIPE ROW (
      my_table_type(
        row.emp_id,
        row.timeinout,
        row.flag,
        v_previous_movement,
        v_next_movement,
        (v_next_movement - row.timeinout) DAY TO SECOND,
        v_check_status
      )
    );
  END LOOP;
END;
/

Then:
SELECT *
FROM   TABLE(parse_my_table());

Outputs:

EMP_ID
CURRENT_MOVEMENT
FLAG
PREVIOUS_MOVEMENT
NEXT_MOVEMENT
DIFF
CHECK_STATUS

1
2018-07-03T16:39:44
0

2018-07-04T01:14:40
+00 08:34:56.000000
FIRST_CHECK

1
2018-07-04T01:14:40
1
2018-07-03T16:39:44
2018-07-04T01:14:44
+00 00:00:04.000000
DURING_DAY

1
2018-07-04T01:14:44
1
2018-07-04T01:14:40

LAST_CHECK

1
2018-07-04T16:14:52
0

2018-07-05T01:07:40
+00 08:52:48.000000
FIRST_CHECK

1
2018-07-05T01:07:40
1
2018-07-04T16:14:52
2018-07-05T01:07:44
+00 00:00:04.000000
DURING_DAY

1
2018-07-05T01:07:44
1
2018-07-05T01:07:40

LAST_CHECK

1
2018-07-05T16:31:08
0

2018-07-06T01:01:48
+00 08:30:40.000000
FIRST_CHECK

1
2018-07-06T01:01:48
1
2018-07-05T16:31:08
2018-07-06T01:01:52
+00 00:00:04.000000
DURING_DAY

1
2018-07-06T01:01:52
1
2018-07-06T01:01:48

LAST_CHECK

2
2018-07-03T08:37:40
0

2018-07-03T16:27:36
+00 07:49:56.000000
FIRST_CHECK

2
2018-07-03T16:27:36
0
2018-07-03T08:37:40

LAST_CHECK

2
2018-07-04T08:37:04
0

2018-07-04T12:58:36
+00 04:21:32.000000
FIRST_CHECK

2
2018-07-04T12:58:36
0
2018-07-04T08:37:04
2018-07-04T13:09:48
+00 00:11:12.000000
DURING_DAY

2
2018-07-04T13:09:48
0
2018-07-04T12:58:36
2018-07-04T17:15:32
+00 04:05:44.000000
DURING_DAY

2
2018-07-04T17:15:32
0
2018-07-04T13:09:48

LAST_CHECK

db<>fiddle here

A: You can use a MODEL clause:
SELECT emp_id,
       current_movement,
       flag,
       previous_movement,
       next_movement,
       (next_movement - current_movement) DAY TO SECOND AS diff,
       check_status
FROM   (
  SELECT m.*,
         ROW_NUMBER() OVER (PARTITION BY emp_id ORDER BY timeinout) AS rn
  FROM   my_table m
)
MODEL
  PARTITION BY (emp_id)
  DIMENSION BY (rn)
  MEASURES (
    timeinout AS current_movement,
    flag,
    CAST(NULL AS DATE) AS first_movement,
    CAST(NULL AS DATE) AS previous_movement,
    CAST(NULL AS DATE) AS next_movement,
    CAST(NULL AS VARCHAR2(11)) AS check_status
  )
  RULES (
    first_movement[1]       = current_movement[1],
    first_movement[rn>1]    = CASE
                              WHEN current_movement[cv(rn)] < first_movement[cv(rn)-1] + INTERVAL '12' HOUR
                              THEN first_movement[cv(rn)-1]
                              ELSE current_movement[cv(rn)]
                              END,
    previous_movement[1]    = NULL,
    previous_movement[rn>1] = CASE
                              WHEN current_movement[cv(rn)] < first_movement[cv(rn)-1] + INTERVAL '12' HOUR
                              THEN current_movement[cv(rn)-1]
                              ELSE NULL
                              END,
    next_movement[1]        = current_movement[cv(rn)+1],
    next_movement[rn>1]     = CASE
                              WHEN current_movement[cv(rn)+1] < first_movement[cv(rn)] + INTERVAL '12' HOUR
                              THEN current_movement[cv(rn)+1]
                              ELSE NULL
                              END,
    check_status[1]         = 'FIRST_CHECK',
    check_status[rn>1]      = CASE
                              WHEN first_movement[cv(rn)-1] != first_movement[cv(rn)]
                              THEN 'FIRST_CHECK'
                              WHEN current_movement[cv(rn)+1] < first_movement[cv(rn)] + INTERVAL '12' HOUR
                              THEN 'DURING_DAY'
                              ELSE 'LAST_CHECK'
                              END
  )

Which outputs:

EMP_ID
CURRENT_MOVEMENT
FLAG
PREVIOUS_MOVEMENT
NEXT_MOVEMENT
DIFF
CHECK_STATUS

1
2018-07-03T16:39:44
0

2018-07-04T01:14:40
+00 08:34:56.000000
FIRST_CHECK

1
2018-07-04T01:14:40
1
2018-07-03T16:39:44
2018-07-04T01:14:44
+00 00:00:04.000000
DURING_DAY

1
2018-07-04T01:14:44
1
2018-07-04T01:14:40

LAST_CHECK

1
2018-07-04T16:14:52
0

2018-07-05T01:07:40
+00 08:52:48.000000
FIRST_CHECK

1
2018-07-05T01:07:40
1
2018-07-04T16:14:52
2018-07-05T01:07:44
+00 00:00:04.000000
DURING_DAY

1
2018-07-05T01:07:44
1
2018-07-05T01:07:40

LAST_CHECK

1
2018-07-05T16:31:08
0

2018-07-06T01:01:48
+00 08:30:40.000000
FIRST_CHECK

1
2018-07-06T01:01:48
1
2018-07-05T16:31:08
2018-07-06T01:01:52
+00 00:00:04.000000
DURING_DAY

1
2018-07-06T01:01:52
1
2018-07-06T01:01:48

LAST_CHECK

2
2018-07-03T08:37:40
0

2018-07-03T16:27:36
+00 07:49:56.000000
FIRST_CHECK

2
2018-07-03T16:27:36
0
2018-07-03T08:37:40

LAST_CHECK

2
2018-07-04T08:37:04
0

2018-07-04T12:58:36
+00 04:21:32.000000
FIRST_CHECK

2
2018-07-04T12:58:36
0
2018-07-04T08:37:04
2018-07-04T13:09:48
+00 00:11:12.000000
DURING_DAY

2
2018-07-04T13:09:48
0
2018-07-04T12:58:36
2018-07-04T17:15:32
+00 04:05:44.000000
DURING_DAY

2
2018-07-04T17:15:32
0
2018-07-04T13:09:48

LAST_CHECK

db<>fiddle here


text:
Q: Passing Parameter to URL ASP.NET MVC I was just wondering what the best practice is for passing a parameter into a URL that contains characters that you do not wish to pass to the URL. For example, I pass the string /LM/W3SVC/7/ROOT into the URL but I want to pass it without the backslashes, thus like LMW3SVC7ROOT
The way I currently do this is by using .Replace(). This is the full line of code that I currently use <a href="@Url.Action("Errors", new { id=item.Application.Replace("/", "").Replace(".", "")})"> @Html.DisplayFor(modelItem => item.Application) </a> which works fine but throws out a warning every now and again so I was just wondering if this is the correct way of implementing it.
'Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'string'
Thanks in advance.

A: The problem you're getting is from var queryString = RouteData.Values["id"];. If you look in Visual Studio and hover over var it will tell you the type of that particular var, which in this case is Object.
Try:
var queryString = RouteData.Values["id"].ToString();

In this case, you're finding yourself having to replace certain characters in your string, which probably means server side, you might be having to do some extra logic to cope without having these characters on the received string. In your View, just wrap the id in Url.Encode:
id = Url.Encode(item.Application)

You will receive this server side with the string decoded, i.e. /LM/W3SVC/7/ROOT

redpajama_set_name: RedPajamaStackExchange


text:
Q: Headless UI "leave" transition not working in React My navbar is setup such that on state change the hamburger menu opens and closes. While the enter animation works perfectly, the leave doesn't. My animation is a smooth slide in and slide out, but only the slide in works whereas on leave it just closes normally.
const NavbarMenu = ({ isOpen, menuClick }) => {
  return (
    <Transition appear={true} show={isOpen}>
      <Transition.Child
        class="flex flex-col bg-yellow-700 fixed top-0 right-0 p-5 z-20 w-1/2 h-full transition ease-in-out duration-300"
        enter="transition-opacity ease-in-out duration-700"
        enterFrom="translate-x-full"
        enterTo="translate-x-0"
        leave="transition-opacity ease-out duration-700"
        leaveFrom="opacity-100"
        leaveTo="opacity-0"
      >
        <Exit className="text-yellow-100 w-1/6" onClick={() => menuClick()} />

          About
          About
          About

      </Transition.Child>
    </Transition>
  );
};

A: Your leave transition is missing the translate-x classes.
You probably also want to add the opacity transition to the enter animation.
This should work:
const NavbarMenu = ({ isOpen, menuClick }) => {
  return (
    <Transition appear={true} show={isOpen}>
      <Transition.Child
        class="flex flex-col bg-yellow-700 fixed top-0 right-0 p-5 z-20 w-1/2 h-full transition duration-700"
        enter="ease-in-out"
        enterFrom="translate-x-full opacity-0"
        enterTo="translate-x-0 opacity-100"
        leave="ease-out"
        leaveFrom="translate-x-0 opacity-100"
        leaveTo="translate-x-full opacity-0"
      >
        <Exit className="text-yellow-100 w-1/6" onClick={() => menuClick()} />

          About
          About
          About

      </Transition.Child>
    </Transition>
  );
};

A: Most often when "leave transitions" doesn't work it's because it unmounts before the transition ends. To work around that you need a "between state" that is triggered when the Transition is in show mode. Then create a useEffect that listens to this state, and set a setTimeout that does the actual unmount of the element.

A: I found a solution, just delay the execution of set state to 0ms so the transition can trigger the leave property. I don't have a logical explanation but this worked smoothly.
    const NavbarMenu = ({ isOpen, menuClick }) => {
  return (
    <Transition appear={true} show={isOpen}>
      <Transition.Child
        class="flex flex-col bg-yellow-700 fixed top-0 right-0 p-5 z-20 w-1/2 h-full transition ease-in-out duration-300"
        enter="transition-opacity ease-in-out duration-700"
        enterFrom="translate-x-full"
        enterTo="translate-x-0"
        leave="transition-opacity ease-out duration-700"
        leaveFrom="opacity-100"
        leaveTo="opacity-0"
      >
        <Exit className="text-yellow-100 w-1/6"
              onClick={() =>
                setTimeout(() => {
                    menuClick();
                }, 0);
              } />

          About
          About
          About

      </Transition.Child>
    </Transition>
  );
};


text:
Q: PHP Keep on getting blank messages I have a very strange problem I have a form on my website which users fills out, everything works fine, with validation and the works, it's pretty solid, however I keep on getting 2 of these emails daily:
A new Enquiry has been received from http://www.cccccc.com.au. Please find details below and follow up:
Email :
Phone Number :
Event Type:
Number Guests:
State:
Suburb:
IP ADDRESS:173.245.50.130
Message:

Why is this why am I getting this?
I have traced the Ip and it comes from the US, which is weird since our website is targeted for Australia and most of our traffic comes from google adwords. However the ISP of the IP is cloudflare which is our hosting provider....?

Any idea to why / how am I getting these blanks?
Here is my script....pretty nasic but it gets the message to us
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$eventType = $_POST['eventType'];
$nrGuests = $_POST['nrGuests'];
$state = $_POST['state'];
$suburb = $_POST['suburb'];
$msg = $_POST['msg'];
$ip = $_SERVER['REMOTE_ADDR'];

    $to_email       = "xxxx@axxxxcom.au, xxxxx@xxxxxx.co.nz";

    $suburb     =   filter_var($_POST["suburb"], FILTER_SANITIZE_STRING);
    $subject        = "You Have a New Booking!";
    //Add booking INFO here;
    $message        = "A new Enquiry has been received from http://www.fingerfoods.com.au. Please find details below and follow up:";

    //email body
    $message_body = $message."\r\n\r\n".$name."\r\nEmail : ".$email."\r\nPhone Number : ". $mobile."\r\nEvent Type: ".$eventType."\r\nNumber Guests:".$nrGuests."\r\nState: ".$state."\r\nSuburb:".$suburb."\r\nIP ADDRESS:".$ip."\r\nMessage:".$msg;

    //proceed with PHP email.
    $headers = 'From: '.$name.'' . "\r\n" .
    'Reply-To: '.$email.'' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    $send_mail = mail($to_email, $subject, $message_body, $headers);
    if($send_mail)
    {
    echo '
Enquiry Successfully submitted
';
}
else{
    echo'
OOPS...SOMETHING WENT WRONG, PLEASE TRY AGAIN!
';
}
        ?>

THIS MAY SOUND A BIT STUPID BUT ANY IDEA WHY I AM I GETTING THESE BLANK EMAILS?? AS SEEN ABOVE

A: First of all, $_SERVER['REMOTE_ADDR'] gives the IP address from which the request was sent to the web server. This is typically the visitor's address, but in your case, it sounds like there is some kind of proxy sitting right before the web server that intercepts the requests, hence to the web server it appears as though the requests are originating from there.
Secondly, maybe you're not getting parameters values because you send GET requests and not POST, you can use $_REQUEST(get content of GET, POST, and COOKIE varialbe) instead of you don't distinguish between GET and POST requests.
for more info. about requests kinds
And the most important thing, you MUST check inputs values, don't send form values unless they are not empty!


text:
Q: How to pass a callback function to a StreamController I was wondering something I'm creating a StreamController like that:
class {
  StreamController _controller =
      new StreamController(onListen: _onListen(), onPause: _onPause(),
          onResume: _onResume(), onCancel: _onCancel());

    Stream get stream => _controller.stream;
}

in an other class I invoke
var sub = myInstance.stream.listen(null);

and I'm really surprise that all the callbacks in the StreamController's constructor are triggered.
Is there an explanation for this behavior ?
Cheers !

A: You should not add the parens ()
class {
  StreamController _controller =
      new StreamController(onListen: _onListen, onPause: _onPause,
          onResume: _onResume, onCancel: _onCancel);

    Stream get stream => _controller.stream;
}

This way the expression you pass as argument to onListen, onPause, ... is a reference to a method/function. When you add parents the expression is a method/function call and the actual argument to onListen, onPause, ... is the return value of the expression.
Alternatively you could to it this way (I omitted arguments because I want to save the time to looke them up)
class {
  StreamController _controller =
      new StreamController(onListen: () => _onListen(), onPause: () => _onPause(),
          onResume: () => _onResume(), onCancel: () => _onCancel());

    Stream get stream => _controller.stream;
}


text:
Q: is there any way to calculate height of irregular tetrahedron with pythagoras theorem given an irregular tetrahedron of side length $a$,$b$,$c$,$d$,$e$,$f$, is it possible to find the perpendicular distance from its apex to base with the help of pythagoras theorem

A: Yes, using two expressions for the volume of the tetrahedron $ABCD$
\begin{align}
V&=\tfrac13\,S_{abc}\cdot h
,\\
V&=
\frac1{12}\,
\left(
4\, u^2\, v^2\, w^2+(u^2+v^2-c^2)\, (v^2+w^2-a^2)\, (u^2+w^2-b^2)
\right.
\\
&\phantom{=}
\left.
-u^2\, (v^2+w^2-a^2)^2-v^2\, (u^2+w^2-b^2)^2-w^2\, (u^2+v^2-c^2)^2
\right)^{1/2}
,
\end{align}
where
\begin{align}
a&=|BC|
,\quad
b=|AC|
,\quad
c=|AB|
,\\
u&=|AD|
,\quad
v=|BD|
,\quad
w=|CD|
.
\end{align}
See
The volume of the pyramid in terms of its side lengths
for the reference.


text:
Q: TextBox with Data Binding should display helper text when empty I am working on an application in C# using the .NET Framework 3.5.  I have a TextBox on one of my forms that is bound to the "ID" property of the DataContext of the form, like so:
<TextBox x:Name="txtID"
    Grid.Row="0" Grid.Column="1"
    Margin="2" MinWidth="200" VerticalAlignment="Top"
    Style="{StaticResource validationToolTip}"
    >
    <TextBox.Text>
        <Binding Path="ID" UpdateSourceTrigger="PropertyChanged"
            ValidatesOnDataErrors="true">
            <Binding.ValidationRules>
                <ui:RequiredFieldValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

I would like the TextBox to display some helper text ("[Leave blank to auto-generate.]") when the ID property is empty and the TextBox does not have input focus.  I am considering styling this text differently (italicize) to distinguish it from a user-typed ID.  Since the TextBox.Text property is bound to the ID property, however, I want to make sure that my solution doesn't cause the ID property to be set to the value of my helper string.  How should I go about implementing this behavior?

A: The simplest approach would be to have a label over the text box to contain the text, or use a tooltip for the text
Another approach would be to have a class sit between the control and the data class that you are currently bound to.  This class could then pass the required '[Leave blank to auto-generate.]' text if the text in the data class is empty, or pass through the value if it is not.  For all the other fields the value would just be a pass through

A: Here's a straightforward approach that can pretty trivially be turned into a control template or a user control:
<Grid>
  <TextBox
     Foreground="LightGray"
     Focusable="False"
     Text="This is the help text."/>
  <TextBox
     Focusable="True"
     Text="The help text only displays if this is empty.">
    <TextBox.Style>
      <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
        <Style.Triggers>
          <DataTrigger
             Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text}"
             Value="">
            <Setter Property="Background" Value="Transparent"/>
          </DataTrigger>
        </Style.Triggers>
      </Style>
    </TextBox.Style>
  </TextBox>
</Grid>

Note that the internal style set here is based on the default style for the TextBox, so this should continue to display properly if you globally restyle the TextBox.


text:
Q: How to type check a function in python3 that has an optional argument initially set to None? How do I use type checking in a function that has optional parameters? For instance:
def do_something_cool(number1: int, letter1: str, seed=None: (None, int) )-> str:
    return

will fail because of (None, int). What is the correct syntax for this?

A: With most type checkers the following works without explicitly saying that the value is nonable:
def do_something_cool(number1: int, letter1: str, seed: int = None) -> str:
    return

However, you can also explicitly specify that the value is nonable:
from typing import Optional

def do_something_cool(number1: int, letter1: str, seed: Optional[int] = None) -> str:
    return

Big warning here: typing.Optional actually means Nonable and has nothing to do with the fact that your value has a default value (so it does not mean "optional"). See this discussion. One way to remember it is to think of Optional as applying to the type, not to the value.
PEP484 was previously recommending the implicit writing, but now recommends that you explicitly states Optional when your value is Nonable. See here.


text:
Q: MySQL date format sort error desc or asc date for sorting query fails :(
How am I supposed to mSQL query?
Please could you help?
$tours = mysql_query("SELECT * FROM tours WHERE tour_category_id='".$tour_category_id[category_id]."' AND tour_status='Aktif' ORDER BY kayit_tarihi DESC ");

A:   $someVariable =  $tour_category_id[category_id];
 $tours = mysql_query("SELECT * FROM tours WHERE tour_category_id='$someVariable' AND tour_status='Aktif' ORDER BY kayit_tarihi DESC ");

Try this.

A: $tours = mysql_query("SELECT *
                      FROM tours
                      WHERE tour_category_id='".$tour_category_id[category_id]."'
                        AND tour_status='Aktif'
                      ORDER BY tour_category_id DESC ");

A: change $tour_category_id[category_id] to $tour_category_id["category_id"]


text:
Q: 10g network cards running at less than 1 gigabit I have installed 10 gigabit fiber-optic cards in two of my servers, but when I test their throughput they run at only around 600Mbps or so:
$ scp random.1G rcm2:/tmp
random.1G 100% 1024MB  73.1MB/s   00:14

My routes look correct.  The network drivers and hardware seem to be setup correctly.
Can someone please tell me where I should be looking next?
Here is more information:
Routing
172.16.157.34
$ ip route get 172.16.157.35
172.16.157.35 dev eth1  src 172.16.157.34

172.16.157.35
$ ip route get 172.16.157.34
172.16.157.34 dev eth2  src 172.16.157.35

Hardware/ifconfig
172.16.157.34
$ ifconfig
...
eth2      Link encap:Ethernet  HWaddr 90:e2:ba:38:aa:ee
          inet addr:172.16.157.34  Bcast:172.16.157.63  Mask:255.255.255.224
...
$ lshw -class network
   ...
   description: Ethernet interface
   product: 82599EB 10-Gigabit SFI/SFP+ Network Connection
   ...
   serial: 90:e2:ba:38:aa:ee
   ...

172.16.157.35
$ ifconfig
...
eth1      Link encap:Ethernet  HWaddr 90:E2:BA:38:AA:82
          inet addr:172.16.157.35  Bcast:172.16.157.63  Mask:255.255.255.224
...
$ lshw -class network
   ...
   description: Ethernet interface
   product: 82599EB 10-Gigabit SFI/SFP+ Network Connection
   ...
   serial: 90:e2:ba:38:aa:82
   ...

Driver setup
172.16.157.34
$ sudo ethtool eth2
Settings for eth2:
    Supported ports: [ FIBRE ]
    Supported link modes:   1000baseT/Full
                            10000baseT/Full
    Supported pause frame use: No
    Supports auto-negotiation: Yes
    Advertised link modes:  1000baseT/Full
                            10000baseT/Full
    Advertised pause frame use: No
    Advertised auto-negotiation: Yes
    Speed: 10000Mb/s
    Duplex: Full
    Port: FIBRE
    PHYAD: 0
    Transceiver: external
    Auto-negotiation: on
    Supports Wake-on: d
    Wake-on: d
    Current message level: 0x00000007 (7)
                   drv probe link
    Link detected: yes

172.16.157.35
$ sudo ethtool eth1
[sudo] password for jsp:
Settings for eth1:
    Supported ports: [ FIBRE ]
    Supported link modes:   1000baseT/Full
                            10000baseT/Full
    Supported pause frame use: No
    Supports auto-negotiation: Yes
    Advertised link modes:  1000baseT/Full
                            10000baseT/Full
    Advertised pause frame use: No
    Advertised auto-negotiation: Yes
    Speed: 10000Mb/s
    Duplex: Full
    Port: FIBRE
    PHYAD: 0
    Transceiver: external
    Auto-negotiation: on
    Supports Wake-on: d
    Wake-on: d
    Current message level: 0x00000007 (7)
                   drv probe link
    Link detected: yes

A: scp has a large overhead for encrypting the data while in flight. Something thinner like nc will give you better throughput and a more realistic test of the physical capabilities of your server and network.
Also, make sure your bottleneck doesn't exist somewhere else like your disks. Use iperf or something similar to test non-diskbound throughput.


text:
Q: update TextBox text format on LostFocus - WinRT I am developing an Windows Store app using C# and XAML and am working on a user input page. I use an IValueConverter that converts my bound data into currency formatted string instead of just showing a decimal.
When the user navigates to the page, the converter works fine and the TextBox text shows up with a currency format. However, when the user changes the TextBox.Text value and then the TextBox loses focus, the converter does not change it into a nice currency format again, it just stays formatted as it was entered by the user.
As far as I can tell, there is no StringFormat to use like in WPF, so how do I get the TextBox to display the currency format again after the user edits the value?
My converter:
public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (parameter == null)
            return ((decimal)value).ToString();
        return String.Format((string)parameter, (decimal)value);
    }

public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        decimal decVal = 0M;
        decimal.TryParse((string)value, out decVal);
        return decVal;
    }

My XAML:
<Grid x:Name="InputGrid">
    ...
    <Border>
        <TextBox Text="{Binding MyValue, ConverterParameter='{}{0:c}', Converter={StaticResource DecimalValueConverter}, Mode=TwoWay}"
    </Border>
    ....
</Grid>

InputGrid.DataContext = MyValueClassInstance set in the code-behind

A: What if you do this:
<TextBox Text="{Binding MyValue, UpdateSourceTrigger=PropertyChanged, ConverterParameter='{}{0:c}', Converter={StaticResource DecimalValueConverter}, Mode=TwoWay}"

A: Does your converter work both ways? I suspect that if it doesn't - the TwoWay binding gets broken.


text:
Q: Add Calculated Row into a Select I have a single table housing sets of data which I partition to do a Zscore per set.  I calculate the average of the set.  I calculate the STDEV of the set.  I calculate the ZScore of the set.
Then per set I want to add to the SELECT partitions a row that has 'My Label', [Set columns], [Calculated Partition Average+X*STDEV)
Below uses X=1.5 and the table data would contain partitioned apple and orange data
item    value avg   stdev
apple     1    2    0.81
apple     2    2    0.81
apple     3    2    0.81
my apple  3.2  null null
orange    2    4.6  2.49
orange    4    4.6  2.49
orange    8    4.6  2.49
my orange 8.4   null null

A: (I assumed you meant STDEVP, not STDEV)
You could do that with a query like this (including sample data creation - table @t):
DECLARE @t TABLE(item VARCHAR(10), value FLOAT);
INSERT INTO @t(item, value)
VALUES('apple', 1),
    ('apple', 2),
    ('apple', 3),
    ('orange', 2),
    ('orange', 4),
    ('orange', 8);

DECLARE @factor FLOAT=1.5;

WITH
    tmp AS (
               SELECT item, value, AVG(value) OVER (PARTITION BY item) AS [Avg], STDEVP(value) OVER (PARTITION BY item) AS [StdevP]
               FROM @t
               UNION ALL
               SELECT item, AVG(value)+(STDEVP(value)* @factor) AS [Value], NULL AS [avg], NULL AS [StdevP]
               FROM @t
               GROUP BY item
           )
SELECT CASE WHEN [Avg] IS NULL THEN 'My ' ELSE '' END+item AS [Label], value, [Avg], [StdevP]
FROM tmp
ORDER BY item, CASE WHEN [Avg] IS NULL THEN 1 ELSE 0 END;


text:
Q: How can I secure my C# software with a registration key during setup?
Possible Duplicate:
How can I create a Product Key for my C# App

I am developing some software with C#.
I want the software to run on a specific system with a registration key.
I want to generate a key for it. How can I make a setup program for it?
Please help me to develop the setup for it with system registration.

A: I would recommend purchasing and using a 3rd party licensing system instead of rolling your own.
I personally have had good luck with the Eziriz products, which provide a lot of functionality for the price.


text:
Q: Impersonate current user when calling a Google API using service account & delegation of authority There is a marketplace requirement that if a Google Apps for Work domain admin installs our app for their domain, the admin and any users from their domain should thereafter not see a scope auth screen when accessing our app.  The act of installing the app for the domain should implicitly delegate domain-wide authority for the service account associated with our app.
In order to achieve this behavior, I am trying to do delegation of authority to a service account to work on behalf of, AKA impersonate, the currently logged in user.
The code snippet below shows the various attempts that I've made to get this to work. The only one that does work is to pass a domain superuser's email address as the "sub" param (AKA prn) when creating the JWT.  However, this essentially elevates a regular run of the mill domain user's privileges to those of super user which is not the desired effect.
var client = new googleapis.auth.JWT(
    '<serviceaccount>@developer.gserviceaccount.com',
    'localhost.pem',
    null,
    ["https://www.googleapis.com/auth/admin.directory.user.readonly"],
    //  null - // 403 not auth
    // {'userId' : 'domainsuperuser@email.com'} // 403 not auth
    // {'userId' : 'me'} // 403 not auth
    // "domainsuperuser@email.com" // works!
    // "{domainsuperuser@email.com}" // not a valid email error
    // 'me' // invalid impersonation prn email address
  );

Does Google honor any other ID than just the email address of the person you want to impersonate such as the special 'me' value?
It feels like we are running into a chicken and egg problem here.  Essentially we don't want to hardcode the email address (especially not an admin email), so it feels like we have to make an API call.  But we can't make an API call without impersonating a user.

A: You don't need to use a service account and domain-wide delegation in this case. Instead, simply go through the normal OAuth2 flow with the user, and the approval screen will be skipped automatically.
When the admin installs the app and approves your scopes, they are essentially automatically granting you access to those scopes for all users in the domain. And while it is a requirement that users not see the approval screen, you still have to go through the OAuth2 flow with them in order get the OAuth2 token. If you launch an OAuth2 flow for the user, and don't request any scopes not already approved by the domain admin and don't set approval_prompt=force in the URL, then the OAuth2 approval screen will instantly redirect to your redirect URI, making the process invisible to the user.


text:
Q: How to mark different bibliographies with different letters in amsrefs? It seems that amsrefs strikes again!  I'd like to have more than one bibliography, and in the first one, the entries should be marked, say, as [A1], [A2] etc., in the second, say, [B1], [B2] etc. and so on.  I could use \BibLabel to modify the look of the entries in the bibliography, and modify \cite@somethings to modify the references, but this seems to be an ugly hack.  Any better ideas?

A: OK, nobody took the challenge;), so I had to dig through some amsrefs code myself.  (Not that I understand it completely - it seems to be rather a mess...)  This code did the trick:
\usepackage{amsrefs}
\usepackage{etoolbox}
\makeatletter
\newcommand{\setbibprefix}[1]{\def\bib@prefix{#1}}
\pretocmd{\thebib}{\bib@prefix}{}{}
\setbibprefix{}
\makeatother


text:
Q: unhashable type: 'list' error with my project i was traying to make a percentage calculator program with python , by this way :
students = {'mohamed':(60,80,90),
           'omar':(50,77,69),
           'ahmed':(88,66,87),
           'ali':(888,69,54)}

names = list(students.keys())

def percentage_calc(a,b,c):
   per = (a + b + c / 300 )*100
   return per

mm = {}

for name in names:
   a , b ,c = students[names]
   mm[names] = percentage_calc(a, b, c)

for name , result in sorted(mm.items()):
   print('the result of {} is {:3.2f} %'.foramt(name,result))

but i got that error :

how can I fix it ? , thanks.

A: There are 3 mistakes in your code:

*

*1: students[name] instead of students[names]

*2: mm[name] instead of mm[names]

*3: {your_code}.format(name,result))  instead of {your_code}.foramt(name,result))


text:
Q: Calling telnet from an ssh command I am trying to figure out a problem, which I have to do in a certain way, unfortunately.
When I ssh into a remote host and log in (this will require a login), it is successful. If I then telnet to another host, telnet works fine.
However, I need to find a way to call telnet from the ssh command when I issue this command:
ssh FIRSTHOST 'telnet SECONDHOST'

(Yes, I am supposed to make this command work.)
When I try to login to the second host (after logging into the first), the input is simply echoed to the screen, and not sent to the second host.
-- Added example from comments -----------
ssh 172.24.128.1 <RETURN> followed by telnet 172.20.1.1 WORKS but the command ssh 172.24.128.1 'telnet 172.20.1.1' will NOT connect properly to the telnet session; any keystokes are echoed without being processed.
An example below
[hmuser@localhost ~]$ ssh 172.24.128.1 'telnet 172.20.1.1'
hmuser@172.24.128.1's password:
Trying 172.20.1.1...
Connected to 172.20.1.1.
Escape character is '^]'.
Welcome to Microsoft Telnet Service login: sdf sdf

I have tried several options, including setting remote ports.
I can't seem to find anything on the web for this. Duplicating this would be good and finding a solution to this would be great.

A: Forcing TTY should solve this issue. Sorry for coming too late.
ssh -t FIRSTHOST 'telnet SECONDHOST'

Please mark it as a solution to remove this question from "unanswered".


text:
Q: Plot: Show specific values in y axis I need to plot a list of points and I am using ListLinePlot. Mathematica decides which values on the y axis are labeled.  How can I show labels for the exact y value of each point?

A: As pointed out by @eldo there is a risk of the labels overlapping. In addition to the methods he mentioned to deal with this, you can reduce the likelihood of overlap by using a Frame and alternating labels between left and right FrameTicks.
data = Round[#, .01] & /@ RandomReal[{0, 7}, {9, 2}] // Sort;

yValues = data[[All, 2]] // Sort;

{yLeft, yRight} = ({yValues, ""} //
       Flatten // Partition[#, 2] & //
       Transpose) /. "" -> Sequence[];
(* padded to handle cases with odd number of points *)

ListLinePlot[Tooltip /@ data,
 Frame -> True, Axes -> False,
 FrameTicks -> {{yLeft, yRight}, {Automatic, None}},
 GridLines -> {Automatic, yValues},
 PlotMarkers -> Automatic]

A: If you have only a couple of points you could try
data = {1.2, 4.3, 5.3, 2.721, 7.32, 1.7, 4.9};

ListLinePlot[
 data,
 Ticks -> {Automatic, data},
 GridLines -> {Automatic, data},
 PlotMarkers -> Automatic]

However, if points are not sufficiently apart ticks will be overwritten. Therefore I would recommend to use Tooltip.
ListLinePlot[
 Tooltip @ data,
 GridLines -> Automatic,
 PlotMarkers -> Automatic]

Setting the mouse pointer on any point you can see its exact value.
With not too many points you might consider
points =
  Text[#2, {##}] & @@@ Transpose[{Range@Length@data, data}] /.
   {a_, b_} :> {a - 0.3, b - 0.3};

ListLinePlot[Tooltip@data,
 Epilog -> points,
 GridLines -> Automatic,
 PlotMarkers -> Automatic]

An unsuccessful rebellion against the closing votes:
data =
  Round[Table[Re[Zeta[1/2 + I x]], {x, 20, 40, 1}], 0.01];

points =
  Text[Framed[#2, FrameMargins -> {{3, 3}, {0, 0}}, Background -> White],
       {##}] & @@@ Transpose[{Range[20, 40], data}] /.
         {a_, b_} :> {a, b - 0.12} /.
            Framed[a_, b__] :> Framed[PaddedForm[a, {2, 2}], b];

ListLinePlot[
 Tooltip@data,
 Epilog -> points,
 DataRange -> {20, 40},
 Filling -> Axis,
 FillingStyle -> Directive[Opacity[0.5], LightBlue],
 Frame -> True,
 GridLines -> Automatic,
 ImageSize -> 600,
 MeshStyle -> Directive[Blue, PointSize[Large]],
 PlotMarkers -> Automatic,
 PlotRangePadding -> {{0.9, 0.5}, {0.3, 0.1}},
 PlotStyle -> GrayLevel@0.7]


text:
Q: SharePoint TextField ClientID changes? I'm trying to use some javascript on a page layout, and I'm encountering a strange issue where the ClientID of a Sharepoint.WebControls.TextField seems to change between OnLoad and the page being displayed.
In the OnLoad event, TextField3.ClientID resolves to "ctl00_PlaceHolderMain_TextField3", but if look to see why my js doesn't work, the page source reveals that the control id to be "ctl00_PlaceHolderMain_TextField3_ctl00_TextField".
Any ideas what's going on?
Here's the code I'm using:
public class PostingTemplate : Microsoft.SharePoint.Publishing.PublishingLayoutPage
{
    protected DropDownList author;
    protected TextField TextField3;
    private List<string> _authorNames;

    public List<string> AuthorName
    {
        get { return _authorNames; }
        set { _authorNames = value; }
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        author.AutoPostBack = false;
        this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
        "fillInAuthorText", getQuery(), true);
        author.Attributes.Add("onChange", "fillInAuthorText()");
        if (!Page.IsPostBack)
        {
            _authorNames = new List<string>();
            _authorNames = Utilities.GetAuthorList(SPContext.Current.Site);
            author.DataSource = _authorNames;
            author.DataBind();
        }
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        if (author.Items.Count > 0)
        {
            author.SelectedIndex = 0;
            TextField3.Text = ((ListItem)author.Items[author.SelectedIndex]).Text;
        }
    }

    private string getQuery()
    {
        string query = @" function fillInAuthorText() {
        var IndexValue = document.getElementById('";
        query += author.ClientID;
        query += @"').selectedIndex;
        var SelectedVal = document.getElementById('";
        query += author.ClientID;
        query += @"').options[IndexValue].value;
        document.getElementById('";
        query += TextField3.ClientID;
        query += @"').value = SelectedVal;
        }";
        return query;
    }
}

A: You need to include the client ID of the parent control as well.
// Replace:
query += author.ClientID;
// With:
query += base.ClientID + "_" + author.ClientID;

(Note that I've only ever done this with a web part so there may be some tweaking you need to do for it to work in a page layout.)
Another option is to resolve this client side. See Eric Shupp's blog for most info.

A: With help form Alex Angas, Here is what I discovered:
The TexField renders out some literals that end up surrounding a textbox, and it's really the textbox that you're interested in. Here's the modified section of code:
 private string getQuery()
    {
        string query = @" function fillInAuthorText() {
        var IndexValue = document.getElementById('";
        query += author.ClientID;
        query += @"').selectedIndex;
        var SelectedVal = document.getElementById('";
        query += author.ClientID;
        query += @"').options[IndexValue].value;
        document.getElementById('";
        query += getTextFieldID(TextField3);
        query += @"').value = SelectedVal;
        }";
        return query;
    }

    private string getTextFieldID(Control txt)
    {
        foreach (Control c in txt.Controls)
        {
            if (c.HasControls())
            {
                foreach (Control con in c.Controls)
                    if (con is TextBox)
                        return con.ClientID;
            }
        }

        return "";
    }

Keep in mind, this is specific to my application, your mileage my vary.


text:
Q: Radiobutton in Android Quiz app I am working on quiz app for Android and I use RadioButtons in RadioGroup. I want to achieve that when someone checks the right answer (this case its id/krzyzyk) the score will increase by one point. I made this code:
int score = 2;

public void onRadioButtonClicked(View view) {
    RadioButton radiobutton1 = (RadioButton) findViewById(R.id.krzyzyk);

    if (radiobutton1.isChecked()) {
        score = score + 1;
    }
}

It works but when I run the app and click in another RadioButton and again id/krzyzyk the score will update again. Can you help me to fix this problem?

A: Your code will always increment the score when the user taps on the RadioButton krzyzyk.
I'll suggest you to Submit the answer and go to the next question incrementing the score if the selected RadioButton is correct.
Change your code to something like:
public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();

    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.correct_answer: // this is id/krzyzyk
            if (checked)
                score++;
                // Go to next question
            break;
        case R.id.wrong_answer:
            if (checked)
                // Go to next question.
            break;
    }
}

A: You could disable the RadioButton or RadioGroup by setEnabled(boolean).
For example, you could disable the radio button that was selected by
radiobutton1.setEnabled(false);

I would suggest disabling all the radio buttons at that point, to prevent a user from changing their answer. You could do this all at once by calling setEnabled(boolean) on the radio group.
RadioGroup group = (RadioGroup) findViewById(R.id.myRadioGroup);
group.setEnabled(false);

A: You have think about logic of your quiz, of course score will  be increase because when you choose right answer and check this in listener ( this method calls on every click on button), it will be wrong result, maybe can you try make isChecked when you click on button (Next, Check) or swipe fragment with question, or you can use some variable like flag of wrong-right indicator,
int m_rightAnswer =0;
...
public void onRadioButtonClicked(View view) {
   RadioButton radiobutton1 = (RadioButton) findViewById(R.id.krzyzyk);

    if (radiobutton1.isChecked() && m_rightAnswer==0){
        score = score + 1; m_rightAnswer=1 }
              }

It's working only once, when you click on right answer, and when you click any radio button and return on right your score don't change, but it doesn't have logic


text:
Q: Google map api v3 shows half a map? I'm doing a project in Jquery Mobile and having a problem with the Google API. When I navigate to the MapPage from diffrent page the MapPage by itself shows the map OK, but when moving from the HomePage to MapPage it only shows half of the map. If I  manually refresh or resize map it will fix it - but I've tried map.resize() without luck so I need a different solution.

I've attached my HTML code of the HomePage and MapPage below:
<!DOCTYPE html>

     <meta charset="utf-8" />
     <meta name="description" content="Project - Mobile" />
     <meta name="author" content="Yuval Vardi" />
     <meta name="viewport" content="width=device-width, initial-scale=1">

     <title>RentAcar</title>

    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />

     Trip Info

 © Copyright Yuval Vardi

Pickup location

Where do you go?

                          <input id="startInput" type="text" value="" placeholder="Start location" />

                         <input type="text" id="end" placeholder="Return location"/>

                         <button id="myLocation" onclick="getMarker()" data-role="button" data-theme="e" > Find me </button>

                          <button onclick="calcRoute()" data-theme="b" > Calculate rout   </button>

 © Copyright Yuval Vardi

          Home

My javascript file:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var israel = new google.maps.LatLng(32.0938254, 34.7786934); // the var for our initial point
    var mapOptions = {
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: israel // where to center the map on initial!
    };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    directionsDisplay.setMap(map);
}

function calcRoute() {
    initialize();
    var start = document.getElementById('startInput').value;
    var end = document.getElementById('end').value;
    var distanceInput = document.getElementById("distance");

    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            distanceInput.value = response.routes[0].legs[0].distance.value / 1000;
        }
    });}

    google.maps.event.addDomListener(window, 'load', initialize);

    function getMarker()  {
        if (navigator.geolocation)  {
            navigator.geolocation.getCurrentPosition(showPosition,showError);
        }
    }

    function showPosition(position) {
        var lat=position.coords.latitude;
        var long=position.coords.longitude;
        marker(lat,long); //calls the marker function
    }

    function showError(error)
    {
        alert ("Error loading map");
    }

    function marker(lat,long) {
        var myLatlng = new google.maps.LatLng(lat,long);
        var mapOptions = {
            zoom: 12,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

    $("#startInput").attr("value",myLatlng);
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title:"You are Here!"
    });
}

A: The map div has zero width.  To use a percentage width, you have to define the width of all its parents (or at least up to a fixed size element that can be used to compute the width).
See Mike Williams' Google Maps API v2 tutorial page on percentage sizing

A: You need to call checkResize() API function. Like This:
map = new google.maps.Map(document.getElementById("map"), mapOptions);
map.checkResize()

This one worked for me as well


text:
Q: App crashes on changing theme under styles My Android App :
Target API:22
Min API:15
Device run on :API level 22
I don't understand this whole theme concept ,
In my manifest.xml ,I have set  android:theme="@style/AppTheme"
and all activities use this theme
Now my understanding is that they all use the theme called AppTheme which I can now define by extending other themes inside my styles.xml
In my styles.xml
I have this
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

</resources>

My understanding is that  AppCompat themes allow us to use newer(say material themes) on  older devices also .
I run this app on API Level 22 and API Level 15 , it works fine
Now when i change it to
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="android:Theme.Material">
        <!-- Customize your theme here. -->
    </style>

</resources>

It gives a warning saying this theme  can be used only on API 21 or above which is correct , now when  I ignore the warning and run it in on API 22 it crashes.
Why?
Also I tried to make AppTheme's parent as Holo , Light etc ,all of them crash the App , why , please explain?
All of these end up crashing the App
<style name="AppTheme" parent="android:Theme.Translucent">
   <style name="AppTheme" parent="android:Theme.Holo">

Why do these not work , Holo was introduced in 15 right?
I am using 22 ,
and can you please elaborate the difference between
Theme....., BaseTheme....,Android..... themeName
And i am running android studio 1.3 and using the latest versions(Stable) of the SDK,SDK build and SDK-Platform tools.
Thank you !

A: Sorry , I found the issue , My activity was extending AppCompatActivity instead of the general activity ,I get it now

A: When ever working with custom styles you have to take care of the parent you are providing. Try to change the parent theme and it might solve your problem.


text:
Q: Show in index notation that the rotation of a cross product is the cross product of the rotations Let $\vec{a}$ and $\vec{b}$ be two arbitrary vectors in 3-space $\Bbb R^3$, and $R$ be a real $3\times 3$matrix representing a proper rotation.  That is, $R$ satisfies the following properties:
$$
\sum_j R_{ij}R_{kj} = \sum_j R_{ji}R_{jk} = \delta_{ik} \\
\sum_{ijk} \epsilon_{ijk} R_{i1}R_{j2}R_{k3} = 1
$$
that is, $R$ is orthogonal and has determinant $+1$.
It is "obvious" that if you apply the rotation to each vector and then take the cross product, you get the same result as if you take the cross product first and then apply the rotation to that.
$$
(R \vec{a}) \times (R \vec{b}) = R (\vec{a} \times\vec{b}  )
$$
there are several ways to prove this, for example, see
Rotations preserve cross products?
.
What I would like to see is a proof that only uses index manipulations.  In terms of indices, what we are trying to prove is that assuming $R$ satisfies the two conditions given above,
$$
\sum_p R_{ip} \sum_{jk} \epsilon_{pjk} a_j b_k
=
\sum_{jk} \epsilon_{ijk}\sum_n R_{jn}a_n \sum_m R_{km}b_m
$$
One thing I tried is multiplying both sides by $R_{qi}$ and summing over $i$, because I can undo that by left-multiplying by $R$.  This comes down to needing to prove that
$$
\sum_{qjk}\epsilon_{ijk} R_{qi} R_{jn} R_{km} = \epsilon_{qnm}
$$
which looks tantalizingly close to the determinant = 1 condition, but I'm not quite there.

A: I'll use lower and upper indices to keep track of which indices are (respectively) covariant and contravariant, to make notationally clearer some later steps where we use the standard inner product to convert indices between the two types. In particular, we write a rotation $R$ as $R^i{}_j$ and the tensor defining the cross product operation as $\epsilon_{ij}{}^k$. In this notation, the desired property (after some relabeling) is
$$R^q{}_k \epsilon_{ij}{}^k = \epsilon_{ij}{}^p R^i{}_m R^j{}_n .$$ Here we use the Einstein summation convention, that is, we implicitly sum over any index that appears twice (once lower and once upper).
We write the inverse of a rotation as $(R^{-1})^i{}_j = (R^\top)^i{}_j = R_i{}^j$, in which notation the first property becomes $R_j{}^k R^i{}_k = \delta^i{}_k$. Then, as you've already done, we can contract both sides of the previous display equation with $R_q{}^r$ to show that the desired identity is equivalent to
$$\epsilon_{ij}{}^r = \epsilon_{mn}{}^q R^m{}_i R^n{}_j R_q{}^r .$$
Now, raising and lowering indices with the standard inner product $g$ gives the more symmetric equivalent identity
$$\phantom{(\ast)} \qquad \epsilon_{ijk} = \epsilon_{mnp} R^m{}_i R^n{}_j R^p{}_k ,  \qquad (\ast)$$ which is just the assertion that volume form $\epsilon$ is invariant under pullback by rotations.
If we use (the inverse of) the inner product to contract any two of the free indices $i, j, k$ in $\epsilon_{mnp} R^m{}_i R^n{}_j R^p{}_k$, say, $i, j$, we find $$g^{ij} \epsilon_{mnp} R^m{}_i R^n{}_j R^p{}_k = - g^{ij} \epsilon_{nmp} R^n{}_i R^m{}_j R^p{}_k = -g^{ji} \epsilon_{nmp} R^n{}_j R^m{}_i R^p{}_k ,$$ which together with symmetry of notation gives that $\epsilon_{mnp} R^m{}_i R^n{}_j R^p{}_k$ is totally skew (this particular statement holds for all linear transformations, not just rotations). Thus, to verify $(\ast)$ it's enough to check that it holds for $(i, j, k) = (1, 2, 3)$. But this is exactly the content of the second of the given identities for $R$, namely, $\epsilon_{mnp} R^m{}_1 R^n{}_2 R^p{}_3 = 1$.


text:
Q: Bootstrap Modal messes the design when scrolling The pre-loaders I used:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

I placed this modal on my page:

                asdasd

But right after doing that, the background image on my page when scrolling seems to glitch like this:

and also my header seems to be affected.
Here's the normal header without adding the modal bootsrap and its pre-loaders:

but when adding the modal bootstrap and its preloaders, when you try to scroll through the page, the header area shrinks:

as you can see, the white area in the header decreases. When scrolling back up, the white area goes back to its original size only a little bit smaller.
I tried messing around with my css but it seems I'm not going far with it.
The css I used to lock my header up top:
.header_scroll_lock {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
}

How can I solve this background-image and header glitch? Is this somewhat fixable with another css? Thanks guys.

.header_scroll_lock {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
}

#header_content {
  /*background-color: #e2e3e7;*/
  background-color: #FFFFFF;
  padding-top: 5px;
  padding-bottom: 5px;
  padding-right: 5px;
}

.header_separator {
  padding-top: 8px;
}
<!DOCTYPE html>

            sample header

            home

            about

            contact

<!DOCTYPE html>

  <title>modal problem</title>
  <link rel="stylesheet" type="text/css" href="css/style.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,800" rel="stylesheet">

                  inside of the modal

sample header

                            delete announcement

UPDATE
The background image glitch only happens on firefox.. I tried running it on chrome and it didn't glitched. It also won't happen (the glitch) here on snippet and jsfiddle.. However as you see, the header bar was affected.


text:
Q: Splunk REST Api : 201 with curl, 404 with python? I'm trying to request against Splunk REST Api. It works greate when calling the Api with curl :
curl -k  https://host:8090/services/collector/event -H "Authorization: Splunk AUTH_CODE" -d '{"event":"Hello, World!","source":"Airwatch","index":"client-myclient"}'
{"text":"Success","code":0}%

But when I try to pull the same request in python, I get a 404 error :
splunkhost = 'MY_IP'
splunkUrl = 'https://%s:8090/services/collector/event' % splunkhost
splunkData = {'index':'client-myclient','event':'Event Python Test'}
splunkResponse = requests.get(splunkUrl, headers={'Authorization': 'Splunk AUTH_CODE'}, data = splunkData, verify=False)
print splunkResponse.text

/Library/Python/2.7/site-packages/requests/packages/urllib3/connectionpool.py:789: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html InsecureRequestWarning)
{"text":"The requested URL was not found on this server.","code":404}

I understand the insecure warning comes from my verify=false. The headers seem to pass through (splunkResponse.erquest.headers displays them correctly), and my different test haven't given anything...
What am I missing ?

A: Turns out the curl was a POST request when the python was a GET one. Solved.


text:
Q: How to replace `require` function while upgrading a NodeJS project to TypeScript? I am trying to modify an existing NodeJS project from JavaScript to TypeScript but I don't know how to deal with require expressions like below:
const indexRouter = require('../routes/index');

const config = require('./config');

EDIT: This is the index.ts dile:
import express, {Request, Response, NextFunction} from 'express';
const router = express.Router();

/* GET home page. */
router.get('/', function(req: Request, res: Response, next: NextFunction) {
  res.render('index', { title: 'Express' });
});

export default router;

A: You don't have to change that lines. TypeScript understands CommonJS modules with the according configuration. But since you want to replace them, I assume you want to use ES6 modules.
It's
import indexRouter from '../routes/index';

import config from './config';


text:
Q: Accessing AppDelegate.h from project - Beginner I need to access AppDelegate.h from another project. The project structure is given below:

MYPROJECT
|_ OTHER PROJECT
     |______OSAPPDELEGATE.H

     |______OSAPPDELEGATE.M

|_ APPDELEGATE.H
|_ APPDELEGATE.M

I need to import #import AppDelegate.h from OsAppDelegate.h. How can i do this?

A: Set the Header Search Path within Xcode to:
$(PROJECT_DIR)/../OTHER PROJECT

and then simply:
#import "OSAPPDELEGATE.H"

better still, set the Header Search Path to:
$(PROJECT_DIR)/..

and:
#import "OTHER PROJECT/OSAPPDELEGATE.H"

However if you are importing an app delegate from another project then you are most certainly doing something wrong.

A: u can try doing this.. copy the methods of the app delegate into OsAppDelegate. not sure just try


text:
Q: How do I program an Arduino to ignore subsequent presses of a push button for 5 minutes after said button is pressed? I am using a push button to trigger a relay; the code for that is below.
I want to program my Arduino to ignore any subsequent presses of the push button for a period of 5 minutes. How do I include this function in my Arduino sketch?
The purpose of this is to disable the user from being able to repeatedly trigger the relay by repeatedly pressing the push button until a 5 minute interval has passed. This is for a public art piece and, as follows, such limitations need to be imposed to guarantee appropriate usage of the piece.
int pinButton = 8;
int Relay = 2;
int stateRelay = LOW;
int stateButton;
int previous = LOW;
long time = 0;
long debounce = 500;
int stayON = 5000; //stay on for 5000 ms

void setup() {
  pinMode(pinButton, INPUT);
  pinMode(Relay, OUTPUT);
}

void loop() {
  stateButton = digitalRead(pinButton);
  if(stateButton == HIGH && previous == LOW && millis() - time > debounce) {
    if(stateRelay == HIGH){
      digitalWrite(Relay, LOW);
    } else {
       digitalWrite(Relay, HIGH);
       delay(stayON);
       digitalWrite(Relay, LOW);
    }
    time = millis();
  }
  previous == stateButton;
}

A: You could add a variable to store the last time that the display was activated. You could then change your else statement to an elseif statement in which you compare the current run time against the last time it was activated. This would work similar to the debounce method that you used.
long lastActivated = 0; //last time display was activated
long myDelay = 300000; //5 minutes in millis

  if(stateButton == HIGH && previous == LOW && millis() - time > debounce) {
    if(stateRelay == HIGH){
      digitalWrite(Relay, LOW);
    } else if (millis() - lastActivated > myDelay) { //verifies it's been 5 minutes
       digitalWrite(Relay, HIGH);
       delay(stayON);
       digitalWrite(Relay, LOW);
       lastActivated = millis(); //resets lastActivated when display is allowed to activate
    }
    time = millis();
  }

A: It depends on the behavior of the device that the relay is operating.  If the relay should be ON for the entire time the art piece is operating, then use a simple delay():
int waitFiveMinutes = 300000;
// ... other stuff ...

void loop() {
  if (digitalRead(pinButton) == LOW)
  {
    digitalWrite(Relay, HIGH);
    delay(waitFiveMinutes);
    digitalWrite(Relay, LOW);
  }
}

If you only need to trigger the relay once, like for a garage door opener, then you delay on the button press:
void loop() {
  if (digitalRead(pinButton) == LOW)
  {
    triggerRelay();
    delay(waitFiveMinutes);
  }
}

void triggerRelay() {
  digitalWrite(Relay, HIGH);
  delay(200);  // you might not need this
  digitalWrite(Relay, LOW);
}

Either way, the button should not respond during the delay.  If it is responding, you may be accidentally bypassing the relay on your breadboard.


text:
Q: How to scrape the ratings and all the reviews from the website using selenium I want to scrape the rating and all the reviews on the page .But not able to find the path .
enter code here
import urllib.request
from bs4 import BeautifulSoup
import csv
import os
from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.keys import Keys
import pandas as pd
import time
chrome_path =r'C:/Users/91940/AppData/Local/Programs/Python/Python39/Scripts/chromedriver.exe'
driver = webdriver.Chrome(executable_path=chrome_path)
driver.implicitly_wait(10)
driver.get("https://www.lazada.sg/products/samsung-galaxy-watch3-bt-45mm-titanium-i1156462257-
        s4537770883.html?search=1&freeshipping=1")
product_name = driver.find_element_by_xpath('//*[@id="module_product_title_1"]/div/div/h1')
print(product_name.text)
rating = driver.find_element_by_xpath("//span[@class='score-average']")
print(rate.text)
review = driver .find_element_by_xpath('//*
         [@id="module_product_review"]/div/div/div[3]/div[1]/div[1]')
print(review.text)

A: Perhaps there is a problem with your path? (apologies I'm not on windows to test). From memory, Windows paths use \ characters instead of /. Additionally, you may need two backticks after the drive path (C:\\).
c:\\Users\91940\AppData\Local\...

A: I believe print(product_name.text) is getting execute correct, right ?
There is an issue with driver.find_element_by_xpath("//span[@class='score-average']") I could not found score-average anywhere in HTML source.
so try this instead :
driver.find_element_by_css_selector("div.pdp-review-summary")
print(rate.text)

You can try the below code to get review :
wait = WebDriverWait(driver, 10)
driver.get("https://www.lazada.sg/products/samsung-galaxy-watch3-bt-45mm-titanium-i1156462257- s4537770883.html?search=1&freeshipping=1")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[class$='pdp-review-summary__link']"))).click()
ActionChains(driver).move_to_element(wait.until(EC.visibility_of_element_located((By.XPATH, "//h2[contains(text(), 'Ratings & Reviews')]")))).perform()
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.item-content")))
for review in driver.find_elements(By.CSS_SELECTOR, "div.item-content"):
    print(review.get_attribute('innerHTML'))

Imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains


text:
Q: How to fully implement server-sent events for message polling I am trying to communicate with a server using an API.
to make it easier I wrote a script that will communicate the API using a php script.
My goal is to make a query to the API every second to see if there is new message in their queue.
I was advised to use server-sent events method and have the server send a respond to the client only when it has something new.
Here is my php script
<?php

    // Register autoloader function
    spl_autoload_register('apiAutoloader');
    header("Content-Type: text/event-stream\n\n");

    $config = array('host' => 'server:IP',              //REQUIRED - Server Name
                    'port' => 8018,                     //REQUIRED - Server Port
                    'userID' => 'user',                 //REQUIRED - UserID to login with
                    'password' => '123456',             //REQUIRED - password for the UserID to login with
                    );

    try {

        //create a new instance of icws
        $icws = new API\ICWS($config);

        //create a new session
        $icws->createSession(true);

        while(1){

            $result = $icws->processMessage();
            echo json_encode($result);

            ob_flush();
            flush();
            sleep(1);

        }

    } catch(Exception $e){
        echo $e->getMessage();
    }

    function apiAutoloader($className)
    {
        $className = ltrim($className, '\\');
        $fileName  = '';
        $namespace = '';

        if ($lastNsPos = strripos($className, '\\'))
        {
            $namespace = substr($className, 0, $lastNsPos);
            $className = substr($className, $lastNsPos + 1);
            $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
        }

        $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

        $toLoad = dirname(__FILE__).'/'.$fileName;

        if (is_file($toLoad) === true)
        {
            include $toLoad;
        }
    }
?>

When a user visit my page this is the code the I run
<script>

    $(function(){

        function isset(a, b){

            if(typeof a !== "undefined" && a){
                return a
            }

            return b;
        }

        var evtSource = new EventSource("poll.php");

        evtSource.onmessage = function(e) {

            $.each(e.data.calls, function(i, item){

                $.each(item, function(z, c){

                    var interactionId = isset(c.interactionId, 0);
                    var Eic_CallDirection = isset(c.Eic_CallDirection, '');
                    var Eic_State = isset(c.Eic_State, '');
                    var AccoRDI_mid = isset(c.AccoRDI_mid, '');
                    var Eic_RemoteAddress = isset(c.Eic_RemoteAddress, '');

                    if(Eic_State == '' || Eic_CallDirection == ''){
                        return;
                    }

                    //incoming call that is not answered
                    if( Eic_CallDirection == 'I' && Eic_State == 'A'){
                        console.log('Incomming Call From ' + Eic_RemoteAddress + ' MID: ' + AccoRDI_mid );
                        return;
                    }

                    //on hold
                    if( Eic_State == 'H'){
                        console.log('Phone number ' + Eic_RemoteAddress + ' is on hold' );
                        return;
                    }

                    //voicemail
                    if( Eic_State == 'M'){
                        console.log('Phone number ' + Eic_RemoteAddress + ' is on leaving a voicemail' );
                        return;
                    }

                    //connected call
                    if(Eic_State == 'C'){
                        console.log('Live Call With ' + Eic_RemoteAddress );
                        return;
                    }

                    //Dialling call
                    if(Eic_State == 'O'){
                        console.log('Dialling ' + Eic_RemoteAddress );
                        return;
                    }

                    //Dialling call
                    if(Eic_State == 'R'){
                        console.log('Outbound call is rining and waiting for answer ' );
                        return;
                    }

                    //Call Disconnected
                    if(Eic_State == 'I' || Eic_State == 'E' ){
                        console.log('Hungup with ' + Eic_RemoteAddress );
                        return;
                    }

                });
            });
        }
    });
</script>

my code above is not working.
I don't get anything in my console. but this error Firefox can't establish a connection to the server at /icws/poll.php
How can I get it to work?
Is the way I implemented by PHP script correct?

A: What is the status code on the browser request for you event source php file ? Try to use firebug to make sure its not 404.
Also regarding php code.
According to Mozilla source you included in your question.
Proper response from server should be  named and separated by newlines
header("Content-Type: text/event-stream\n\n");
while (1) {
  echo "event: ping\n"; //event name
  echo 'data: '.json(); //event data
  Echo "\n\n"; //required

  ob_flush(); flush(); sleep(1);
 }

Event example
event: userconnect
data: {"username": "bobby", "time": "02:33:48"}

event: usermessage
data: {"username": "bobby", "time": "02:34:11", "text": "Hi everyone."}

A: To solve this issue I added a listener event like so
        var evtSource = new EventSource("poll.php");

        evtSource.addEventListener("ping", function(e) {

          var obj = JSON.parse(e.data);
          processMessages(obj);

        }, false);

and I wrote my processMessages function like so
        function processMessages(obj) {

            $.each(obj.calls, function(i, item){

                $.each(item, function(z, c){

                    var interactionId = isset(c.interactionId, 0);
                    var Eic_CallDirection = isset(c.Eic_CallDirection, '');
                    var Eic_State = isset(c.Eic_State, '');
                    var mid = isset(c.mid, '');
                    var account_id = isset(c.account_id, '');
                    var Eic_RemoteAddress = isset(c.Eic_RemoteAddress, '');

                    if(Eic_State == '' || Eic_CallDirection == ''){
                        return;
                    }

                    //incoming call that is not answered
                    if( Eic_CallDirection == 'I' && Eic_State == 'A'){
                    var msg = '';
                        if(mid != ''){
                            msg = ' MID: ' + mid;
                        }

                        if(account_id != ''){
                            msg = ' Account ID: ' + account_id;
                        }
                        console.log('Incomming Call From ' + Eic_RemoteAddress + msg );
                        return;
                    }

                    //on hold
                    if( Eic_State == 'H'){
                        console.log('Phone number ' + Eic_RemoteAddress + ' is on hold' );
                        return;
                    }

                    //voicemail
                    if( Eic_State == 'M'){
                        console.log('Phone number ' + Eic_RemoteAddress + ' is on leaving a voicemail' );
                        return;
                    }

                    //connected call
                    if(Eic_State == 'C'){
                        console.log('Live Call With ' + Eic_RemoteAddress );
                        return;
                    }

                    //Dialling call
                    if(Eic_State == 'O' && Eic_CallDirection = 'O'){
                        console.log('Dialling ' + Eic_RemoteAddress );
                        return;
                    }

                    //Dialling call
                    if(Eic_State == 'R'){
                        console.log('Outbound call is rining and waiting for answer ' );
                        return;
                    }

                    //Call Disconnected
                    if(Eic_State == 'I' || Eic_State == 'E' ){
                        console.log('Hungup with ' + Eic_RemoteAddress );
                        return;
                    }

                });
            });
        }

and my PHP code looks like this
    while(1){

        $result = array('test' => 'This is a test records');
        echo 'event: ping' . "\n";
        echo 'data: ' . json_encode($result) . "\n";
        echo "\n"; //required

        ob_flush(); flush(); sleep(1);

    }

Few things to point out in the PHP. It is IMPORTANT to have \nafter each line and one more at the very end. also it is important to look for the keyword ping which is located in my PHP code and in the listener event in my javascript code. if you change it you must change it in 2 places.
I hope this helps someone :)


text:
Q: React create issue I've started a course to learn React and I'm having
trouble in developmental setup.
In the previous course, I used browser-sync and in this course the teacher used lite-server, so I installed that. But now, on creating react app, I'm having this error and I can't understand, please help.
I'm new to the whole npm, node.js environment.
Screenshot of Error


text:
Q: Vue JS v-model not working I just starting off learning Vue JS from the documentation provided and I am using Vue CLI for the project. On using the v-model directive I'm not getting the expected output.
<template>

Add Data

        <form id="form" name="form">
            Name
            <input type="text" name="Name" id="NameInput">

            Good
            <input type="text" name="Good" id="GoodInput">

            Bad
            <input type="text" name="Bad" id="BadInput">

            Picture Link
            <input type="text" name="Picture" id="PictureInput">

        </form>

Entered Data is {{NameModel}}

</template>

The name I'm entering is not getting updated in the 'p' tag. What am I doing wrong here?

A: You simply have to remove v-model="NameModel" from the label element and add it to the input element.
Name
<input type="text" name="Name" id="NameInput" v-model="NameModel">

A: data : function() {
    return {
      msg: 'This Page is for Adding Data',
      NameModel: ''
    }
}

And v-model must be in <input>


text:
Q: Code after await doesn't work I have the next code:
  static void Main()
    {
        Program.DownloadFile();
        Console.ReadKey();
    }

    static async Task DownloadFile()
    {
        using(WebClient wc = new WebClient())
        {
            string address = "http://www.phantastike.com/link/astrology/predictive_astrology_a.zip";
            await wc.DownloadFileTaskAsync(address, "f.zip");
            // Here method returns
        }
        Console.WriteLine("This line not reached");
    }

When I start it  the program never reached to Console.WriteLine method. It returned after await.
But in the next code it works well:
 static void Main(string[] args)
    {
        Program.DownloadFile();
        Console.ReadKey();
    }

    static async Task DownloadFile()
    {
        await Task.Factory.StartNew(() => Task.Delay(2000));
        Console.WriteLine("Now you can see this message on console");
    }

Who can explain that? Thank you and sorry for my English

A: This is what probably happens: You don't wait for DownloadFile to complete, the control returns to Main, you reach Console.ReadKey, you press on a key and the program ends before it had a chance to complete the download.
When you use await Task.Factory.StartNew(() => Task.Delay(2000)); instead you're not really waiting the whole 2 seconds because Task.Factory.StartNew returns a Task<Task> so Console.WriteLine is reached immediately. You need to use Task.Run instead.
The problem is that you're not waiting for you operation to complete. Regularly you would do that with await, but that can't be used in Main so just in this case use Task.Wait:
static void Main()
{
    DownloadFile().Wait();
}

A: There's nothing wrong with await usage here. You should monitor the download progress of the file you're downloading. Add event handler for DownloadProgressChanged
 using (WebClient wc = new WebClient())
   {
     wc.DownloadProgressChanged += wc_DownloadProgressChanged;
     string address = "http://www.ayobamiadewole.com/Blog/Files/AOP.zip";
     await wc.DownloadFileTaskAsync(address, "f.zip");
   }

 static void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
   {
       Console.WriteLine("\r{0} % Completed.", e.ProgressPercentage);
   }


text:
Q: Linux Software RAID - Migrate from disk device to a partition I have two 8TB disks configured as RAID1 using mdadm on Ubuntu 18.04 server. They way I created software RAID was on the whole device - /dev/sdb and /dev/sdc - instead of the partition such as /dev/sdb1 and /dev/sdc1.
The problem is, the RAID does not assemble on reboot and the only way to get back the md devices is by recreating - running the same command used to create the RAID1 volume initially. I've read here that for the md device to assemble automatically upon reboot one needs to create RAID on partitions instead of the whole device .
I have LVM on top of the RAID1 and use it as store for VMs managed using Ganeti. I already have few VMs running and using about 2TB of the total 7.6TB capacity.
If I create a partition on these disks spanning the whole device and create RAID again as I currently do, is there hope in getting back the LVM and the partitions on it?


text:
Q: Python crashing while calculating SHA-1 hashs for large files in Windows OS I am wondering if I could have some fresh eyes on this python script.  It works fine with small and medium size files but with large ones (4-8GB or so) it inexplicable crashes after running for a couple of minutes.
Zipped script here
Or:
import sys
import msvcrt
import hashlib

#Print the file name (and its location) to be hashed
print 'File:  ' + str(sys.argv[1])

#Set "SHA1Hash" equal to SHA-1 hash
SHA1Hash = hashlib.sha1()

#Open file specified by "sys.argv[1]" in read only (r) and binary (b) mode
File = open(sys.argv[1], 'rb')

#Get the SHA-1 hash for the contents of the specified file
SHA1Hash.update(File.read())

#Close the file
File.close()

#Set "SHA1HashBase16" equal to the hexadecimal of "SHA1Hash"
SHA1HashBase16 = SHA1Hash.hexdigest()

#Print the SHA-1 (hexadecimal) hash of the file
print 'SHA-1: ' + SHA1HashBase16

#Make a blank line
print ' '

#Print "Press any key to continue..."
print 'Press any key to continue...'

#"Press any key to continue..." delay
char=0
while not char:
    char=msvcrt.getch()

* Updated *
Working python script for calculating SHA-1 hash of large files.  Thanks goes to Ignacio Vazquez-Abrams for pointing out what was wrong and Tom Zych for the code.
Zipped source here
To use simply drag and drop the file to be hashed on top of script.  Alternatively you can either use a command prompt with the usage of:
SHA-1HashGen.py Path&File

Were SHA-1HashGen.py is the file name of the script and Path&File is the path and file name of the file to be hashed.
Or drop the script in to the SendTo folder (in Windows OS; shell:sendto) to get it as a right click option.

A: Stop reading the file in one go; you're consuming all the memory on the system. Read in 16MB or so chunks instead.
data = File.read(16 * 1024 * 1024)

A: (In response to Peter's comment that 2 GB are left.)
I suspect Ignacio is right nonetheless. Try replacing the read/update line with this:
while True:
    buf = File.read(0x100000)
    if not buf:
        break
    SHA1Hash.update(buf)


text:
Q: Razor won't display value in Chrome, works most other places I have a form with several fields and am using the standard EditorFor template to edit each value. When I display in Safari and IE then the value for "Code" appears. If I show the same form in Chrome, the value for "Code" is not visible. If i do a ViewSource then I can see the correct value, just doesn't render on page. Any ideas?
public class PageViewModel
{
    public int Id { get; set; }
    public string Forename { get; set; }
    public string Surname { get; set; }

    [Display(Name = "Code")]
    [RegularExpression("^[0-9]*", ErrorMessage = "Enter digits only for the code number")]
    public string Code { get; set; }
}

And my Razor is:

    @Html.LabelFor(model => model.Code, new { @class = "control-label col-md-2" })

         @Html.EditorFor(model => model.Code)
         @Html.ValidationMessageFor(model => model.Code)

Update:
If I add the "Code" field in for a second time, then the second copy correctly shows the value. So confused:

    @Html.LabelFor(model => model.Code, new { @class = "control-label col-md-2" })

        @Html.EditorFor(model => model.Code)
        @Html.EditorFor(model => model.Code)
        @Html.ValidationMessageFor(model => model.Code)

This is the View-Source:
<input data-val="true" data-val-regex="Enter digits only for the code number" data-val-regex-pattern="^[0-9]*" id="Code" name="Code" type="text" value="22222">


text:
Q: How do I target non-immediate parent of class I have the following code:
$(".less").click(function(){
    $(".myblurb").css('height', '220');
});

In a setup like this.

Some text

A link

I have 3 or more different "myblurb" DIVs on a page and sometimes the "less" link may be nested further down inside the "myblurb" DIV.
How do I target this specific "myblurb" only?  It may or may not be an immediate parent of the "less" link.

A: Use closest() method to get the first ancestor in DOM tree.
$(".less").click(function() {
  $(this).closest(".myblurb").css('height', '220');
});

$(".less").click(function() {
  $(this).closest(".myblurb").css('height', '220');
});

Some text

A link


text:
Q: How to calculate time stamp difference in Elasticserarh +Kibana and show it in new column i n results Suppose we have two time stamps fields, can we calculate difference of time between them? For
example
[2014-04-01T18:50:41.817+0000] ~[2014-04-01T18:50:45.680Z]

A: I struggled to achieve this, but found a way.
ruby {
  code => 'event["buffer_time"] = Time.now.to_f - event["arrival_ts"].to_f'
}

The code above is no longer supported in latest versions as of today - Logstash-7.x.
We can achieve the same with event.set and event.get in ruby
and converting timestamp (datetime) using the time library
ruby {
    init => "require 'time'"
    code => '
    to_date_v   = Time.iso8601(event.get("[B-date]").to_s).to_i
    from_date_v = Time.iso8601(event.get("[A-date]").to_s).to_i

    event.set("[to_date]", to_date_v)
    event.set("[from_date]", from_date_v)

    difference_v = to_date_v - from_date_v
    event.set("[difference]", difference_v)
    '
    }

You can check sample input, output and the complete script here

A: They decided to disable server scripts in elasticsearch as a security precaution.  You can use lucene expressions, but they only work for integers (not dates).
I would compute the difference between the two dates in a ruby{} filter in logstash, so you're not at the whim of elasticsearch/kibana.
  ruby {
    code => "

      begin

        event['elapsed_time'] = ((DateTime.parse(event['date2']) - DateTime.parse(event['date1'])) * 86400).to_i

      rescue Exception => e

        event['logstash_ruby_exception'] = 'elapsed: ' + e.message

      end

    "
  }

A: I learned this from R.Clarke from elastic (version logstash 2.1.0):
ruby {
  code => 'event["buffer_time"] = Time.now.to_f - event["arrival_ts"].to_f'
}


text:
Q: Selecting multiple fields using If condition, with left join in mysql - throwing error Any help is appreciated  --
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as receiverimage, re.fName as receiverfName , re.lName as receiverlName , re.add' at line
SELECT co.*,
if(( co.senderid = 1) , ( re.image as receiverimage, re.fName as receiverfName , re.lName as receiverlName , re.address as receiverAddress , re.city as receivercity , re.state as receiverstate, re.country as receivercountry, re.zipCode as receiverzip),(se.address as senderAddress,se.city as sendercity , se.state as senderstate , se.country as sendercountry , se.zipCode as senderzip , se.image as senderimage ,se.fName as senderfName, se.lName as senderlName ))
FROM contacts as co
LEFT JOIN users as se ON( se.id = co.senderid )
LEFT JOIN users as re ON( re.id = co.receiverid )
where (senderid = 1 OR receiverid = 1)

-- is that selecting multiple fields on join table is not valid with or something else ?
I am unable to figure out the exact reason , basic prob. here is to select few fields based on if condition from user table based on join.

A: You cannot use aliases in the if statement it seems. I have just tested your query, and removing the aliases, resolves the issue.
if(( co.senderid = 1) , ( re.image, re.fName, re.lName, re.address, re.city, re.state, re.country, re.zipCode),(se.address,se.city, se.state, se.country, se.zipCode, se.image,se.fName, se.lName )) AS mydata
Edit: You should also add an alias to your entire IF so you don't get the expression as a column name :)
Edit 2: Sorry, I wrote too soon. You cannot select multiple rows like this in a select. You will have to write a subquery if you want that data or put an if for every column you need.
IF(co.senderid = 1, re.image, se.address,) as col1
IF(co.senderid = 1, re.fName, se.city) as col2
IF(co.senderid = 1, re.lName, se.state) as col3
IF(co.senderid = 1, re.address, se.country) as col4

And so on... You get the point :)


text:
Q: Add Text in ImageView on Android I'm  currently having a viewlist composed of Imageview. I'm trying to add text on each imageview of the list.
Here is the view management: A call called the ImgView method with it's context and Associated view.
public ImgView(Context c, ImageView ImageV) {
    mImageView = filteredImage;
    mImageView.setTag(this);

    mFiltersText = new TextView(c);
    mFiltersText.setText("No effect");
    mFiltersText.setVisibility(View.VISIBLE);

    mContext = c;
    mImage = new GPUImage(mContext);
    mEffect = R.id.none;
    mActivity = (Activity) mContext;
}

the mEffect is just an int used to know the type of effect I want to apply on the pic and stored in xml
<resources>
    <item type="id" name="none" />
    <item type="id" name="blackandwhite" />
    <item type="id" name="bla" />
</resources>

My goal is to find a way to get a string from the xml and display this string on the image view.
for example, when selecting "None" id, I display "No effect" on the image
I defined mFilterText but it's not displaying anything.
The View is get as shown below:
public View getView(int position, View convertView, ViewGroup parent) {
    ....
    convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item_filter, null);
    filteredImage = (ImageView) convertView.findViewById(R.id.filteredImage);
    filteredImage.setBackground(new BitmapDrawable(mFakeBitmap));
    filteredText = new TextView(mContext);

it's possible that filteredText is not correctly used. I use it as new but perhaps I need to attached it ad the FilteredImage do.
Any idea

A: Just place TextView on top of ImageView.

A: Use a Framelayout
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
    />

</FrameLayout>

You can also use the drawable property of textview
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawableLeft="@drawable/ic_clear_white_24dp"
    android:drawableRight="@drawable/ic_clear_white_24dp"
    android:drawableBottom="@drawable/ic_clear_white_24dp"
    android:drawableTop="@drawable/ic_clear_white_24dp"
/>


text:
Q: Implementing c++ Callback using Qt Signal and Slot I have created a library which has following interface and callback.
I wanted to Implent it using QT Signal and Slot.
Is is possible to replace IWifiCameraDiscovery with Signal and slot
class IWifiCameraDiscovery
{
    public:

      virtual int InitialiseWiFiDiscovery(IWifiCameraEnumerationCallback*) = 0;

      virtual void UnInitialiseWiFiDiscovery() = 0;

      virtual int   EnumerateWiFiDevice() = 0;
 };

  class IWifiCameraEnumerationCallback
  {
  public:

virtual void onWiFiDeviceDiscovered( WiFiDeviceInfo* pDeviceInfo,unsigned short nNoOfDevice) = 0;

virtual void onDiscoveryTimeout() = 0;
 };

A: Yes, in a quite straightforward way.
class IWifiCameraDiscovery
{
public:
    virtual int InitialiseWiFiDiscovery() = 0;
    virtual void UnInitialiseWiFiDiscovery() = 0;
    virtual int EnumerateWiFiDevice() = 0;

signals:
    void onWiFiDeviceDiscovered(WiFiDeviceInfo* pDeviceInfo, unsigned short nNoOfDevice);
    void onDiscoveryTimeout();
};

In your implementation, instead of calling the callbacks directly:
callback.onWiFiDeviceDiscovered(pDevInfo, x);

You would emit a signal:
emit onWiFiDeviceDiscovered(pDevInfo, x);

And you would use QObject::connect to connect these signals to your actual receivers (slots) on the other end. Be aware that emitting a signal is more expensive than calling a virtual function.

A: try this simple example
#include <QApplication>
#include <QFont>
#include <QPushButton>
#include <QWidget>

class MyWidget : public QWidget
{
public:
    MyWidget(QWidget *parent = 0);
};

MyWidget::MyWidget(QWidget *parent)
    : QWidget(parent)
{
    setFixedSize(200, 120);

    QPushButton *quit = new QPushButton(tr("Quit"), this);
    quit->setGeometry(62, 40, 75, 30);
    quit->setFont(QFont("Times", 18, QFont::Bold));

    connect(quit, SIGNAL(clicked()), qApp, SLOT(quit()));
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MyWidget widget;
    widget.show();
    return app.exec();
}

you can use like this
class IWifiCameraDiscovery
{
 public slots:
    void UnInitialiseWiFiDiscovery();

 signals:
    void EnumerateWiFiDevice();
}


text:
Q: Windows Server 2008 R2 backup includes volume with MSSQL data I'm using wbadmin to schedule image backup every night on a Windows Server 2008 R2 Standard server.
Ever since installing MS-SQL 2008 Express R2, wbadmin wants to also backup the volume where the MS-SQL data files are located (L:).
I'm using -allCritical to make sure bare metal restore will work.
command-line:
wbadmin start backup -backupTarget:\\myserver\backup$\myserver\%DATE% -include:C: -allCritical -quiet

I don't want to do this, because I'm backing up MS-SQL manually elsewhere. It worked just fine only taking C: before I installed MS-SQL.

A: You will need to tell the backup that the SQL files can't be backed up as trying to restore from the files that it backs up can't be used to restore.
Instead of running wbadmin start backup use wbadmin enable backup to schedule the backup. This gives you the option of using the -exclude parameter (you can try using this with start backup but I don't think it'll work).