text:
Q: Selecting first and last scores from a list of appointments I have a database of appointments, each with a personid, sequence number, appointment date and two questionnaire scores.
What I need to do is bring back one line per personid, showing their first appointment with scores, and their last appointment with scores, along with the scores themselves for both.
Having spent a long time already on what is probably a very simple query, I've tried to use the following to just give me the first appointment with scores:
SELECT
PERSONID,
MIN(CONTACTDATE) AS 'FIRST_CONTACT',
QUEST_1,
QUEST_2

FROM TBL_APPOINTMENTS

GROUP BY
PERSONID,
CONTACTDATE,
QUEST_1,
QUEST_2

ORDER BY
PERSONID,
FIRST_CONTACT

As you can probably guess, this is giving me duplicate rows every time the values in QUEST_1 or QUEST_2 change.
Can anyone help please? I'm sure this is all very simple but it's driving me up the wall!
Thanks in advance!

A: Using ROW_NUMBER() you can assign appointments a sequential value starting from 1 on a per PERSONID basis.
In the example below I create two such ordinals, one forward in time, and one reverse in time.  then I can pick the first going forward as well as the first going backwards.
WITH
  sorted AS
(
  SELECT
    PERSONID,
    CONTACTDATE,
    QUEST_1,
    QUEST_2,
    ROW_NUMBER() OVER (PARTITION BY PERSONID ORDER BY CONTACTDATE  ASC)   AS ORD_FWD,
    ROW_NUMBER() OVER (PARTITION BY PERSONID ORDER BY CONTACTDATE DESC)   AS ORD_REV
  FROM
    TBL_APPOINTMENTS
)
SELECT
  PERSONID,
  CONTACTDATE,
  QUEST_1,
  QUEST_2
FROM
  sorted
WHERE
  ORD_FWD = 1 OR ORD_REV = 1
ORDER BY
  PERSONID,
  CONTACTDATE

EDIT With both first and last aggregated in to one row...
WITH
  sorted AS
(
  SELECT
    PERSONID,
    CONTACTDATE,
    QUEST_1,
    QUEST_2,
    ROW_NUMBER() OVER (PARTITION BY PERSONID ORDER BY CONTACTDATE  ASC)   AS ORD_FWD,
    ROW_NUMBER() OVER (PARTITION BY PERSONID ORDER BY CONTACTDATE DESC)   AS ORD_REV
  FROM
    TBL_APPOINTMENTS
)
SELECT
  PERSONID,
  MAX(CASE WHEN ORD_FWD = 1 THEN CONTACTDATE END)   AS FIRST_CONTACTDATE,
  MAX(CASE WHEN ORD_FWD = 1 THEN QUEST_1     END)   AS FIRST_QUEST_1,
  MAX(CASE WHEN ORD_FWD = 1 THEN QUEST_2     END)   AS FIRST_QUEST_2,
  MAX(CASE WHEN ORD_REV = 1 THEN CONTACTDATE END)   AS FINAL_CONTACTDATE,
  MAX(CASE WHEN ORD_REV = 1 THEN QUEST_1     END)   AS FINAL_QUEST_1,
  MAX(CASE WHEN ORD_REV = 1 THEN QUEST_2     END)   AS FINAL_QUEST_2
FROM
  sorted
WHERE
  ORD_FWD = 1 OR ORD_REV = 1
GROUP BY
  PERSONID
ORDER BY
  PERSONID

NOTE: It is possible that the first and last appointment are the same appointment (if the person only had one appointment).

A: If the result you're looking for is something like this:
PERSONID    FIRST_CONTACT FIRST_QUEST_1 FIRST_QUEST_2 LAST_CONTACT LAST_QUEST_1 LAST_QUEST_2
----------- ------------- ------------- ------------- ------------ ------------ ------------
1           2015-01-01    10            11            2015-01-21   21           211
2           2015-01-01    11            24            2015-01-31   12           25
3           2015-02-01    13            21            2015-03-01   14           28
4           2015-03-01    15            29            2015-04-01   16           21

then the query below would give you that. Note that the max and min dates and scores would be the same if there is only one record for a person.
SELECT
    PERSONID,
    FIRST_CONTACT, FIRST_QUEST_1, FIRST_QUEST_2,
    LAST_CONTACT, LAST_QUEST_1, LAST_QUEST_2
FROM (
    SELECT PERSONID, MIN(CONTACTDATE) AS 'FIRST_CONTACT', MAX(CONTACTDATE) AS 'LAST_CONTACT'
    FROM TBL_APPOINTMENTS a
    GROUP BY PERSONID
) a
CROSS APPLY (
    SELECT QUEST_1 AS 'FIRST_QUEST_1', QUEST_2  AS 'FIRST_QUEST_2'
    FROM TBL_APPOINTMENTS
    WHERE PERSONID = a.PERSONID AND CONTACTDATE = A.FIRST_CONTACT
) o_first
CROSS APPLY (
    SELECT QUEST_1 AS 'LAST_QUEST_1', QUEST_2  AS 'LAST_QUEST_2'
    FROM TBL_APPOINTMENTS
    WHERE PERSONID = a.PERSONID AND CONTACTDATE = A.LAST_CONTACT
) o_last
ORDER BY PERSONID, FIRST_CONTACT;

The same query could be written using joins:
SELECT
    A.PERSONID,
    FIRST_CONTACT,
    F.QUEST_1 AS FIRST_QUEST_1,
    F.QUEST_2 AS FIRST_QUEST_2,
    LAST_CONTACT,
    L.QUEST_1 AS LAST_QUEST_1,
    L.QUEST_2 AS LAST_QUEST_2
FROM (
    SELECT PERSONID, MIN(CONTACTDATE) AS 'FIRST_CONTACT', MAX(CONTACTDATE) AS 'LAST_CONTACT'
    FROM TBL_APPOINTMENTS a
    GROUP BY PERSONID
) a
JOIN TBL_APPOINTMENTS F ON F.PERSONID = a.PERSONID AND A.FIRST_CONTACT = F.CONTACTDATE
JOIN TBL_APPOINTMENTS L ON L.PERSONID = a.PERSONID AND A.LAST_CONTACT = L.CONTACTDATE
ORDER BY A.PERSONID, FIRST_CONTACT;

A:     SELECT PERSONID,
    MIN(CONTACTDATE) AS 'FIRST_CONTACT', MAX(CONTACTDATE) AS 'LAST_CONTACT'
    QUEST_1,
    QUEST_2
    FROM TBL_APPOINTMENTS
    GROUP BY PERSONID,
CONTACTDATE,
QUEST_1,
QUEST_2
 ORDER BY
    PERSONID,
    FIRST_CONTACT


text:
Q: Device logs for bluetooth on iOS I am currently developing an iPhone app that pairs with a bluetooth device.
We are having some latency issues regarding this pairing, and detecting at the correct time when our device is paired/connected.
Do you guys know if the iPhone has some log information we can look at/extract for bluetooth devices?

A: Try generating a Bluetooth diagnostic log, that's the most info you will get (without jail breaking).
If you need more info, a Bluetooth sniffer/protocol analyzer may be needed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Caroufredsel slider - keep variable width image in center of scroller I have a series of variable width images.  I want to rotate them in a carousel and have chosen 'carouFredSel' as it seems to be the most configurable one I can find.  I want one of the images to be centered horizontally in the browser always.  So with the traditional carousel images would be left-aligned by default, but here I want them to align around the image in the middle of the view, with consistent (10px) gaps between the images.  Here's an example: http://coolcarousels.frebsite.nl/c/2/.  This is great for fixed width images, but my images are variable in width.  This variable width is the issue.
I've done a quick mock-up to highlight this.  The code is as follows:
HTML:

CSS:
.strip {
    height: 210px;
    background: #333;
    overflow: hidden;
}
.carousel-image {
    float:  left;
    width: 410px;
    height: 306px;
    text-align: center;
}
.carousel-image img {
    float: left;
    margin: 5px;
}

JS:
$(function () {

    $('#carousel').carouFredSel({
        width: '100%',
        align: 'center',
        items: {
            visible: 3,
            start: -1
        },
        scroll: {
            items: 1,
            duration: 1000,
            timeoutDuration: 3000
        },
        prev: '#prev',
        next: '#next',
        pagination: {
            container: '#pager',
            deviation: 1
        }
    });

});

Fiddle: http://jsfiddle.net/qqBus/
You'll see if you remove the '.carousel-image' width it has the desired effect in making the images sit next to each other without gaps, but it also stops the middle image from being centered.
I wondered if anyone could figure out a way to achieve the effect I'm looking for?  I'm open to an alternative plug-in if such a thing exists, but having looked long and hard I can't find one that works with variable width images!
Thanks folks.

A: Check this link http://samanthaswade.com/editorial.html
This is the slider plugin http://jquery.lemmonjuice.com/plugins/slider-variable-widths.php without centered images
And here is the centered image solution enter link description here
$( function() {
// slider 1
    $( '#yourslider' ).lemmonSlider( {
        infinite: true
    });
});


text:
Q: Powershell cmd /c with 2 pairs of quotes works on Win 7 but not Win 10 When I run this Powershell command, it works on my Windows 7 PC, but not on my Windows 10 PC, why is that?
cmd /c "`"`"C:\Program Files (x86)\National Instruments\LabVIEW 2018\LabVIEW.exe`"`""

The error is
'""C:\Program' is not recognized as an internal or external command, operable program or batch file.

The command
cmd /c "`"C:\Program Files (x86)\National Instruments\LabVIEW 2018\LabVIEW.exe`""

works on both but I have to add another pair of quotes because my command actually contains paths:
cmd /c "`"`"C:\Program Files (x86)\National Instruments\LabVIEW 2018\LabVIEW.exe`" `"$runner_File`" > `"$runnerResult_File`"`""

A: Avoid the quoting headaches:

*

*by letting PowerShell handle the invocation of your console application directly

*and by emulating cmd.exe's > redirection with Set-Content -Encoding Oem:

& "C:\Program Files (x86)\National Instruments\LabVIEW 2018\LabVIEW.exe" $runner_File |
  Set-Content -Encoding Oem $runnerResult_File

Read on for an explanation.
See the bottom section if you do want to solve the original problem with cmd /c.

*

*There is generally no need to use cmd /c to invoke console applications from PowerShell.

*

*Piping to Set-Content -Encoding Oem can be used to emulate cmd.exe's > output redirection, though note that this may slow things down.

*

*On the plus side, Set-Content allows you to control the output encoding.

*To control what character encoding PowerShell assumes the console application's output uses, set [Console]::OutputEncoding before invoking the application.

*While you could use PowerShell's own >, it would create UTF-16LE files by default in Windows PowerShell (and BOM-less UTF-8 files in PowerShell Core) - though in PSv5.1+ you can change the encoding that > uses via the $PSDefaultParameterValues dictionary of presets.

*To invoke a console application whose path needs quoting or is provided via a variable, use &, the call operator.

*If you provide arguments via variables (e.g., $runnerFile), PowerShell will take care of quoting the variable values for you, behind the scenes, if needed.

Solving the problem with cmd /c:
Bizarrely, passing a command line to cmd /c that contains multiple "..."-enclosed arguments additionally requires enclosing the entire command line in "...".
Here's how to achieve that from PowerShell, by:

*

*placing individually escaped " instances (`") on both ends of the command line passed to cmd /c, which become the overall enclosing "...".

*otherwise relying on PowerShell's own behind-the-scenes on-demand quoting of variable values.
cmd /c `" "C:\Program Files (x86)\National Instruments\LabVIEW 2018\LabVIEW.exe" $runner_File > $runnerResult_File `"


text:
Q: Input data validation in CakePHP REST API I am developing a REST API using CakePHP. The problem is regarding the validation of data that is sent as input parameters to my API. In the CakePHP documentation they have mentioned this. But how do I implement it for a REST API?
I want that if I add a validation something like this in app/Model/Table.php:
public $validate = array(
    'email' => 'email'
);

Then when I user makes the request myapi.com/resource?email=abc123 I want the API to respond like
status: 400
{
    "message": "Invalid Parameter",
    "url": "/resource"
}

A: Based on the documentation, in the controller you can use:
$this->Model->set($this->request->data);

if (!$this->Model->validates()) {
    $this->response->statusCode(400);
    $this->set('_serialize', array(
       'message' => 'Invalid Parameter',
       'url' => '/resource',
    ));
}


text:
Q: Run adb logcat in the background without WiFi and USB I have an application that uses both the USB and WiFi interface. I am currently debugging an issue where I have to use both the phone's USB and WiFi, and it switches between WiFi networks. This renders both USB and WiFi debugging useless.
Is there a way I could start adb logcat to run as a background process, do everything that my app requires with USB and WiFi, and then stop the process I started and read the logs in a file?

A: Increase the Logcat buffer size to 16MB. That gives plenty of time to do whatever you want while the wire is disconnected. You can do this by going to Developer Options -> Log Buffer Sizes.
This works better than the old answer as the formatting of the logs don't depend on the app used for this purpose.

Old answer:
I used a logcat app from the Play Store which worked -- it started a foreground service capturing the logs from logcat while my phone was disconnected from my laptop. This was also helpful because I could see these logs in real time by switching to the app.
The particular app I used was LogcatReader, but ideally any should do.


text:
Q: CTE slow performance on Left join I need to provide a report that shows all users on a table and their scores. Not all users on said table will have a score, so in my solution I calculate the score first using a few CTE's then in a final CTE i pull a full roster and assign a default score to users with no actual score.
While the CTE's are not overly complex, they are also not simple. Separately when I run the calculation part of the CTE's for users with an actual score, it runs in less than a second. When I join to a final CTE that grabs the full roster and assigns default scores where the nulls appear (no actual score) the wheels completely fall off and it never completes.
I've experimented with switching up the indexes and refreshing them to no avail. I have noticed the join at agent_effectiveness when switched to INNER runs in one second, but I need it to be a LEFT join so it will pull in the whole roster even when no score is present.
EDIT*
Execution Plan Inner Join
Execution Plan Left Join
WITH agent_split_stats AS (
Select
    racf,
    agent_stats.SkillGroupSkillTargetID,
    aht_target.EnterpriseName,
    aht_target.target,
    Sum(agent_stats.CallsHandled) as n_calls_handled,
    CASE WHEN (Sum(agent_stats.TalkInTime) + Sum(agent_stats.IncomingCallsOnHoldTime) + Sum(agent_stats.WorkReadyTime)) = 0 THEN 1 ELSE
        (Sum(agent_stats.TalkInTime) + Sum(agent_stats.IncomingCallsOnHoldTime) + Sum(agent_stats.WorkReadyTime)) END
    AS total_handle_time
from tblAceyusAgntSklGrp as agent_stats
-- GET TARGETS
INNER JOIN tblCrosswalkWghtPhnEffTarget as aht_target
  ON aht_target.SgId = agent_stats.SkillGroupSkillTargetID
  AND agent_stats.DateTime BETWEEN aht_target.StartDt and aht_target.EndDt
-- GET RACF
INNER JOIN tblAgentMetricCrosswalk as xwalk
  ON xwalk.SkillTargetID = agent_stats.SkillTargetID
--GET TAU DATA LIKE START DATE AND GRADUATED FLAG
INNER JOIN tblTauClassList AS T
  ON T.SaRacf = racf
WHERE
--FILTERS BY A ROLLING 15 BUSINESS DAYS UNLESS THE DAYS BETWEEN CURRENT DATE AND TAU START DATE ARE <15
agent_stats.DateTime >=
    CASE WHEN dbo.fn_WorkDaysAge(TauStart, GETDATE()) <15 THEN TauStart ELSE
        dbo.fn_WorkDate15(TauStart)
    END
And Graduated = 'No'
--WPE FILTERS TO ENSURE ACCURATE DATA
AND CallsHandled <> 0
AND Target is not null
Group By
racf, agent_stats.SkillGroupSkillTargetID, aht_target.EnterpriseName, aht_target.target
),
agent_split_stats_with_weight AS (
-- calculate weights
-- one row = one advocate + split
SELECT
    agent_split_stats.*,
    agent_split_stats.n_calls_handled/SUM(agent_split_stats.n_calls_handled) OVER(PARTITION BY agent_split_stats.racf) AS [weight]
FROM agent_split_stats
),
agent_split_effectiveness AS (
-- calculate the raw Effectiveness score for each eligible advocate/split
-- one row = one agent + split, with their raw Effectiveness score and the components of that
SELECT
    agent_split_stats_with_weight.*,
    -- these are the components of the Effectiveness score
    (((agent_split_stats_with_weight.target * agent_split_stats_with_weight.n_calls_handled) / agent_split_stats_with_weight.total_handle_time)*100)*agent_split_stats_with_weight.weight AS effectiveness_sum
FROM agent_split_stats_with_weight
), -- this is where we show effectiveness per split  select * from agent_split_effectiveness
agent_effectiveness AS (
-- sum all of the individual effectiveness raw scores for each agent to get each agent's raw score
SELECT
    racf AS SaRacf,
    ROUND(SUM(effectiveness_sum),2) AS WpeScore
FROM agent_split_effectiveness
GROUP BY racf
),
--GET FULL CLASS LIST, TAU DATES, GOALS FOR WHOLE CLASS
tau AS (
Select L.SaRacf, TauStart, Goal as WpeGoal
,CASE WHEN agent_effectiveness.WpeScore IS NULL THEN 1 ELSE WpeScore END as WpeScore
FROM tblTauClassList AS L
LEFT JOIN agent_effectiveness
  ON agent_effectiveness.SaRacf = L.SaRacf
LEFT JOIN tblCrosswalkTauGoal AS G
  ON G.Year = TauYear
  AND G.Bucket = 'Wpe'
WHERE TermDate IS NULL
AND Graduated = 'No'
)
SELECT tau.*,
CASE WHEN dbo.fn_WorkDaysAge(TauStart, GETDATE()) > 14 --MUST BE AT LEAST 15 DAYS TO PASS
        AND WpeScore >= WpeGoal THEN 'Pass'
    ELSE 'Fail' END
from tau

This style of query runs fine in 3 other different calculation types (different score types). So i am unsure why its failing so badly here. Actual results should be a list of individuals, a date, a score, a goal  and a score. When no score exists, a default score is provided. Additionally there is a pass/fail metric using the score/goal.

A: As @Habo mentioned, we need the actual execution plan (e.g. run the query with "include actual execution plan" turned on.) I looked over what you posted and there is nothing there that will explain the problem. The difference with the actual plan vs the estimated plan is that the actual number of rows retrieved are recorded; this is vital for troubleshooting poorly performing queries.
That said, I do see a HUGE problem with both queries. It's a problem that, once fixed will, improve both queries to less than a second. Your query is leveraging two scalar user Defined Functions (UDFs): dbo.fn_WorkDaysAge & dbo.fn_WorkDate15. Scalar UDFs ruin
everything. Not only are they slow, they force a serial execution plan which makes any query they are used in much slower.
I don't have the code for dbo.fn_WorkDaysAge or dbo.fn_WorkDate15 I have my own "WorkDays" function which is inline (code below). The syntax is a little different but the performance benefits are worth the effort. Here's the syntax difference:
-- Scalar
SELECT d.*, workDays = dbo.countWorkDays_scalar(d.StartDate,d.EndDate)
FROM   <sometable> AS d;

-- Inline version
SELECT d.*, f.workDays
FROM   <sometable> AS d
CROSS APPLY dbo.countWorkDays(d.StartDate,d.EndDate) AS f;

Here's a performance test I put together to show the difference between an inline version vs the scalar version:
-- SAMPLE DATA
IF OBJECT_ID('tempdb..#dates') IS NOT NULL DROP TABLE #dates;

WITH E1(x)  AS (SELECT 1 FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS x(x)),
     E3(x)  AS (SELECT 1 FROM E1 a, E1 b, E1 c),
     iTally AS (SELECT N=ROW_NUMBER() OVER (ORDER BY (SELECT 1)) FROM E3 a, E3 b)
SELECT TOP (100000)
  StartDate = CAST(DATEADD(DAY,-ABS(CHECKSUM(NEWID())%1000),GETDATE()) AS DATE),
  EndDate   = CAST(DATEADD(DAY,+ABS(CHECKSUM(NEWID())%1000),GETDATE()) AS DATE)
INTO #dates
FROM iTally;

-- PERFORMANCE TESTS
PRINT CHAR(10)+'Scalar Version (always serial):'+CHAR(10)+REPLICATE('-',60);
GO
DECLARE @st DATETIME = GETDATE(), @workdays INT;
  SELECT @workdays = dbo.countWorkDays_scalar(d.StartDate,d.EndDate)
  FROM   #dates AS d;
PRINT DATEDIFF(MS,@st,GETDATE());
GO 3

PRINT CHAR(10)+'Inline Version:'+CHAR(10)+REPLICATE('-',60);
GO
DECLARE @st DATETIME = GETDATE(), @workdays INT;
  SELECT @workdays = f.workDays
  FROM   #dates AS d
  CROSS APPLY dbo.countWorkDays(d.StartDate,d.EndDate) AS f
PRINT DATEDIFF(MS,@st,GETDATE());
GO 3

Results:
Scalar Version (always serial):
------------------------------------------------------------
Beginning execution loop
380
363
350
Batch execution completed 3 times.

Inline Version:
------------------------------------------------------------
Beginning execution loop
47
47
46
Batch execution completed 3 times.

As you can see - the inline version about 8 times faster than the scalar version. Replacing those scalar UDFs with an inline version will almost certainly speed this query up regardless of join type.
Other problems I see include:

*

*I see a lot of Index scans, this is a sign you need more filtering and/or better indexes.

*dbo.tblCrosswalkWghtPhnEffTarget does not have any indexes which means it will always get scanned.
Functions used for performance test:
-- INLINE VERSION
----------------------------------------------------------------------------------------------
IF OBJECT_ID('dbo.countWorkDays') IS NOT NULL DROP FUNCTION dbo.countWorkDays;
GO
CREATE FUNCTION dbo.countWorkDays (@startDate DATETIME, @endDate DATETIME)
/*****************************************************************************************
[Purpose]:
 Calculates the number of business days between two dates (Mon-Fri) and excluded weekends.
 dates.countWorkDays does not take holidays into considerations; for this you would need a
 seperate "holiday table" to perform an antijoin against.

 The idea is based on the solution in this article:
   https://www.sqlservercentral.com/Forums/Topic153606.aspx?PageIndex=16

[Author]:
 Alan Burstein

[Compatibility]:
 SQL Server 2005+

[Syntax]:
--===== Autonomous
 SELECT f.workDays
 FROM   dates.countWorkDays(@startdate, @enddate) AS f;

--===== Against a table using APPLY
 SELECT t.col1, t.col2, f.workDays
 FROM dbo.someTable t
 CROSS APPLY dates.countWorkDays(t.col1, t.col2) AS f;

[Parameters]:
  @startDate = datetime; first date to compare
  @endDate   = datetime; date to compare @startDate to

[Returns]:
 Inline Table Valued Function returns:
 workDays = int; number of work days between @startdate and @enddate

[Dependencies]:
 N/A

[Developer Notes]:
 1. NULL when either input parameter is NULL,

 2. This function is what is referred to as an "inline" scalar UDF." Technically it's an
    inline table valued function (iTVF) but performs the same task as a scalar valued user
    defined function (UDF); the difference is that it requires the APPLY table operator
    to accept column values as a parameter. For more about "inline" scalar UDFs see this
    article by SQL MVP Jeff Moden: http://www.sqlservercentral.com/articles/T-SQL/91724/
    and for more about how to use APPLY see the this article by SQL MVP Paul White:
    http://www.sqlservercentral.com/articles/APPLY/69953/.

    Note the above syntax example and usage examples below to better understand how to
    use the function. Although the function is slightly more complicated to use than a
    scalar UDF it will yield notably better performance for many reasons. For example,
    unlike a scalar UDFs or multi-line table valued functions, the inline scalar UDF does
    not restrict the query optimizer's ability generate a parallel query execution plan.

 3. dates.countWorkDays requires that @enddate be equal to or later than @startDate. Otherwise
    a NULL is returned.

 4. dates.countWorkDays is NOT deterministic. For more deterministic functions see:
    https://msdn.microsoft.com/en-us/library/ms178091.aspx

[Examples]:
 --===== 1. Basic Use
 SELECT f.workDays
 FROM   dates.countWorkDays('20180608', '20180611') AS f;

---------------------------------------------------------------------------------------
[Revision History]:
 Rev 00 - 20180625 - Initial Creation - Alan Burstein
*****************************************************************************************/
RETURNS TABLE WITH SCHEMABINDING AS RETURN
SELECT workDays =
    -- If @startDate or @endDate are NULL then rerturn a NULL
  CASE WHEN SIGN(DATEDIFF(dd, @startDate, @endDate)) > -1 THEN
                (DATEDIFF(dd, @startDate, @endDate) + 1) --total days including weekends
               -(DATEDIFF(wk, @startDate, @endDate) * 2) --Subtact 2 days for each full weekend
    -- Subtract 1 when startDate is Sunday and Substract 1 when endDate is Sunday:
    -(CASE WHEN DATENAME(dw, @startDate) = 'Sunday'   THEN 1 ELSE 0 END)
    -(CASE WHEN DATENAME(dw, @endDate)   = 'Saturday' THEN 1 ELSE 0 END)
  END;
GO

-- SCALAR VERSION
----------------------------------------------------------------------------------------------
IF OBJECT_ID('dbo.countWorkDays_scalar') IS NOT NULL DROP FUNCTION dbo.countWorkDays_scalar;
GO
CREATE FUNCTION dbo.countWorkDays_scalar (@startDate DATETIME, @endDate DATETIME)
RETURNS INT WITH SCHEMABINDING AS
BEGIN
  RETURN
  (
    SELECT workDays =
        -- If @startDate or @endDate are NULL then rerturn a NULL
      CASE WHEN SIGN(DATEDIFF(dd, @startDate, @endDate)) > -1 THEN
                    (DATEDIFF(dd, @startDate, @endDate) + 1) --total days including weekends
                   -(DATEDIFF(wk, @startDate, @endDate) * 2) --Subtact 2 days for each full weekend
        -- Subtract 1 when startDate is Sunday and Substract 1 when endDate is Sunday:
        -(CASE WHEN DATENAME(dw, @startDate) = 'Sunday'   THEN 1 ELSE 0 END)
        -(CASE WHEN DATENAME(dw, @endDate)   = 'Saturday' THEN 1 ELSE 0 END)
      END
  );
END
GO

UPDATE BASED ON OP'S QUESTION IN THE COMMENTS:
First for the inline table valued function version of each function. Note that I'm using my own tables and don't have time to make the names match your environment but I did my best to include comments in the code. Also note that if, in your function, workingday = '1' is simply pulling weekdays then you'll find my function above to be a much faster alternative to your dbo.fn_WorkDaysAge function. If workingday = '1' also filters out holidays then it won't work.
CREATE FUNCTION dbo.fn_WorkDaysAge_itvf
(
 @first_date  DATETIME,
 @second_date DATETIME
)
RETURNS TABLE AS RETURN
SELECT  WorkDays = COUNT(*)
FROM    dbo.dimdate -- DateDimension
WHERE   DateValue   -- [date]
BETWEEN @first_date AND @second_date
AND     IsWeekend = 0 --workingday = '1'
GO

CREATE FUNCTION dbo.fn_WorkDate15_itvf
(
 @TauStartDate DATETIME
)
RETURNS TABLE AS RETURN
WITH DATES AS
(
  SELECT
  ROW_NUMBER() OVER(Order By DateValue Desc) as RowNum, DateValue
  FROM dbo.dimdate -- DateDimension
  WHERE DateValue BETWEEN @TauStartDate AND --GETDATE() testing below
   CASE WHEN GETDATE() < @TauStartDate + 200 THEN GETDATE() ELSE @TauStartDate + 200 END
  AND IsWeekend = 0 --workingday = '1'
)
--Get the 15th businessday from the current date
SELECT DateValue
FROM  DATES
WHERE RowNum = 16;
GO

Now, to replace your scalar UDFs with the inline table valued functions, you would do this (note my comments):
WITH agent_split_stats AS (
Select
    racf,
    agent_stats.SkillGroupSkillTargetID,
    aht_target.EnterpriseName,
    aht_target.target,
    Sum(agent_stats.CallsHandled) as n_calls_handled,
    CASE WHEN (Sum(agent_stats.TalkInTime) + Sum(agent_stats.IncomingCallsOnHoldTime) + Sum(agent_stats.WorkReadyTime)) = 0 THEN 1 ELSE
        (Sum(agent_stats.TalkInTime) + Sum(agent_stats.IncomingCallsOnHoldTime) + Sum(agent_stats.WorkReadyTime)) END
    AS total_handle_time
from tblAceyusAgntSklGrp as agent_stats
INNER JOIN tblCrosswalkWghtPhnEffTarget as aht_target
  ON aht_target.SgId = agent_stats.SkillGroupSkillTargetID
  AND agent_stats.DateTime BETWEEN aht_target.StartDt and aht_target.EndDt
INNER JOIN tblAgentMetricCrosswalk as xwalk
  ON xwalk.SkillTargetID = agent_stats.SkillTargetID
INNER JOIN tblTauClassList AS T
  ON T.SaRacf = racf
-- INLINE FUNCTIONS HERE:
CROSS APPLY dbo.fn_WorkDaysAge_itvf(TauStart, GETDATE()) AS wd
CROSS APPLY dbo.fn_WorkDate15_itvf(TauStart)             AS w15
-- NEW WHERE CLAUSE:
WHERE       agent_stats.DateTime >=
              CASE WHEN wd.workdays < 15 THEN TauStart ELSE w15.workdays END
And Graduated = 'No'
AND CallsHandled <> 0
AND Target is not null
Group By
racf, agent_stats.SkillGroupSkillTargetID, aht_target.EnterpriseName, aht_target.target
),
agent_split_stats_with_weight AS (
SELECT
    agent_split_stats.*,
    agent_split_stats.n_calls_handled/SUM(agent_split_stats.n_calls_handled) OVER(PARTITION BY agent_split_stats.racf) AS [weight]
FROM agent_split_stats
),
agent_split_effectiveness AS
(
  SELECT
      agent_split_stats_with_weight.*,
      (((agent_split_stats_with_weight.target * agent_split_stats_with_weight.n_calls_handled) /
         agent_split_stats_with_weight.total_handle_time)*100)*
         agent_split_stats_with_weight.weight AS effectiveness_sum
  FROM agent_split_stats_with_weight
),
agent_effectiveness AS
(
  SELECT
      racf AS SaRacf,
      ROUND(SUM(effectiveness_sum),2) AS WpeScore
  FROM agent_split_effectiveness
  GROUP BY racf
),
tau AS
(
  SELECT L.SaRacf, TauStart, Goal as WpeGoal
  ,CASE WHEN agent_effectiveness.WpeScore IS NULL THEN 1 ELSE WpeScore END as WpeScore
  FROM tblTauClassList AS L
  LEFT JOIN agent_effectiveness
    ON agent_effectiveness.SaRacf = L.SaRacf
  LEFT JOIN tblCrosswalkTauGoal AS G
    ON  G.Year   = TauYear
    AND G.Bucket = 'Wpe'
  WHERE TermDate IS NULL
  AND   Graduated = 'No'
)
SELECT tau.*,
-- NEW CASE STATEMENT HERE:
CASE WHEN wd.workdays > 14 AND WpeScore >= WpeGoal THEN 'Pass' ELSE 'Fail' END
from tau
-- INLINE FUNCTIONS HERE:
CROSS APPLY dbo.fn_WorkDaysAge_itvf(TauStart, GETDATE()) AS wd
CROSS APPLY dbo.fn_WorkDate15_itvf(TauStart)             AS w15;

Note that I can't test this right now but it should be correct (or close)

A: UPDATE
I accepted Alan's answer, i ended up doing the following. Posting examples hoping the formatting helps someone, it slowed me down a bit...or maybe I am just slow heh heh.
1. Changed my Scalar UDF to InlineTVF
SCALAR Function 1-
    ALTER FUNCTION [dbo].[fn_WorkDaysAge]
(
    -- Add the parameters for the function here
    @first_date DATETIME,
    @second_date DATETIME
)
RETURNS int
AS
BEGIN
    -- Declare the return variable here
    DECLARE @WorkDays int

    -- Add the T-SQL statements to compute the return value here
SELECT @WorkDays = COUNT(*)
FROM DateDimension
WHERE Date BETWEEN @first_date AND @second_date
AND workingday = '1'

    -- Return the result of the function
    RETURN @WorkDays

END

iTVF function 1-
    ALTER FUNCTION [dbo].[fn_iTVF_WorkDaysAge]
(
    -- Add the parameters for the function here
 @FirstDate as Date,
 @SecondDate as Date
)
RETURNS TABLE  AS RETURN

SELECT WorkDays = COUNT(*)
FROM DateDimension
WHERE Date BETWEEN @FirstDate AND @SecondDate
AND workingday = '1'

I then updated my next function the same way. I added the CROSS APPLY (something ive personally not used, im still a newbie) as indicated below and replaced the UDFs with the field names in my case statement.
Old Code
INNER JOIN tblTauClassList AS T
  ON T.SaRacf = racf
WHERE
--FILTERS BY A ROLLING 15 BUSINESS DAYS UNLESS THE DAYS BETWEEN CURRENT DATE AND TAU START DATE ARE <15
agent_stats.DateTime >=
    CASE WHEN dbo.fn_WorkDaysAge(TauStart, GETDATE()) <15 THEN TauStart ELSE
        dbo.fn_WorkDate15(TauStart)
    END

New Code
INNER JOIN tblTauClassList AS T
  ON T.SaRacf = racf
--iTVFs
CROSS APPLY dbo.fn_iTVF_WorkDaysAge(TauStart, GETDATE()) as age
CROSS APPLY dbo.fn_iTVF_WorkDate_15(TauStart) as roll
WHERE
--FILTERS BY A ROLLING 15 BUSINESS DAYS UNLESS THE DAYS BETWEEN CURRENT DATE AND TAU START DATE ARE <15
agent_stats.DateTime >=
    CASE WHEN age.WorkDays <15 THEN TauStart ELSE
        roll.Date
    END

New code runs in 3-4 seconds. I will go back and index the appropriate tables per your recommendation and probably gain more efficiency there.
Cannot thank you enough!


text:
Q: Proof verification - Cauchy completeness of $\mathbb{R}$ Let $(x_n)$ be a Cauchy sequence in $\mathbb{R}$. We want to show that $(x_n)$ converges in $\mathbb{R}$. I'm presenting my proof below. I've used standard $\epsilon-N$ technique, triangle inequality and Bolzano-Weierstrass theorem. I think that this scheme, while keeping it intuitive, has lengthened the proof considerably. I'd appreciate if anyone checks the proof, whether or not there is any hole in it (I checked, but still) and most importantly, if you can suggest me some other scheme to attack the problem, which may give us a quick and short proof. Thank you.

Let $\epsilon>0$. Since $(x_n)$ is Cauchy, there exists $N=N(\epsilon) \in \mathbb{N}$ such that
$$m,n \geq N \implies |x_n-x_m|<\frac{\epsilon}{3}$$
In particular, choosing $m=N$, we have
$$n \geq N \implies |x_n-x_N|<\frac{\epsilon}{3}$$
It is clear that, for all $n \in \mathbb{N}$,
$$\min\{x_1,\ldots,x_{N-1},x_N-\frac{\epsilon}{3}\} \leq x_n \leq \max\{x_1,\ldots,x_{N-1},x_N+\frac{\epsilon}{3}\}$$
Hence the sequence $(x_n)$ is bounded. So we are in a position to employ the powerful Bolzano-Weierstrass theorem. There exists a subsequence $(x_{n_k})$ that converges in $\mathbb{R}$. Let $x_{n_k} \to x$ as $k \to \infty$. Hence, there exists $K_1 \in \mathbb{N}$ such that
$$k \geq K_1 \implies |x_{n_k}-x|<\frac{\epsilon}{3}$$
This gives us a point $x$ of attack, a "guesstimate" for where the sequence $(x_n)$ might converge. Now, there exists $K_2 \in \mathbb{N}$ such that
$$k \geq K_2 \implies n_k \geq N \implies |x_{n_k}-x_N|<\frac{\epsilon}{3}$$
Choose $K_0=\max\{K_1,K_2\}$. Then in particular,
$$|x_{n_{K_0}}-x|<\frac{\epsilon}{3},\,\,\,\,|x_{n_{K_0}}-x_N|<\frac{\epsilon}{3}$$
Finally, We combine all these estimates by triangle inequality to write
$$n \geq N \implies |x_n-x| \leq |x_n-x_N|+|x_N-x_{n_{K_0}}|+|x_{n_{K_0}}-x|<\frac{\epsilon}{3}+\frac{\epsilon}{3}+\frac{\epsilon}{3}=\epsilon$$
Since $\epsilon>0$ is chosen arbitrarily, the sequence $(x_n)$ converges to $x$. Hence the proof.

A: It looks fine to me. Here's an alternative (though similar) approach, by splitting the problem into parts.

Lemma. A real Cauchy sequence is bounded.

Proof. Let $\{x_n\}_{n \geq 1} \subseteq \mathbb{R}$ be a Cauchy sequence. By hypothesis, there exists $n_0 \in \mathbb{N}$ such that if $n, m \geq n_0$ then $|x_n -x_m| < 1$. Therefore,
$$
|x_n| \leq |x_n-x_{n_0}| + |x_{n_0}| \leq 1 + |x_{n_0}|
\quad (\forall n \geq n_0)
$$
so $|x_n| \leq 1 + \max_{1 \leq i \leq n_0}|x_i|$ for all $n$.

Lemma: let $\{x_n\}_{n \geq 1} \subseteq \mathbb{R}$ be a Cauchy sequence. If  $\{x_n\}_{n \geq 1}$ has a convergent subsequence, it is convergent.

Proof. By hypothesis, there exists a convergent subsequence $x_{n_k} \to x$. Now, I claim that:
$$
|x_k -x| \leq |x_k - x_{n_k}| + |x_{n_k} - x| \to 0
$$
Since $x_{n_k} \to x$, we only have to note that $|x_k - x_{n_k}| \to 0$. In effect, if $\varepsilon > 0$, there exists $K \in \mathbb{N}$ such that $n,m > K$ implies $|x_n - x_m| < \varepsilon$. Now if $k \geq K$, we have that $n_k \geq  k \geq K$ and thus $|x_k - x_{n_k}| < \varepsilon$. Therefore, $x_k \to x$ as claimed.
Finally, we can prove the original statement.

Theorem: $\mathbb{R}$ is complete.

Proof. Let $\{x_n\}_{n \geq 1} \subseteq \mathbb{R}$ be a Cauchy sequence. By the first lemma, the sequence is bounded. Thus, the Bolzano-Weierstraß theorem guarantees the existence of a convergent subsequence. By the second lemma, this implies that $\{x_n\}_{n \geq 1}$ itself is convergent, which completes the proof.


text:
Q: how to update a bunch of entities with one async call(submit) Suppose I have table Mytab in my database like:
MyTab(ID, col1, col2, col3,col4)

With EF, I have an entity named MyTab. With WCF RIA SERVICES, I can update data by SubmitChanges at Silverlight on the client side.
Then I have a list of data for this entity at client side:
ID    col3
1     A
2     B
3     C
4     D
5     E

I want to update Col3 for all those data in the list. Then I need populate each entity by WCF RIA Services firstly, then change col3 for each entity in entity collection, then submit change. If I have 1000 records in the list, I will have 1000 async calls to populate each entity with the ID.
I have no query to get all entities with those IDs, because no rules for this IDs in the list.
Any solution could with one async call to send all database to server to update data in DB?

A: In this case I would use an invoke operation on the service. That way you simply invoke the method and there is no need to previously load any entity to the client.
To do so first create an invoke operation on your service
[EnableClientAccess]
public class MyDomainService : DomainService
{
    [Invoke(HasSideEffects = true)]
    public void UpdateCol3OfAllEntities()
    {
        // Use you data access layer to perform the neccessary
        // query: "UPDATE MyTab SET col3 = 'X'"...
    }
}

You can even extend the method by passing the ids to it:
[Invoke(HasSideEffects = true)]
public void UpdateCol3OfAllEntitiesWithIds(int[] ids)
{
    // Use you data access layer to perform the neccessary
    // query: "UPDATE MyTab SET col3 = 'X' WHERE id IN (...)"...
}

Then simply invoke that on the client side:
var context = new MyDomainContext();
context.UpdateCol3OfAllEntities(operation =>
    {
        if (operation.HasError)
        {
            // If in trouble or in doubt, run in circles, scream and shout!
            operation.MarkErrorAsHandled();
        }
        else
        {
            // Rejoice, for the operation succeeded!
        }
    }, null);

Note that the operation is decorated with the InvokeAttribute, which has set its HasSideEffects-parameter to true. That indicates that by invoking this method you acutally change something on the relevant data. See the MSDN for further details on that topic:

*

*on the InvokeAttribute

*on the HasSideEffects-property


text:
Q: Where do I find a free (open source preferably) VNC management tool? I am trying to get remote internal setup for our business. Basically, I just want to remote desktop into any computer on the network. I don't want to use LogMein, because I only want it to be internal for security.
Basically, I am looking for a way to just install VNC clients on all the machines, and on my machine have centralized manager for all the machines that are connected to it.
Doesn't have to VNC - just needs to work and be free.
All systems running Win 7 64bit

A: Remote Desktop Manager, I've found, is the simplest and most powerful remote connection manager.  It keeps a hierarchical list of all connections, and can keep track of a huge number of types of connections: RDP, VNC, PCAnywhere, TeamViewer, LogMeIn, DameWare, FTP, SSH, Telnet, VMWare, Hyper-V, X11, Citrix, VirtualBox, etc.
The programs can store its list of connections in an MDB which can be put on a file share so multiple computers can have the same database, or the Enterprise version supports storing on SQL Server or Amazon S3.

For the actual connection, I agree with Owen and say you should probably just use Remote Desktop.  I've found it's the fastest and best engineered of the remote desktop solutions.
If you're trying to help another user on their logon (as you mentioned in a comment), you should install Remote Assistance on each of the computers.  It's a feature built-in to Windows that allows screen sharing; I use it myself since I have to support a few people remotely, and it works very well.  And yes, Remote Desktop Manager supports Remote Assistance connections.

A: If every computer is Windows - I wouldn't even bother with VNC.  Just use the Remote Desktop Connection provided via Windows.  (Note:  Only included with Pro, Ultimate, and Business versions.)  Couple resources to get you started:
http://windows.microsoft.com/en-us/windows-vista/Remote-Desktop-Connection-frequently-asked-questions
http://www.howtogeek.com/howto/windows-vista/turn-on-remote-desktop-in-windows-vista/

A: Some vendors have free editions, like this one.  Do a Google search and you should find plenty of resources.  Also, I'm sure SU has several posts on the topic as well.

A: An open source, tabbed, multi-protocol, remote connections manager:
https://mremoteng.org/


text:
Q: Trying to add websites to localstorage in chrome extension options page I want to be able to add websites to a chrome extension options page. So I have a text box with a "save" button and I want to be able to save multiple websites with the ability to edit or remove them later. Like this:
Enter URL: |_________| |_save_|
Edit Remove - www.google.com
Edit Remove - www.msn.com
Edit Remove - www.yahoo.com
Once you enter a website and click save, it will add it to the list of websites already there. I've been trying to scavenge the internet to try to figure out how to accomplish this, but I just don't know enough about it to complete it.

A: I'd recommend chrome.storage instead of localStorage: http://developer.chrome.com/extensions/storage.html
It's fantastic. You can even choose to store data online in your Google profile (100KB max). Otherwise offline (100MB max, I think).
API is super simple too:
chrome.storage.local.get('websites', function(items) {
  console.log('websites:', items.websites);
});

Unlike localStorage, it's async, so you'll be using callbacks. But it's lightning fast, so the UI won't notice.
What I'd do is not keep a virtual record of your storage, but keep it in HTML and read from/write to that as necessary:

*

*btnAdd adds a new LI to the list and then saves the list

*btnEdit fills the textfield and removes the LI from the list (no save) (saving via btnAdd)

*btnDelete removes the LI from the list and saves the list

*save = get items from list as array and save to storage

*init = load items from storage and fill list

http://jsfiddle.net/rudiedirkx/Zbpmx/
I'm assuming jQuery since it's popular. It's not necessary of course.
If you're having problems with this already, a Chrome extension will be insanely difficult.


text:
Q: Track number of Calls/Emails from Case I would like to track on how many Calls and Email Sent/Received on Case.We have enabled email 2 case and sending emails using Send an Email button(Emails related list) on Case and Logging calls from Log a Call button(Activity History) on Case.
Now I would like to report on Number of Calls/Emails made on each case

*

*Created a custom pick list field 'Activity Type' with Call and Email
as pick list options.

*Created a workflow rule to update Activity Type with Call if
subject of Task contains 'Call' and

*Created a workflow rule to update Activity Type with'Email' if subject of
Task  starts with Email
I would like to run report off of Activity Type field
But second workflow is not working as expected as it doesn't update Activity Type to email.I tried by changing the workflow rule criteria from Starts with to Contains
Is my approach correct ?

A: You cant fire off a workflow for the task that gets created from Email to Case, just like you can't fire a workflow for using the Send an Email button. The internal workflow that Salesforce has for those is not set to fire off your workflow rules after it creates the task. Resolution of this idea would allow for what you want to do here. I also know this doesn't work with Process Builder either. I believe this can be done using a trigger on the Task object, but I don't know if that's the answer/solution you are looking for here. There is a knowledge base article on this here as well


text:
Q: How to structure this interface in xcode? I've am learning Objective C by myself and i was trying to do something like this, but i was wondering what would be the best and the most correct way of doing it.
I am using storyboard but it won't matter, since this is for my learning, it can be done with separated xibs.
Just explaining, a bunch of buttons on top (no need to scroll to the sides), that when you touch them, it loads a specific view as if it was a ballon. Not like the tab bars.
Any idea?
Just a PS here, i am not asking for the code ready, just ideas of how to implement it.
Thanks
Here follows the image:

A: You could implement this in a number of ways, here are a few suggestions:

*

*Use UIViewController containment where the button bar is a subview of the ContainerViewController and each button displays a ContentViewController (the white view with corresponding arrow).

*Simply have each button in the button bar display a UIView subclass (the white area with arrow).

*Have each button in the button bar trigger the display of a UIPopoverController (white area, with the advantage that the arrow will be be included and positioned for free).

*If you do need to side scroll the buttons in the button bar you could use a UICollectionView.
Hope this helps.

A: I would do that, using a custom Container Controllers.

*

*The parent viewController should have all views from the screenShoot

*The childView Controller should have the view inside the ballon

You can create a list of child viewControllers, and every time one of the circle is click you can change the controller using:
- (void) displayContentController: (UIViewController*) content;
{
   [self addChildViewController:content];
   content.view.frame = [self frameForContentController];
   [self.view addSubview:self.currentClientView];
   [content didMoveToParentViewController:self];
}

- (void) hideContentController: (UIViewController*) content
{
   [content willMoveToParentViewController:nil];
   [content.view removeFromSuperview];
   [content removeFromParentViewController];
}

Create a view with the up arrow, and change the center property of it, based on the position of the button that revived the click.
-(void)didTouchButton:(UIButton*)target{
       [UIView animateWithDuration:0.5f animations:^ {
           CGRect frame = _upArrow.frame;
           frame.origin.x = target.origin.x;
           _upArrow.frame = frame;
       } completion:^(BOOL finished) {
          // here you can added your view controller
       }
 }


text:
Q: ASP.NET MVC 5 database update I was initializing my website Users and Roles data in IdentityConfig.cs file and when I added a new model than mapping it to the database using code-first add-migration and update-database command, I get an empty database:
public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
{
    protected override void Seed(ApplicationDbContext context)
    {
        InitializeIdentityForEF(context);
        base.Seed(context);
    }

    // Create User=aadmin2018@mail.com with Admin2018@mail.com in the Admin role
    public static void InitializeIdentityForEF(ApplicationDbContext db)
    {
        var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
        const string name = "admin2018@mail.com";
        const string password = "Admin2018@mail.com";
        const string roleName = "Admin";

        // Create role Admin if it does not exist
        var role = roleManager.FindByName(roleName);

        if (role == null)
        {
            role = new IdentityRole(roleName);
            var roleresult = roleManager.Create(role);
        }

        var user = userManager.FindByName(name);

        if (user == null)
        {
            user = new ApplicationUser
            {
                UserName = name,
                Email = name,
                FirstName = "Admin",
                LastName = "Admin",
                DateOfBirth = new DateTime(2015, 1, 1),
                Address = new Address
                {
                    AddressLine1 = "1 Admin Street",
                    Town = "Town",
                    County = "County",
                    Postcode = "PostCode"
                }
            };

            var result = userManager.Create(user, password);
            result = userManager.SetLockoutEnabled(user.Id, false);
        }

        // Add user admin to Role Admin if not already added
        var rolesForUser = userManager.GetRoles(user.Id);

        if (!rolesForUser.Contains(role.Name))
        {
            var result = userManager.AddToRole(user.Id, role.Name);
        }

        // Create users role
        const string userRoleName = "Users";
        role = roleManager.FindByName(userRoleName);

        if (role == null)
        {
            role = new IdentityRole(userRoleName);
            var roleresult = roleManager.Create(role);
        }
    }
}

What should I change to the code so those data return to the database?


text:
Q: How to get line break in E-Mail from shellscript? There is a shell script (bash) that check a csv file for lines that don't match a pattern and send a mail with the wrong lines. Thats works fine but while combine the wrong lines linux give a \r as line break, in the E-Mail there is no linebreak. So I try to send \r\n as line break but this has no effect, perl or bash delete this \n newline.
Here is a minimal working script as example:
SUBJECT="Error while parse CSV"
TO="rcpt@domain.tld"
wrongLines=$(perl -ne 'print "Row $.: $_\r\n" if not /^00[1-9]\d{4,}$/' $file)
MESSAGE="Error while parse following Lines, pattern dont match: \r\n $wrongLines"
echo $MESSAGE |od -c

The output of od is:
0000000   E   r   r   o   r       w   h   i   l   e       p   a   r   s
0000020   e       f   o   l   l   o   w   i   n   g       L   i   n   e
0000040   s   ,       p   a   t   t   e   r   n       d   o   n   t
0000060   m   a   t   c   h   :       \   r   \   n       R   o   w
0000100   2   :       4   9   2   7   8   3   8   7   4   3      \r   R
0000120   o   w       3   :       4   8   2   3   2   8   9   7   3   8
0000140      \r  \n
0000143

But what is the reason that in the od output the \n between the rows is deleted? I also try \x0D\x0A instead of \r\n but this also don't help. Any suggestions?

A: Your problem is that you're not using quotes!
Look:
$ a="A multi-line
input
variable"
$ echo $a
A multi-line input variable
$ echo "$a"
A multi-line
input
variable
$

Without quotes, you'll be victim of word splitting and filename expansion (not illustrated in the example above).
Also, adding \r or \n (that is, verbatim backslash followed by r or n) is not going to help at all.
Conclusion: Quote every variable expansion! always! (unless you really mean a glob pattern — in which case you will also add a comment in the code to explain why you purposely didn't quote the expansion).
Side note: don't use upper case variable names!

It is recommended you use lower-case names for your own parameters so as not to confuse them with the all-uppercase variable names used by Bash internal variables and environment variables.


text:
Q: Text Gradient in Android Jetpack Compose Can't figure out how to add a gradient to a text with an inner shadow with a modifier in Jetpack Compose.
To have something like this? Any ideas?

A: So far jetpack compose doesn't provide text gradient and inner shadow out of the box.
Hence need to paint it by yourself:

@Composable
fun drawGradientText(name: String, modifier: Modifier = Modifier) {

    val paint = Paint().asFrameworkPaint()

    val gradientShader: Shader = LinearGradientShader(
        from = Offset(0f, 0f),
        to = Offset(0f, 400f),
        listOf(Color.Blue, Color.Cyan)
    )

    Canvas(modifier.fillMaxSize()) {
        paint.apply {
            isAntiAlias = true
            textSize = 400f
            typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
            style = android.graphics.Paint.Style.FILL
            color = android.graphics.Color.parseColor("#cdcdcd")
            xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER)
            maskFilter = BlurMaskFilter(30f, Blur.NORMAL)
        }
        drawIntoCanvas { canvas ->
            canvas.save()
            canvas.nativeCanvas.translate(2f, 5f)
            canvas.nativeCanvas.drawText(name, 0f, 400f, paint)
            canvas.restore()
            paint.shader = gradientShader
            paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
            paint.maskFilter = null
            canvas.nativeCanvas.drawText(name, 0f, 400f, paint)
            canvas.nativeCanvas.translate(2f, 5f)
            paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER)
            paint.maskFilter = BlurMaskFilter(30f, Blur.NORMAL)
            canvas.nativeCanvas.drawText(name, 0f, 400f, paint)
        }
        paint.reset()
    }
}

You can adjust PorterDuff modes and offsets to meet your requirements.

A: Just ran into the same use case, but just for a simple gradient on text. Posting it here in case it helps someone.
What worked for me was drawing the content and then the gradient via Modifier.graphicsLayer (extrapolated from this answer on Slack):
Text(
   text = "$ 20",
   /** size/font style, etc. **/
   modifier = Modifier.graphicsLayer(alpha = 0.99f)
     .drawWithCache {
        val brush = Brush.horizontalGradient(listOf(StartColor, EndColor))
        onDrawWithContent {
            drawContent()
            drawRect(brush, blendMode = BlendMode.SrcAtop)
        }
     }
)

I ended up making it a Modifier for reuse:
fun Modifier.textBrush(brush: Brush) = this
   .graphicsLayer(alpha = 0.99f)
   .drawWithCache {
      onDrawWithContent {
         drawContent()
         drawRect(brush, blendMode = BlendMode.SrcAtop)
      }
   }

Example Result:

A: In Jetpack Compose 1.2.0-beta01 text gradients were added.
Example:
@Composable
fun BrushDemo() {
    Text(
        "Brush is awesome\nBrush is awesome\nBrush is awesome",
        style = TextStyle(
            brush = Brush.linearGradient(
                colors = RainbowColors,
                tileMode = TileMode.Mirror
            ),
            fontSize = 30.sp
        )
    )
}

More examples here.


text:
Q: Checking if an index in a multidimensional array is an array The code:
    $row['text'] = 'http://t.co/iBSiZZD4 and http://t.co/1rG3oNmc and http://t.co/HGFjwqHI and http://t.co/8UldEAVt';

    if(preg_match_all('|http:\/\/t.co\/.{1,8}|i',$row['text'],$matches)){
        foreach($matches[0] as $value){
            $headers = get_headers($value,1);
            if(is_array($headers['Location'])){
                $headers['Location'] = $headers['Location'][0];
            }
            $row['text'] = preg_replace('|http:\/\/t.co\/.{1,8}|i', '' . $headers['Location'] . '',$row['text']);
        }
    }

This is related to get_headers().  Sometimes get_headers($url,1) returns an array with a location index key like so: [Location]=>Array([0]=>url1 [1]=>url2).  I basically want to make [Location] equal to [Location][0] if [Location][0] exists.  However, the above code doesn't seem to accomplish that task.  I've also tried array_key_exists() and isset() but neither solved the problem.  Thoughts?

A: Don't try to replace on the fly. First get all the values, and then do the replace in one batch (using two arrays as the $search and $replace parameters).
<?php

    $replace = array();
    $row = array('text' => 'http://t.co/iBSiZZD4 and http://t.co/1rG3oNmc and http://t.co/HGFjwqHI and http://t.co/8UldEAVt');
    if (preg_match_all('|http:\/\/t.co\/.{1,8}|i', $row['text'], $search)) {
        foreach ($search[0] as $value) {
            $headers = get_headers($value, 1);
            if (is_array($headers['Location'])) {
                $headers['Location'] = $headers['Location'][0];
            }
            $replace[] = "{$headers["Location"]}";
        }
        $row['text'] = str_replace($search[0], $replace, $row['text']);
        echo $row["text"];
    }

P.S. - Next time, please tell us the context of your problem, tell us you "are making a service that resolves shortened URLs", don't let me figure that out from your code alone.


text:
Q: Highcharts X-axis labels on the side I'm using Highcharts, and I used to be able to get labels on the side. But it's not working now, am I missing something? The red arrow is where I would want the labels like in the following example.
http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/bar-basic/

This is the code I'm using, I add the series in a dynamic way.
 credits: {
                enabled: false
            },
            chart: {
                type: 'bar'
            },
            xAxis: {
                categories: ['Jan', 'Feb'],
                labels: {
                    enabled: true,
                }
            },
            yAxis: {
                min: 0,
                max: 100,
                title: {
                    text: 'Score',
                    align: 'high'
                }
            },
            plotOptions: {
                bar: {
                    dataLabels: {
                        enabled: true
                    }
                }
            }
        });

        // Add Series
        var detailchart = $('#chart-detail').highcharts();
        var categories = new Array;

        // Set Chart Title
        detailchart.setTitle({text: results[0].category});

        $.each(results, function(i, data){
            categories.push(data.name);
            detailchart.addSeries({
                name: data.name,
                data: [data.score]
            });
        });

        detailchart.xAxis[0].setCategories(["1", "2"]);
        $('#chart-detail').highcharts().reflow();

Results is an array that looks like this (I get it through ajax):

A: As I understand from your code here, you wish to specify two categories with names 1 and 2 but you are not specifying any data for second category, So the only category that is showing on your chart is 1. Your data array for each series must have elements per each category. For example if you have two category you should consider having two data elements in each series. In this line data: [data.score] you are just specifying one element in data array. Your code should be something like this: (make it dynamic per your need)
$.each(results, function(i, data){
        categories.push(data.name);
        detailchart.addSeries({
            name: data.name,
            data: [data.score, 40], //40 is some data for your second category.
        });
    });

Demo: http://jsfiddle.net/u6crkatv/

A: Only what you need is use 4 series, each of them with single data point.
series: [{
        name: 'Year 1800',
        data: [107]
    }, {
        name: 'Year 1900',
        data: [138]
    }, {
        name: 'Year 2008',
        data: [973]
    },{
        name: 'Year 20098',
        data: [973]
    }]

Example: http://jsfiddle.net/y9wzggc4/


text:
Q: Why is Jackson using the wrong element name when serializing? I have a Object that I would like Jackson to serialize like this...
<AccountsResponse>
    <accounts>
        <account/>
        <account>
            <userId>user</userId>
            ...
        </account>
    </accounts>
</AccountsResponse>

To try this I create the following class...
@Getter
@Setter
@ToString
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Payload {
    @JacksonXmlProperty(localName = "errormessage")
    private String errorMessage;
}

@Getter
@Setter
@ToString
public class AccountsResponse extends Payload{
    @JsonIgnore
    private static Logger LOGGER = LogManager.getLogger(AccountsResponse.class);

    @JacksonXmlProperty(localName = "accounts")
    private List<Account> accounts = Lists.newArrayList();
    public static AccountsResponse mapFromResultSet(ResultSet rs)
            throws SQLException
    {
        AccountsResponse response = new AccountsResponse();
        do {
            Account acct = Account.mapFromResultSet(rs);
            response.getAccounts().add(acct);
        } while (rs.next());
        return response;
    }
    public String toXml() throws JsonProcessingException {
        ObjectMapper mapper = new XmlMapper();
        return mapper.writeValueAsString(this);
    }
}

@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Account extends ResultSetParser{
    ...
}

But when I serialize I get...
<AccountsResponse>
    <accounts>
        <accounts/>
        <accounts>
            <userId>user</userId>
            ...
        </accounts>
    </accounts>
</AccountsResponse>

As you can see the problem here is the child tags should be account but in fact are accounts. I tried hacking around with the localname but can't find the right mixture of VooDoo. What am I doing wrong?

A: I would change annotations on account list in AccountsResponse:
public class AccountsResponse extends Payload{

    @JacksonXmlElementWrapper(localName = "accounts")
    @JacksonXmlProperty(localName = "account")
    private List<Account> accounts = Lists.newArrayList();

}


text:
Q: Extjs6 Excel like grid filters with store I am trying to create a complex filter for a grid. I want the following general behavior:

*

*The filters have a different store than the grid

*Apply filter on column A

*The grid is filtered based on my selection

*The filter in column B will show the available items

Also, the grid has a button that clears all the filters and more, remove the checked items from the filters.
Based on this link I've tried to do something similar. I've created also a fiddle.
Regarding the fiddle, I have some question:
1.The following code returns undefined. Based on the documentation it should return a Menu object.
business.filter.menu = business.filter.createMenu({
        store: localStore
})

2.I want to clear the checked items when user press the Clear Inline Filter button.
    var f = Ext.ComponentQuery.query('test-grid')[0].getColumnManager().getHeaderByDataIndex(element).filter;
    if (f.menu) {
        for (var j = 0; j < f.menu.items.length; j++) {
            f.menu.items.items[j].setChecked(false)
        }
    }

Here the, f.menu is always undefined so I can't clear the checkbox. Somehow I lose reference to menu.
How to clear the checkboxes based on my scenario? Why the createMenu returns undefined?
Edit
The accepted answer worked for this specific question(fiddle)

A: On a general note:
Don't call methods/use properties explicitly marked private in the documentation.
This usually means the way you're doing something is wrong and there is another more automated way to achieve that.
Especially don't take Ext4 examples and port them 1:1 to Ext5 or Ext6.
The Framework changed quite a lot in Ext5 and a little more in Ext6.
In this case the filter menu is supposed to be created automatically from the filter store without human interaction.
In order to uncheck a menu items, simply stop filtering by that value.
Using the ColumnManager to find a certain column is also a reserved for internal use, but I can see why you'd want to go that way. It's easier than filtering the response form getColumns by hand.


text:
Q: Command Not Found Jekyll I'm trying to create and publish a Jekyll blog using this template.
I installed Jekyll initially. Without any luck, I did resort to installing it via sudo. (And have now since uninstalled it!)
Jekyll(1.4.2, 1.0.3) and am running rvm with ruby 2.0.0p195. After installing the gem, I run jekyll serve in the folder but get the error: Zsh Command Not Found. I tried changing my path to no avail. Any advice on how to troubleshoot?
I cannot uninstall/reinstall nokogiri (see other SO articles on this) because of dependencies related to work projects.

A: If you're using rvm you should not install gems with sudo. Rvm is user-specific (the binaries are all in your home directory), so putting Ruby stuff in system-wide folders with sudo will not work. Just install without sudo and you should be ok.
The rvm docs tries to explain this a little bit here:
http://rvm.io/rubies/rubygems

DO NOT use sudo...
...to work with RVM gems. When you do sudo you are running commands as root, another user in another shell and hence all of the setup that RVM has done for you is ignored while the command runs under sudo (such things as GEM_HOME, etc...). So to reiterate, as soon as you 'sudo' you are running as the root system user which will clear out your environment as well as any files it creates are not able to be modified by your user and will result in strange things happening. (You will start to think that someone has a voodoo doll of your application...)


text:
Q: Why does my java file not see the new elements in my R file? I am creating a compound view.
I have created a class for my new view:
import android.R;
public class LogoAndTextButton extends LinearLayout{

public LogoAndTextButton(Context context, AttributeSet attrs) {
    super(context, attrs);
    setOrientation(VERTICAL);

    TypedArray array = context.obtainStyledAttributes(attrs, R. , 0, 0);

I have created a attrs.xml for the in my res/values:
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <declare-styleable name="LogoAndTextButton">
        <attr name="image" format="reference"/>
        <attr name="text"  format="string"/>
    </declare-styleable>
</resources>

the styleable shows up in my R.java file!!!
public static final class style {
    public static final int AppBaseTheme=0x7f080000;
    public static final int AppTheme=0x7f080001;
}
public static final class styleable {
    public static final int[] LogoAndTextButton = {
        0x7f010000, 0x7f010001
    };
    public static final int LogoAndTextButton_image = 0;

    public static final int LogoAndTextButton_text = 1;
};

but when I go to my LogoAndTextButton java class file and type "R." and cntrl+space, "styleable" does not show up as one of the elements. and if I type it manually it complains that it cant be resolved. I've tried cleaning my project, and closing and re opening eclipse.

A: The problem is at the top of your source file
import android.R;

You are importing the Android resources, so it doesn't see yours. Remove that line and then try again.

A: For some reason I was importing android.R


text:
Q: Can I use the Same WordPress plugin used twice or more? I wanna know if is it possible to use the same plugin for 2 different websites?
For example, I'm buying a plugin from envanto market and I will install that to my current website. However, I'm worried that my website will be infected by malware later on (my websites under siteground are always being infected with no apparent reason so I'm quite worried)
If ever that happens, I'm just gonna create a new website (to avoid costly malware removal) and possibly install the same plugin I purchased from envanto.
Please help.
Thanks, guys.

A: Yes you can use the same plugin but on other website / domain. You have to just enter purchase code each time when you install plugin.
Before doing that please confirm with plugin author team if they have restricted the use / installation of plugin.
Thanks,

A: You can ofcourse use any plugin on any number of websites.
But, since you have purchased that plugin you will have to consider the license information. If you have purchased the plugin for only one website, then before using it on any other website you will have to disable and delete that plugin from previous website.
Developer of the plugin that you have purchased will be able to help you better in this case.


text:
Q: A particle is projected from the ground at an angle theta with horizontal and some velocity For any position A, show that $\tan\alpha + \tan\beta =\tan\theta$
MY SOLUTION:
We know that $\tan\theta=\frac{4h}{R}$
$$\tan\alpha=\frac{h}{x}$$
And
$$\tan\beta = \frac{h}{R-x}$$
So $$\tan\alpha + \tan\beta = \frac{hR}{xR-x^2}$$
That's as far as I could go up to. What should I do next?

A: You may continue by substituting the following results for a projectile into your expression
$$ x = v_0t\cos \theta  $$
$$ R = \frac{v_0^2}{g}\sin2\theta $$
$$ h = v_0t\sin\theta - \frac{1}{2} g t^2 $$
and verify that
$$\frac{hR}{xR-x^2}= \tan\theta$$

The numerator is
$$hR = \left(x\tan\theta - \frac{gx^2}{2v_0^2\cos^2\theta}\right)\frac{v_0^2\sin 2\theta}{g}=x\tan\theta \left(\frac{v_0^2\sin 2\theta}{g}-x  \right)$$
and the denominator
$$x(R-x) = x\left(\frac{v_0^2\sin 2\theta}{g}-x  \right)$$
Their ratio comes out as
$$\frac{hR}{xR-x^2}= \tan\alpha + \tan\beta= \tan\theta$$

A: Let's start with the equations of motions along the two axis. In the horizontal axis you have $$x=ut\cos\theta$$
In the vertical direction you have $$h=ut\sin\theta-\frac12 gt^2$$
Taking $t=\frac{x}{u\cos\theta}$ from the first equation and plugging it into the second you get $$h=x\tan\theta-\frac12 g\frac{x^2}{u^2\cos^2\theta}$$
First, to calculate $R$ you set $h=0$. One solution is obviously $x=0$. For the other solution $$0=\tan\theta-\frac12 g\frac{R}{u^2\cos^2\theta}$$
This yields $$R=2\frac{u^2}{g}\tan\theta\cos^2\theta$$
Now rewrite the formula for the height in terms of $R$ as $$h=x\tan\theta-\frac{x^2}R\tan\theta$$
From here it should be easy, just plug this into your $\tan\alpha+\tan\beta$ equation:
$$\tan\alpha+\tan\beta=\frac{hR}{x(R-x)}=\frac{xR\tan\theta-x^2\tan\theta}{x(R-x)}=\tan\theta$$


text:
Q: Creating jars from a class and using in in other programs I am a newbie in Java.
I have a java file A which I want to call in another java program B.
I want to create jar for the A and use it in B by creating the objects and calling the methods for A.
What type of jar is to be created and how can I add it to the library. Please help how to do it in Eclipse.
Also, how to import the jar in B.

A: You can go to File->Export->jar-File
name your jar-file (you do not need a runnable jar)
after that you can open your other project B
right-click -> properties-> java build path
select libraries and click on add external jars
choose your exported jar-file. Click ok
and it is imported to your actual project B
now you can use classes and methods of this jar-File

A: *

*First create a project in eclipse with class A (Creating project in Eclipse)

*Export this project as jar (Exporting jar in Eclipse)

*Create another project with class B and set class path of for exported jar (Setting class path in Eclipse)

Now you can use object of A in B.
 import com.A;
 public class B{
    public static void main(String[] args){
           A a=new A();
           //.......
}
 }


text:
Q: Reading an XML File and Selecting Nodes in .NET I have a heavier XML file with lots and lots of tree nodes. I need to pick-up some particular node (for example say Diet), under which there are multiple sections.
ie. Diet node occurs randomly in the XML, so i need to find the node as Diet and get its child elements and save it to DB.
Assume that Diet is not only one line, it has 10-12 entries underneath it (may be i can get its contents using InnerXML, but really can't get line by line nodes)

A: *

*Make sure you have added a reference to "System.xml.Linq'.

*Suck out all the Diet elements:
XElement wholeFile = XElement.Load(@"C:\DietSampleXML.xml");
IEnumerable<XElement> dietElements = wholeFile.Descendants("Diet");

*If you set a breakpoint and hover the mouse over "dietElements" and click "Results View", you will see all the Diet elements and their inner xml.

*Now iterate through dietElements to add each element and/or children to your database: "foreach (XElement x in dietElements) { ... }"
I tested this with the following xml:
<?xml version="1.0" encoding="utf-8" ?>
<TestElement>
  <Diet>
    <Name>Atkins</Name>
    <Colories>1000</Colories>
  </Diet>
  <TestElement2>
    <Diet>
      <Name>Donuts Only</Name>
      <Calories>1500</Calories>
    </Diet>
  </TestElement2>
  <TestElement3>
    <TestElement4>
      <Diet>
        <Name>Vegetarian</Name>
        <Calories>500</Calories>
      </Diet>
    </TestElement4>
  </TestElement3>
</TestElement>

A: In XPath, it's just //Diet
To say more, I'd need to know more about your environment.
var doc = XDocument.Load("yourfile.xml");
var nodes = from d in doc.Desendants("Diet")
            select d;

foreach(var node in nodes)
{   // do stuff with node
}

A: Depending on the structure of your XML file, you might try loading it into a DataSet (DataSet.ReadXML()) and see what DataTable it puts your Diet nodes into ... if it parses it ok then it is pretty simple to loop through the DataTable and get all your Diet node values.
I wrote a little toy app that opens XML like that, listing all the DataTables in a tree view then showing the table content in a grid.  The VS project file for it is here or just an MSI to install it is here, if you want to see how a DataSet parses your XML file.

A: The pseudo code below, contains the XPath statement that would get you all elements who have a 'Diet' as parent. Since it produces a XmlNodeList you can walk every node and save it to the DB. For performance i would consider consolidating what you want to save, and then save it, not per line (round trip for every entry is sub-optimal)

XmlNodeList list = xDoc.DocumentElement.SelectNodes("//*[parent::Diet]");
foreach (XmlNode entry in list)
{
    DAL.SaveToDatabase(entry);
}

Hope this helps,


text:
Q: Position sticky relative to parent to parent container I need a sticky header relative to parent div. Currently, Header is sticky only on a section div.
But I want a sticky header relative to a parent class.
HTML code

Header 1

         content 123

Header 2

         content 789

Header 3

         content 456

Here is my css,
.parent {
   position: relative;
}
.section-one h1{
   position: sticky;
   top: 0;
   z-index: 9999;
}
.section-two h1{
   position: sticky;
   top: 50;
   z-index: 9999;
}
.section-three h1{
   position: sticky;
   top: 100;
   z-index: 9999;
}

I want a sticky header as per below
Header 1
Header 2
Header 3

I want a sticky header as per image.

A:

$(window).scroll(function() {
    var distanceFromTop = $(this).scrollTop();
    if (distanceFromTop >= $('.section-one').offset().top) {
        $('.section-one h1').addClass('fixed');
    }
    if (distanceFromTop >= $('.section-two').offset().top) {
        $('.section-two h1').addClass('fixed');
    }
    if (distanceFromTop >= $('.section-three').offset().top) {
        $('.section-three h1').addClass('fixed');
    }

    if (distanceFromTop >= $('.parent').height()) {
        $('.section-one h1').removeClass('fixed');
        $('.section-two h1').removeClass('fixed');
        $('.section-three h1').removeClass('fixed');
    }
});
.parent {
   position: relative;
}
.section-one,
.section-two,
.section-three { min-height: 100vh; }

.section-one { background: lightgray; }
.section-two { background: lightblue; }
.section-three { background: lightgreen; }

.section-one h1{
   position: sticky;
   top: 0;
   z-index: 9999;
}
.section-two h1{
   position: sticky;
   top: 0;
   z-index: 9999;
}
.section-three h1{
   position: sticky;
   top: 0;
   z-index: 9999;
}

.section-one h1.fixed {
    position: fixed;
    top: 0px;
}
.section-two h1.fixed {
    position: fixed;
    top: 50px;
}
.section-three h1.fixed {
    position: fixed;
    top: 100px;
}

Header 1

         content 123

Header 2

         content 789

Header 3

         content 456


text:
Q: Prove that $ (\mathbb{Q}\times\mathbb{R})\cup (\mathbb{R}\times\mathbb{Q})$ is a locally connected and connected subspace of $\mathbb{R}^2$ The book I am using for my Introduction of Topology course is Principles of Topology by Fred H. Croom.

Prove that $A = (\mathbb{Q}\times\mathbb{R})\cup (\mathbb{R}\times\mathbb{Q})$ is a locally connected and connected subspace of $\mathbb{R}^2$

This is what I understand:

*

*A space $X$ is connected provided that it cannot be written as the disjoint union of specifically two open sets.

*A space $X$ is locally connected at a point $a$ in $X$ if every open set containing $a$ contains a connected open set which contains $a$. The space $X$ is locally connected provided that it is locally connected at each point.

*I'm aware that neither connected nor locally connected implies the other, nor do their negations. Meaning I would have to prove each.

*Now the set of rationals is disconnected (in fact totally disconnected). $\mathbb{R}^2$ is connected and locally connected.

*$A \subseteq \mathbb{R}^2$

I'm a little stuck on how to approach this question; however, I do have a rough idea.
To prove $A$ is connected, I can claim that $A$ is disconnected. Then there exists two nonempty set $U$ and $V$ such that $U\cup V=A$ and $U \cap V = \emptyset$. Thus $U$ and $V$ are clopen. Eventually, I should arrive at a contradiction because $\emptyset$ and $A$ are the only subsets of $A$ that are clopen, proving $A$ is connected. However I am not sure how to properly execute the approach.
To prove $A$ is locally connected. I can claim the space $A$ has a local basis $\mathscr{B}_a$. I would need to prove that $\mathscr{B}_a$ consist of connected open sets, proving $A$ is locally connected.
Am I on the right track? Any suggestions oh how I can proceed with my ideas?

Sorry for the long read. If there are any mistakes in what I stated above, please let me know so I can correct it. I sincerely thank you for taking the time to read this question. I greatly appreciate any assistance you may provide.

A: For "connected", I suggest you show that it's path-connected. To find a path from $(q, r)$ to $(q', r')$, move along the edge $([q, 0], r)$ that's in the first component, and then along $(0, [r, r'])$ and then along $([0, q'], r')$. Once you make sense of this (looking at cases where $q < 0, q> 0, q = 0$, etc.), the rest should be straightforward.
In fact, just write down a path from $(q, r)$ to $(0, 0)$, and you're done  (at least with this part). That should also help you do the second part. Why? Because there are a lot of rationals -- 0 isn't the only one.

A: There are several possible approaches to this. As suggested by John Hughes, you could prove path-connectedness. Another approach is as follows: $A$ is the union of $$A_q=\{q\}\times\mathbb R\cup\mathbb R\times\{q\}$$ over all rationals $q\in\mathbb Q$. Now, remember the following:
Theorem. Suppose $(X_\lambda)_{\lambda\in\Lambda}$ is a family of connected sets such that $X_{\lambda_1}\cap X_{\lambda_2}$ is non-empty for all $\lambda_1,\lambda_2$. Then $\bigcup_{\lambda\in\Lambda}X_\lambda$ is connected.
It follows easily from this that $A_q$ are connected and that $\bigcup_{q\in\mathbb Q} A_q$ is connected.
Your can prove local connectedness using a similar approach: first observe that the neighborhood of any point contains a "square", then prove that this "square" is connected.


text:
Q: Moving cursor to cell below in google sheets automatic when datainput amount = 1 Im making a registration kind of google sheets project, where the amount of input is quite high, however the input in each cell only needs to be 1 number. It would therefore be usefull to have a script, which made the cursor jump to the cell below after input of 1 number.
efunction onEdit(e) {
var sheet = e.source.getActiveSheet();
var activeCell = sheet.getActiveCell();
var col = activeCell.getColumn();
var row = activeCell.getRow();
var value = activeCell.getValue();
if (value.length == 1) {
 sheet.getRange(row + 1, col).activate();
  }
}

However this only makes the cursor jump to the cell below the one which the input has been made, when another action is made, like clicking on 3rd cell. therefore not making the registrations easier.
Hope you can help.

A: The Google Sheets onEdit(e) trigger only runs when the user completes their data entry in a cell, usually by pressing Enter or Tab. You cannot watch individual characters as they are being entered.
What you can do, however, is let the user enter longer strings of digits in the cell, and when Enter is finally pressed, put each one of those digits in a cell of its own. You can then move the selection after the last digit that was thus filled down.
To do that, use String.split(), like this:
/**
* Simple trigger that runs each time the user hand edits the spreadsheet.
*
* Watches column Sheet1!A2:A as it is edited and splits digit strings such
* as 321654 or 321 654 into single digits 3, 2, 1, 6, 5, 4, and puts each
* digit in a cell of its own, stacking them vertically, starting at the
* cell where the digit string was entered.
* Moves the selection to the cell after the cell where last digit was put.
* Will happily overwrite values in cells under the cell that was edited.
*
* @param {Object} e The onEdit() event object.
*/
function onEdit(e) {
  // version 1.0, written by --Hyde, 2 January 2023
  //  - see https://stackoverflow.com/a/74986570/13045193
  if (!e) throw new Error('Please do not run the onEdit(e) function in the script editor window.');
  if (!e.value
    || e.value.match(/[^\d\s]/i)
    || e.range.columnStart !== 1 // column A
    || e.range.rowStart < 2
    || !e.range.getSheet().getName().match(/^(Sheet1)$/i)) {
    return;
  }
  const numbers = e.value
    .replace(/\s/g, '')
    .split('')
    .map(n => [n]);
  e.range
    .offset(0, 0, numbers.length, 1)
    .setValues(numbers)
    .offset(numbers.length, 0, 1, 1)
    .activate();
}

A: I am afraid that it is not possible to recognize what the users are typing until the edit is completely made. What you can do instead is to recognize if the value they have introduced is longer than 1 character and edit the cell by taking only the first character of what they introduce.
You can try the following script:
function onEdit(e) {
  var ss = e.source;
  var val = e.value;
  var r = e.range;

  if(val.length>1)
  {
    var x  = val.substring(0,1);
  }
  r.setValue(x);
}

References:

*

*Simple Triggers

*Event Objects

*setValue()


text:
Q: How to select files from a specific extension I would like to know how to select only a certain extension using file choose in AppleScript.
choose file of type {"png"} with multiple selections allowed
I've tried something like this but my files with the PNG extension can not be selected, and I want whatever else is done.

A: i solved, it was just put the name of the extension in the upper case.
choose file of type {"PNG"} with multiple selections allowed


text:
Q: How to pass member function as argument in python? I want to pass something similar to a member function pointer. I tried the following.
class dummy:
    def func1(self,name):
        print 'hello %s' % name
    def func2(self,name):
        print 'hi %s' % name

def greet(f,name):
    d = getSomeDummy()
    d.f(name)

greet(dummy.func1,'Bala')

Expected output is hello Bala

A: Since dummy is the class name, dummy.func1 is unbound.
As phihag said, you can create an instance of dummy to bind the method:
def greet(f,name):
    d = dummy()
    f(d, name)

greet(dummy.func1, 'Bala')

Alternatively, you can instantiate dummy outside of greet:
def greet(f,name):
    f(name)

my_dummy = dummy()

greet(my_dummy.func, 'Bala')

You could also use functools.partial:
from functools import partial

def greet(f,name):
    f(name)

my_dummy = dummy()

greet(partial(dummy.func1, my_dummy), 'Bala')

A: dummy.func1 is unbound, and therefore simply takes an explicit self argument:
def greet(f,name):
    d = dummy()
    f(d, name)

greet(dummy.func1,'Bala')

A: You can use something like this:
class dummy:
  def func1(self,name):
      print 'hello %s' % name
  def func2(self,name):
      print 'hi %s' % name
def greet(name):
  d = dummy()
  d.func1(name)
greet('Bala')

and this works perfectly: on codepad


text:
Q: React deleted nextJS and can't build connection I have deleted NextJS from my dependencies, deleted the nextjsconfig file and also reinstalled the node modules again. I also added the App.js and index.js file again to the source directory.
As I am trying to start the app - My browser tells me, that I Can't build a connection to localhost:3000.
I am also using Docker.
Anyone an idea?
Very best regards
Michael


text:
Q: Create Offline Installation of Visual C++ Build Tools 2019 for Rust I am trying to install Rust on an offline machine and it needs me to install Visual C++ Build Tools 2019:

I am now trying to install Visual C++ build tools offline but I am having trouble. On an online machine, I can download the files with:
vs_buildtools__aa90d186.7874.4cfb.a00e.95c80b36e650.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --add Microsoft.VisualStudio.Component.Windows10SDK.19041 --add Microsoft.VisualStudio.Workload.VCTools --layout "Z:\Visual Studio Build Tools\offline_build_tool" --lang en-us
And then install it by moving the files to the offline computer and running the vs_buildtools exe file it creates. However, even after restarting the offline machine once I have installed it offline, Rust still gives me the exact same error. So clearly I am missing some components, but I don't know what.
Can you please help me figure out which components my download command is missing? I feel like I have tried everything and it still doesn't work. I don't understand what's missing.


text:
Q: Mysql LOAD DATA IN FILE discard file like Oracle Sql Loader does I have to load several CSVs into some tables with Mysql LOAD DATA IN FILE, and I want to save discard records that could not be loaded (Because failed FKs, duplicates, etc.) in a discard file, such as Oracle SQL loader does
Any suggestion?
Thanks!

A: You can import data easily using MySQL WorkBench using import wizard through CSV.  It has the option to import all the data and create new table. From there you can alter the tables later on or make necessary indexes as needed, or change dataTypes on the go.
Another option is to use LOAD DATA commands as usual. Import data to a newly created tables without the foreign keys. You can target csv columns to specific table columns as well. see  https://dev.mysql.com/doc/refman/8.0/en/load-data.html


text:
Q: Post string from javascript code to ApiController on server I start to play with ASP.NET Web API. I am wondering with serialization feature when I get my entity in the Controler like next:
public class EntitiesController : ApiController
{
    [Queryable]
    public IEnumerable<Entity> Get()
    {
        return m_repository.GetAll();
    }
    public HttpResponseMessage Post(Entity entity)
    {
        if (ModelState.IsValid)
        {
            m_repository.Post(entity);
            var response = Request.CreateResponse<Entity>(HttpStatusCode.Created, entity);
            return response;
        }
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
}

and on the JavaScript side:
// create new entity.
$.post("api/entities", $(formElement).serialize(), "json")
    .done(function (newEntity) { self.contacts.push(newEntity); });

But I don't need entity. I want to receive string. So I've changed controller in the next manner:
public class EntitiesController : ApiController
{
    [Queryable]
    public IEnumerable<string> Get()
    {
        return m_repository.GetAll();
    }
    public HttpResponseMessage Post(string entity)
    {
        if (ModelState.IsValid)
        {
            m_repository.Post(entity);
            var response = Request.CreateResponse<Entity>(HttpStatusCode.Created, entity);
            return response;
        }
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
}

I tried to different dataType ("json", "text", "html") for post function. and different data representation $(formElement).serialize(), "simple Text", jsonObject, JSON.stringify(jsonObject). But I always get null on server side as entity parameter in the Post action.
What am I doing wrong?

A: If you want to post your form data as a string you need to do two things:
By default, Web API tries to get simple types like int, string etc. from the request URI. You need to use FromBody attribute tells Web API to read the value from the request body:
public HttpResponseMessage Post([FromBody]string entity)
{
   //...
}

And you need to post your value with an empty key:
$.post("api/entities", { "": $(formElement).serialize() }, "json")
    .done(function (newEntity) { self.contacts.push(newEntity); });

You can read more about this Web.API tutorial article: Sending HTML Form Data

A: Could you post the HTML for the form that you're using with serialize?  I'm guessing you're missing the name attribute from the particular element you are selecting.
As for the AJAX request, I tend to use the "perfect ajax request" template by Kyle Schaeffer; It's more readable and allows for better result handling IMHO, at least in older versions of jQuery.
$.ajax({
  type: 'POST',
  url: 'api/entities',
  data: { postVar1: 'theValue1', postVar2: 'theValue2' },
  beforeSend:function(){
  },
  success:function(data){
  },
  error:function(){
  }
});

Refer to: http://kyleschaeffer.com/development/the-perfect-jquery-ajax-request/

A: Try
$.ajax({
  type: 'POST',
  url: 'api/entities',
   traditional: true,

.....


text:
Q: Dispatching event doesn't fire :( package com.fladev.background
{
    //import all classes
    import caurina.transitions.Tweener;
    import flash.display.Loader;
    import flash.display.LoaderInfo;
    import flash.display.MovieClip;
    import flash.display.Sprite;
    import flash.display.DisplayObject;
    import flash.display.StageAlign;
    import flash.display.StageDisplayState;
    import flash.display.StageScaleMode;
    import flash.events.Event;
    import flash.events.FullScreenEvent;
    import flash.events.MouseEvent;
    import flash.net.URLLoader;
    import flash.net.URLRequest;

public class MainClass extends Sprite
{
    //create variables
    private var loaderMenu:Loader;
    private var loaderNames:Array = new Array ();
    private var loaderContents:Array = new Array ();
    private var loaderSlide:Loader;
    private var swfDisplayObject:DisplayObject;
    private var swfComObject:Object;
    private var xmlLoader:URLLoader = new URLLoader();
    private var xmlSlideLoader:URLLoader = new URLLoader();

    public function MainClass()
    {
        stage.align = StageAlign.TOP_LEFT;
        stage.scaleMode = StageScaleMode.NO_SCALE;
        stage.addEventListener(Event.RESIZE, stageResize);

        xmlLoader.addEventListener(Event.COMPLETE, showXML);
        xmlLoader.load(new URLRequest("navigation.xml"));

        //xmlSlideLoader.addEventListener(Event.COMPLETE, showSlideXML);
        //xmlSlideLoader.load(new URLRequest("slides.xml"));
    }

    function showXML(e:Event):void
    {
        XML.ignoreWhitespace = true;

        var menuBtns:XML = new XML(e.target.data);
        var i:Number = 0;

        for ( i = 0; i < menuBtns.navItem.length(); i++ )
        {
            loaderMenu = new Loader();
            loaderMenu.name = menuBtns.navItem[i].name ;
            loaderMenu.load(new URLRequest(menuBtns.navItem[i].swfURL));
            loaderMenu.contentLoaderInfo.addEventListener(Event.COMPLETE, createSwfObjects);
        }
    }

    private function createSwfObjects(event:Event):void
    {
        var swfContent = event.currentTarget.content as MovieClip ;
        var swfName = event.currentTarget.loader ;

        navigationContainer.addChild(event.target.loader);
        showImage(swfContent);

        if ( swfName.name == 'topNavigation' )
        {
            swfContent.addEventListener("clickHandle",topNavigationClickHandler);
        }
    }

    private function topNavigationClickHandler():void
    {
        trace('Back to root');
    }

    private function showImage(navigationItem):void
    {
        try
            {
                navigationItem.alpha = 0;
                Tweener.addTween(navigationItem, { alpha:1, time:1, transition:"easeOutSine" } );
                navigationItem.smoothing = true;

            } catch (e:Error) { trace('Error no tweening'); };

        stageResize();
    }

    private function stageResize(e:Event=null):void
    {
        var centerImages:Array = new Array ( contentContainer, navigationContainer, backgroundImage ) ;

        backgroundImage.x = 0;
        backgroundImage.y = 0;
        backgroundImage.scaleX = backgroundImage.scaleY = 1;

        if ((stage.stageHeight / stage.stageWidth) < backgroundImage.height / backgroundImage.width) {
            backgroundImage.width = stage.stageWidth;
            backgroundImage.scaleY = backgroundImage.scaleX;
        } else {
            backgroundImage.height = stage.stageHeight;
            backgroundImage.scaleX = backgroundImage.scaleY;
        }

        for each ( var centered:MovieClip in centerImages )
        {
            centered.x = stage.stageWidth / 2 - centered.width / 2;
            centered.y = stage.stageHeight / 2 - centered.height / 2;
        }
    }
}
}

This is my code for the main.as.
And here my code for my loaded SWF on the maintimeline.
addEventListener(Event.ADDED_TO_STAGE, init);

function init(event:Event):void
{
    trace('try dispatch');
    dispatchEvent(new Event("clickHandle",true));
}

Try dispatch works, but it does not get back to the main to fire up "Back to root".
Any idea?
thx!

A: As long as all movieclips dispatching events are added to the display list, this should work. This makes me think that perhaps the event listener being added is not working. Try adding a trace statement to the block of code as shown below:
if ( swfName.name == 'topNavigation' )
{
     trace("adding listener");
     swfContent.addEventListener("clickHandle",topNavigationClickHandler);
}

I expect that this if condition is failing, and thus your listener is never being created. Also, you need to add a function parameter to the callback method "topNavigationClickHandler" to accept the event as the callback parameter. You have not done this, and this is an error that would be thrown at runtime when the event was received and dispatched to the callback method. You havn't seen this yet because your listener has never had to invoke the callback. So you're gonna have to fix this code like so:
private function topNavigationClickHandler(e:Event):void
{
    trace('Back to root');
}

Also I just want to add that your if condition on setting this listener seems a bit redundant, since you already know you are expecting the navigation swf, because you're explicitly loading it. Also I don't believe the name property would be set like this. Typically the name is only set inside the IDE before compilation, and if it isn't, it gets dynamically generated at runtime. What might be more useful is to check the URL of the loaded SWF to see if it contains "topNavigation" or whatever the swf name is. You can do this like so:
var swfUrl:String = myLoader.contentLoaderInfo.url;
if (swfUrl.search("topNavigation") != -1){
   //Match found, add listener for navigation
}


text:
Q: RunLWC Function from Aura Parent Component I'm trying to run a method in my child component (LWC component) from my parent component (Aura Component) but the method is never run.
Parent (Aura Helper)
    const months = component.find("month");
    for(let i=0; i < months.length; i++){
        months[i].getAllDays();
    }

Child (Aura)
    @api
    getAllDays(){
        console.log('Check');
    }

The components "month" are found. I can get attributes if I do:
months[i].get("v.myVar");

I can't run exposed functions.
Have you any ideas ?
EDIT
The problem is that my parent component initialization is faster than my child component loading and it can't run the function. My syntax is good

A: The problem is that my parent component initialization is faster than my child component loading and it can't run the function. My syntax is good


text: Q: How to check whether the geofence is already created or not in the device? If it is not need to add the geofence in my android app? I have tried to check whether the geofence event is already created or not.How to check geofence already created in the device or not?


text:
Q: Update SQL record from Excel I am trying to build a quotation sheet for our sales staff. I need to read a field from a SQL record, use that quote number for the spreadsheet, add one to it, and then update the SQL record to the incremented number.
Reading the data is easy, pushing an update to a single field in a specific record is the hard part.
Anyone done this before?
Some of you have suggested ways of exporting to CSV, and then importing. That is not what I am looking to do here. What I want is an interactive spreadsheet that retrieves, and then dynamically updates the SQL table record. I need this to require no user interaction.

A: export the data from excel as a CSV. Then create a temporary table with it and use that to get the info you need and then export that information to your "real" table.
CREATE TEMPORARY TABLE temp LIKE real_table;

LOAD DATA INFILE 'file.csv'
INTO TABLE temp
FIELDS TERMINATED BY ','
(list, values, here);

UPDATE real_table
INNER JOIN temp on temp.id = temp.id
SET real_table.value = temp.value;

DROP TEMPORARY TABLE temp;