text:
Q: Can I do this in SQL function without a cursor? I'm working on a timesheet database.  In simple terms, the TimesheetEntries table has four columns
ID int (identity, 1, 1)
StaffID int
ClockedIn datetime
ClockedOut datetime

I've been asked to write a report to show staff attendance by date range.  The user puts in a date, and the report outputs the clocking in and out times of all attending staff members together with their duration on-site.
However, and this is where it gets tricky, staff members sometimes clock out to leave the site for short periods, and the report is required to ignore these (when they leave the site for less than 2 hours).
So, let's assume the following entries
ID  StaffID  ClockedIn    ClockedOut
1   4        0900         1200
2   4        1330         1730
3   5        0900         1200
4   5        1409         1730
5   4        1830         1930

The report's output SHOULD be
StaffID  ClockedIn    ClockedOut
4        0900         1930
5        0900         1200
5        1409         1730

Is there any way of doing this without a cursor or even a cursor nested inside a cursor (which is where I'm at right now!)?  We're not talking about huge datasets here and performance isn't really an issue (it's a report, not a production system) but I really don't like cursors if I can avoid them.
Thanks
Edward

A: I'm sure there's less complicated ways to do this, but I was able to pull it off with a couple of CTEs:
declare @TimeSheetEntries table
    (
    ID int identity not null primary key,
    StaffID int not null,
    ClockedIn datetime not null,
    ClockedOut datetime not null
    );

insert into @TimeSheetEntries
    (
    StaffID,
    ClockedIn,
    ClockedOut
    )
select
    4,
    '2012-01-01 09:00:00',
    '2012-01-01 12:00:00'
union all select
    4,
    '2012-01-01 13:30:00',
    '2012-01-01 17:30:00'
union all select
    5,
    '2012-01-01 09:00:00',
    '2012-01-01 12:00:00'
union all select
    5,
    '2012-01-01 14:09:00',
    '2012-01-01 17:30:00'
union all select
    4,
    '2012-01-01 18:30:00',
    '2012-01-01 19:30:00'
;
with MultiCheckins as (
    select distinct
        StaffID,
        cast(cast(cast(ClockedIn as float) as int) as datetime) as TimeSheetDate,
        rank() over (
            partition by StaffID,
            cast(cast(cast(ClockedIn as float) as int) as datetime)
            order by ClockedIn
            ) as ordinal,
        ClockedIn,
        ClockedOut
    from @TimeSheetEntries
), Organized as
(
select
    row_number() over (
        order by
            mc.StaffID,
            mc.TimeSheetDate,
            mc.ClockedIn,
            mc.ClockedOut
            ) as RowID,
    mc.StaffID,
    mc.TimeSheetDate,
    case
        when datediff(hour, coalesce(mc3.ClockedOut, mc.ClockedIn), mc.ClockedIn) >= 2
            then mc.ClockedIn
        else coalesce(mc3.ClockedIn, mc.ClockedIn)
        end as ClockedIn,
    case
        when datediff(hour, mc.ClockedOut, coalesce(mc2.ClockedIn, mc.ClockedOut)) < 2
            then coalesce(mc2.ClockedOut, mc.ClockedOut)
        else mc.ClockedOut
        end as ClockedOut
from
    MultiCheckins as mc
left outer join
    MultiCheckIns as mc3
        on mc3.StaffID = mc.StaffID
        and mc3.TimeSheetDate = mc.TimeSheetDate
        and mc3.ordinal =  mc.ordinal - 1
left outer join
    MultiCheckIns as mc2
        on mc2.StaffID = mc.StaffID
        and mc2.TimeSheetDate = mc.TimeSheetDate
        and mc2.ordinal = mc.ordinal + 1
)
select distinct
    o.StaffID,
    o.ClockedIn,
    o.ClockedOut
from Organized as o
where
    not exists (
        select null from Organized as o2
        where o2.RowID <> o.RowID
        and o2.StaffID = o.StaffID
        and
            (
            o.ClockedIn between o2.ClockedIn and o2.ClockedOut
            and o.ClockedOut between o2.ClockedIn and o2.ClockedOut
            )
        )

A: I used the data from Jeremy's response above but went at the problem a whole different way. This uses a recursive CTE, which I think requires SQL Server 2005. It reports the results accurately (I believe) and also reports the number of clock-ins recorded during the timeframe and the total number of minutes off (can be more than 120 because the restriction is simply that each offsite period is less than two hours).
declare @TimeSheetEntries table
    (
    ID int identity not null primary key,
    StaffID int not null,
    ClockedIn datetime not null,
    ClockedOut datetime not null
    );

insert into @TimeSheetEntries
    (
    StaffID,
    ClockedIn,
    ClockedOut
    )
select
    4,
    '2012-01-01 09:00:00',
    '2012-01-01 12:00:00'
union all select
    4,
    '2012-01-01 13:30:00',
    '2012-01-01 17:30:00'
union all select
    5,
    '2012-01-01 09:00:00',
    '2012-01-01 12:00:00'
union all select
    5,
    '2012-01-01 14:09:00',
    '2012-01-01 17:30:00'
union all select
    4,
    '2012-01-01 18:30:00',
    '2012-01-01 19:30:00';

WITH ClockData AS
(
    SELECT ID, StaffID, ClockedIn, ClockedOut AS EffectiveClockout, 1 AS NumClockIns, 0 AS MinutesOff
    FROM @TimeSheetEntries ts
    WHERE NOT EXISTS (SELECT ID FROM @TimeSheetEntries tsWhere WHERE tsWhere.ClockedOut BETWEEN DATEADD(hour, -2, ts.ClockedIn) AND ts.ClockedIn)

    UNION ALL

    SELECT cd.ID, cd.StaffID, cd.ClockedIn, ts.ClockedOut AS EffectiveClockout, cd.NumClockIns + 1 AS NumClockIns, cd.MinutesOff + DateDiff(minute, cd.EffectiveClockout, ts.ClockedIn) AS MinutesOff
    FROM @TimeSheetEntries ts
    INNER JOIN ClockData cd
        ON ts.StaffID = cd.StaffID
            AND ts.ClockedIn BETWEEN cd.EffectiveClockout AND dateadd(hour, 2, cd.EffectiveClockout)
)
SELECT *
FROM ClockData cd
WHERE NumClockIns = (SELECT MAX(NumClockIns) FROM ClockData WHERE ID = cd.ID)

This returns:
ID   StaffID   ClockedIn                 EffectiveClockout        NumClockIns   MinutesOff
3    5         2012-01-01 09:00:00.000   2012-01-01 12:00:00.000  1             0
4    5         2012-01-01 14:09:00.000   2012-01-01 17:30:00.000  1             0
1    4         2012-01-01 09:00:00.000   2012-01-01 19:30:00.000  3             150

UPDATE
In case it isn't clear, the MinutesOff is only the 'allowance' time, or the amount of time 'eaten' between the ClockedIn and EffectiveClockout shown in the same row. So, StaffID 5 took 129 minutes off between clocked time periods, but no allowance time, so MinutesOff is 0 for both rows.

A: Option 1 :
Maybe insert it into a temp table and then use a left join to build a results table (if they can only clock in and out twice during the day this will work if you have 3 results it will not)
select *
from timesheet ts
left join timesheet tss on tss.id = ts.id

After this you can just get the min and max or even have a more robust report.
Option 2 :
create #TimeTable Table (UserID int, InTime int, OutTime int)

insert into #TimeTable (UserID) select distinct StaffID

Update #TimeTable set InTime = (select Min(InTime) from #TimeTable where StaffID = s.StaffID)  from #TimeTAble s

Update #TimeTable set OutTime = (Select Max(OutTime) from #TimeTable where StaffID = s.StaffID) from #TimeTable s

Given mroe time i'd merge these into two quick queries but three would work for not worrying about performance.

A: An iterative set-based approach:
-- Sample data.
declare @TimesheetEntries as Table ( Id Int Identity, StaffId Int, ClockIn DateTime, ClockOut DateTime )
insert into @TimesheetEntries ( StaffId, ClockIn, ClockOut ) values
  ( 4, '2012-05-03 09:00', '2012-05-03 12:00' ),
  ( 4, '2012-05-03 13:30', '2012-05-03 17:30' ), -- This falls within 2 hours of the next two rows.
  ( 4, '2012-05-03 17:35', '2012-05-03 18:00' ),
  ( 4, '2012-05-03 19:00', '2012-05-03 19:30' ),
  ( 4, '2012-05-03 19:45', '2012-05-03 20:00' ),
  ( 5, '2012-05-03 09:00', '2012-05-03 12:00' ),
  ( 5, '2012-05-03 14:09', '2012-05-03 17:30' ),
  ( 6, '2012-05-03 09:00', '2012-05-03 12:00' ),
  ( 6, '2012-05-03 13:00', '2012-05-03 17:00' )
select Id, StaffId, ClockIn, ClockOut from @TimesheetEntries

-- Find all of the periods that need to be coalesced and start the process.
declare @Bar as Table ( Id Int Identity, StaffId Int, ClockIn DateTime, ClockOut DateTime )
insert into @Bar
  select TSl.StaffId, TSl.ClockIn, TSr.ClockOut
    from @TimesheetEntries as TSl inner join
      -- The same staff member and the end of the left period is within two hours of the start of the right period.
      @TimesheetEntries as TSr on TSr.StaffId = TSl.StaffId and DateDiff( ss, TSl.ClockOut, TSr.ClockIn ) between 0 and 7200

-- Continue coalescing periods until we run out of work.
declare @Changed as Bit = 1
while @Changed = 1
  begin
  set @Changed = 0
  -- Coalesce periods.
  update Bl
    -- Take the later   ClockOut   time from the two rows.
    set ClockOut = case when Br.ClockOut >= Bl.ClockOut then Br.ClockOut else Bl.ClockOut end
    from @Bar as Bl inner join
      @Bar as Br on Br.StaffId = Bl.StaffId and
        -- The left row started before the right and either the right period is completely contained in the left or the right period starts within two hours of the end of the left.
        Bl.ClockIn < Br.ClockIn and ( Br.ClockOut <= Bl.ClockOut or DateDiff( ss, Bl.ClockOut, Br.ClockIn ) < 7200 )
  if @@RowCount > 0
    set @Changed = 1
  -- Delete rows where one period is completely contained in another.
  delete Br
    from @Bar as Bl inner join
      @Bar as Br on Br.StaffId = Bl.StaffId and
        ( ( Bl.ClockIn < Br.ClockIn and Br.ClockOut <= Bl.ClockOut ) or ( Bl.ClockIn <= Br.ClockIn and Br.ClockOut < Bl.ClockOut ) )
  if @@RowCount > 0
    set @Changed = 1
  end

-- Return all of the coalesced periods ...
select StaffId, ClockIn, ClockOut, 'Coalesced Periods' as [Type]
  from @Bar
union all
-- ... and all of the independent periods.
select StaffId, ClockIn, ClockOut, 'Independent Period'
  from @TimesheetEntries as TS
  where not exists ( select 42 from @Bar where StaffId = TS.StaffId and ClockIn <= TS.ClockIn and TS.ClockOut <= ClockOut )
order by ClockIn, StaffId

I'm sure that there are some optimizations that ought to be made.

A: I think you can do this pretty easily with just a left join back to itself and a one-off match. The following is not a full implementation, but more of a proof of concept:
create table #TimeSheetEntries
    (
    ID int identity not null primary key,
    StaffID int not null,
    ClockedIn datetime not null,
    ClockedOut datetime not null
    );

insert into #TimeSheetEntries
    (
    StaffID,
    ClockedIn,
    ClockedOut
    )
select
    4,
    '2012-01-01 09:00:00',
    '2012-01-01 12:00:00'
union all select
    4,
    '2012-01-01 13:30:00',
    '2012-01-01 17:30:00'
union all select
    5,
    '2012-01-01 09:00:00',
    '2012-01-01 12:00:00'
union all select
    5,
    '2012-01-01 14:09:00',
    '2012-01-01 17:30:00'
union all select
    4,
    '2012-01-01 18:30:00',
    '2012-01-01 19:30:00'
union all select 4, '2012-01-01 18:30:00', '2012-01-01 19:30:00';

select * from #timesheetentries tse1
left outer join #timesheetentries tse2 on tse1.staffid = tse2.staffid
  and tse2.id =
  (
      select MAX(ID)
      from #timesheetentries ts_max
      where ts_max.id < tse1.id and tse1.staffid = ts_max.staffid
  )
  outer apply
  (
  select DATEDIFF(minute, tse2.clockedout, tse1.clockedin) as BreakTime
  ) as breakCheck

where BreakTime > 120 or BreakTime < 0 or tse2.id is null

order by tse1.StaffID, tse1.ClockedIn

   GO
   drop table #timesheetentries
   GO

The idea here is that you have your original timesheet table tse1, and then you do a left join to the same timesheet table, aliased as tse2 and matching rows when staffID is the same and tse2.ID is the highest ID value that is still less than tse1.ID. This is clearly poor form - you'd probably want to use ROW_NUMBER() for this ID comparison, partitioned and ordered by StaffID and your ClockedIn/ClockedOut values, since times could have been input out of chronological order.
At this point, a row from the joined tables now contains time data from the current timesheet entry, as well as the one before it. This means that we can make a comparison between ClockedIn/ClockedOut values for consecutive time entries... and using DATEDIFF(), we can find out the length of time that a user has been away between their previous Clockedout and more recent ClockedIn values. I used an OUTER APPLY for this simply because it makes the code cleaner, but you could probably pack it into a subquery.
Once we do a DATEDIFF(), it's trivial to find cases where an individual's BreakTime does not exceed the 120-minute barrier and remove those timesheet entries, leaving only the significant rows of the employee's timesheet to be used in your later reporting.


text:
Q: Recursively running a for loop within a for loop (python) I'm new to python and had the idea of trying to use it to solve the numbers game on the TV show countdown. (rules for those unfamiliar). I googled and it turns out this has been done before - But I didn't understand the code properly and then thought why not just give it a go myself. I have searched and there are other people looking for recursive solutions but I couldn't get them to work for my example (Apologies, I am very new to this after all).
What I'm trying to do is to take a list of numbers, then loop through applying operations to pairs of them and replacing that pair with the output. This would repeat recursively until either we find the number we are looking for, or the list of numbers is reduced to size 1.
My function "single_move_generator" is a generator producing tuples of the form ((a,b,operation), answer, numbers left to use). I want to feed this final part of the tuple back into the function as the new list, but also keep track of the first part as it is the 'history' of how we achieved our answer. At the moment I have the following:
target = 155
numbers_to_use = [6, 25, 3, 2]
for a in single_move_generator(numbers):
    if a[1] == target:
        print(a[0])
    for b in single_move_generator(a[2]):
        if b[1] == target:
                print(a[0],b[0])
                quit()
        for c in single_move_generator(b[2]):
                if c[1] == target:
                    print(a[0],b[0],c[0])
                    quit()

produces:
(25, 6, 'add') (3, 2, 'add') (31, 5, 'multiply')

But I'd like to able to give it a larger list of numbers and have it just continue until the list reaches size one. I suspect I need a while loop - but this attempt doesn't work. It doesn't find the target or keep track of the history of moves.
numbers_available = numbers
while len(numbers_available) >1 and target not in numbers_available:

    for a in single_move_generator(numbers_available):
        if a[1] == target:
            print("Target Found", a)
            break

    numbers_available = a[2]

numbers_available = a[2]

I feel like there must be a pythonic way of doing this which is far neater than I've done - any hints would be greatly appreciated. Thanks!

A: Based on your idea of using tuples (i, j, operation), I wrote the following. This is a recursive solution, as the main function calls itself back.
from itertools import combinations, product

def check_operation(i, j, operation):
    """
    Check whether 'i operation j' is permitted.
    """
    if operation == '/' and j == 0:
        return False
    elif operation == '/' and i%j != 0:
        return False
    # if not playing with negative values
    #elif operation == '-' and i-j < 0:
    #    return False
    else:
        return True

def countdown(target, numbers, trackback):
    if target in numbers:
        print trackback
    for possibility in product(combinations(numbers,2), ['+', '*', '/', '-']):
        new_numbers = [k for k in numbers] # copy list, use list.copy in python 3
        i, j = possibility[0][0], possibility[0][1]
        operation = possibility[1]
        new_numbers.remove(i)
        new_numbers.remove(j)
        if not check_operation(i, j, operation):
            continue
        new_numbers.append(eval('%i%s%i' % (i, operation, j)))
        countdown(target, new_numbers, trackback+[possibility])

countdown(155, [6, 25, 3, 2], [])

It only works if a solution exists, since it won't intend to get as close to the solution as possible. However it will return all the solutions, not only one.

A: Based on what you posted, this should work for you:
def solve(numbers, target):
  for op, res, nums in single_move_generator(numbers):
    if res == target:
      return [op]
    ops = solve(nums, target)
    if ops:
      return [op] + ops

print(*solve(numbers_to_use, target))

It should be equivalent to the nested for loop you posted.
Bottom of the recursion is hit when res == target. Python functions return None by default, so if a recursive call to solve returned a truthy value then it must have hit the target. ops will contain the last operation if it was the bottom of the recursion. It is then appended to the operation that launched the recursive call and returned to an upper level. So the function will return all operations at the top level.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is the finding trace of the Riemann tensor the same thing as contracting two indices? To form the Ricci curvature tensor, we have to take the trace of the Riemann tensor. But I also know
\begin{equation}
R_{ij} := R_{kij}^{\phantom{kij}k}
\end{equation}
Can someone show me why taking the trace is the same thing as contracting indices?

A: Consider the following matrix
\begin{equation}
A =
\begin{bmatrix}
a & b & c \\
d & e & f \\
g & h & i \\
\end{bmatrix}
\end{equation}
By definition, the trace of $A$ is defined as
\begin{equation}
\text{tr}(A) = a + e + i = a_{11} + a_{22} + a_{33}
\end{equation}
So think about how we write tensor indices. If I have a tensor $a_{ij}$ and I contract one index to get $a_i^i$, now both indices have the same value. So for all values of $i$ in this case we would have $a_1^1$, $a_2^2$, $a_3^3$, which corresponds to $a$,$e$,$i$.
Thus, contracting indices gives the same value as taking the trace.


text:
Q: Trying typescript monobuild and last step fails following simple blog article My yarn -v yield v1.22.15
The steps for reproducing the error below are pretty simple.

*

*git clone git@github.com:ahoopen/typescript-mono-repo.git

*cd typescript-mono-repo

*yarn install

*yarn build

Failure ->
dean@Deans-MBP typescript-mono-repo % yarn build
yarn run v1.22.15
$ lerna run build --stream
lerna notice cli v3.22.1
lerna info versioning independent
lerna info Executing command in 3 packages: "yarn run build"
@ahoopen/core: $ yarn clean && tsc --build && cp "./package.json" ./dist/
@ahoopen/utils: $ yarn clean && tsc --build && cp "./package.json" ./dist/
@ahoopen/core: $ rimraf dist && rimraf tsconfig.tsbuildinfo
@ahoopen/utils: $ rimraf dist && rimraf tsconfig.tsbuildinfo
@ahoopen/web: $ yarn clean && tsc --build && cp "./package.json" ./dist/
@ahoopen/web: $ rimraf dist && rimraf tsconfig.tsbuildinfo
@ahoopen/web: src/add.ts(1,31): error TS2307: Cannot find module '@ahoopen/utils' or its corresponding type declarations.
@ahoopen/web: error Command failed with exit code 1.
@ahoopen/web: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
lerna ERR! yarn run build exited 1 in '@ahoopen/web'
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
dean@Deans-MBP typescript-mono-repo %

Any idea what I can do to make this work?. I am pretty new to typescript & yarn workspaces (ie. very new).


text:
Q: Print triangle shape with star symbol I wonder how do I show my kids how to print a triangle shape with basic symbol.
I started with this code

for (i = 1; i <= 5; i++) {
  const strs = []
  for (j = 0; j < i; j++) {
    strs.push('*')
  }
  console.log(strs.join(''))
}

But I want to get
  *
 **
 ***
****
*****

or worst case skip the non-formatting row,
  *

 ***

*****

A: This is how you can achieve your goal
var spaces = "  ";
for (i = 1; i <= 5; i++) {
  if (i % 2 == 1) spaces = spaces.substring(0, spaces.length - 1);
  const strs = []
  for (j = 0; j < i; j++) {
    strs.push('*')
  }
  console.log(spaces + strs.join(''))
}

Even better if you ask me:
for (i = 1; i <= 5; i++) {
  var strs = []
  for (j = 0; j < i; j++) {
    strs.push('*')
  }
  j = 5 - j;
  strs = strs.join("");
  while (j-- > 0) strs = " " + strs;
  console.log(strs)
}

Or even much, much better:
var spaces = "    ";
for (i = 1; i <= 5; i++) {
  const strs = []
  for (j = 0; j < i; j++) {
    strs.push('* ')
  }
  console.log(spaces + strs.join(''))
  spaces = spaces.substring(0, spaces.length - 1);
}

A: I just wrote an algo,
int starBase = N;

for(int i=0; i<N; i++){
    // print prefix spaces (formating)
    for(int k=0; k<(i-N);k++){
        print(" ");
    }

    // print *
    for(int j=0; j<i;j++){
        print("* ");
    }

    // new line
    print ("\n")
}

with N=5
your should work look like this.
its just a pseudo code you may have to convert it to your prefered langauge.
0
1     *
2    * *
3   * * *
4  * * * *

A: for (i = 1; i <= 5; i++) {
const strs = []
for(x=1;x <= 2-i; x++){
strs.push(' ')
}
for (j = 0; j < i; j++) {
strs.push('*')
}
console.log(strs.join(''))
}


text:
Q: How to make a table span two columns? I am making a two column document, but I have a large table that I want to make span the columns. How can I do this in Microsoft Word?
................................

              TABLE

................................
text text text    text text text
text text text    text text text
text text text    text text text
text text text    text text text

A: To insert a two column table paste the table at its desired location. MS Word will format the table in the column where you pasted it. So, if the table is too wide (the raison d'etre why spanning across two columns is desired), it will appear a bit distorted.
Then place the cursor before the table and insert a section break (continuous). Repeat this after placing the cursor after the table. Then select the contents of this section (i.e. just select the table). Don't fret if the section is not clearly demarcated from the rest of the document (if you prefer to see the section breaks, just press Ctrl+Shift8; the same combo to hide them).  Then convert the section to a single column layout. Your table should now span across two columns.
If you are unable to complete any step(s) mentioned in the previous paragraph, refer to the following links:

*

*Insert section break in MS Word

*Create two column layout

*See or hide section breaks

A: I think you can just drag the table to where you want it once you've created it. Or more formally try setting the table's position relative to the margin or page, rather than to the column. You will need to play with the wrapping too (probably set it to Around).

A: I faced similar situation. Google brought me to this forum, however, I do not think any of the solutions on this page are correct or complete. I see that this post is quite old but I would still like to share my solution, so that others may benefit from it.
I am using Microsoft Office 2016.

*

*First, I inserted a text box by going to Insert > Text Box

*Once the text box is on the document, I adjusted its width so that it meets my needs.
It spanned from column 1 to column 2 (roughly speaking, it was as wide as the page)

*Next, I could see the box is covering my text. To solve this, I selected the text box and went to  Layout > Wrap Text > Square
The beauty of this solution is that Text Box serves as an independent identity and any formatting changes made else where in the word document will not affect the text box

A: Select the whole table.
Select the Layout tab, click Columns, Two.
Optionally, select the header row.
Select the Layout tab and click Repeat Header Rows.

A: The latest suggestion was mostly useful, until I was trying to import some text reference (for scientific work) within the table. So I had to discard it and something strange just worked.
Step 1. On the last line before the table, press enter followed by section break.
Step 2. Select the whole table content by clicking the small cross-arrow sign that appears at the top left corner of the table.
Step 3. while the whole table is selected go to "page layout tab" under the "page setup" section press "columns" select "one" and that should do it.


text:
Q: Perl vs Sed regex substitue /(foo|bar)/ I'm hoping someone might explain why sed does not work where perl does for this issue:
$ egrep "(foo|bar)=0" /var/tmp/test.txt
This is example output of the test.txt file foo=0
This is another example output of the bar=0 test.txt file
$ sed -ir 's/(foo|bar)=0//g' /var/tmp/test.txt
$ egrep "(foo|bar)=0" /var/tmp/test.txt
This is example output of the test.txt file foo=0
This is another example output of the bar=0 test.txt file
$

Trying with perl the substitute works:
$ egrep "(foo|bar)=0" /var/tmp/test.txt
This is example output of the test.txt file foo=0
This is another example output of the bar=0 test.txt file
$ perl -ne 's/(foo|bar)=0//g;print;' -i /var/tmp/test.txt
$ egrep "(foo|bar)=0" /var/tmp/test.txt
$

Is there a way to make sed accomplish what perl's doing here?  Thank you kindly!

A: This is just a problem on the order of the arguments you provide to sed. Say sed -r -i and you will see it working.
When you say sed -ir you are setting in-place editing but NOT -r mode. Why? Because -r is understood as the parameter for -i, so that you end up having a file + r backup.

Full test:
$ sed -ir 's/(foo|bar)=0//g' file

file and filer are equal!
$ cat file
This is example output of the test.txt file foo=0
This is filenother example output of the bar=0 test.txt file
$ cat filer
This is example output of the test.txt file foo=0
This is filenother example output of the bar=0 test.txt file

Let's separate the parameters:
$ sed -i -r 's/(foo|bar)=0//g' file

Now it is fine, file doesn't have this content any more:
$ cat file
This is example output of the test.txt file
This is filenother example output of the  test.txt file


text:
Q: What is the conventional location to install binary executables? I would like to install a binary executable so that all users can run it from the terminal. Where should I put it?

A: /usr/local/bin/. It may already be in your path.


text:
Q: Suggestion regarding models I need your suggestion. I am creating a model named PlayList where user's can add songs and movies in his playlist.
 I've added a field name playlist_type. It will ask the user's is it song playlist or movies playlist? If it is song playlist so he can't add movies in playlist.
Ok. Now should I use ContenType or Should I create two more seperate models PlayListSong and PlayListMovies. What do you suggest? Thanks
class PlayList(TimeStampedModel):
    SONG_PLAYLIST = 1
    MOVIES_PLAYLIST = 2

    PLAYLIST_CHOICES = (
        (SONG_PLAYLIST, 'Songs'),
        (MOVIES_PLAYLIST, 'Movies'),
    )
    name = models.CharField(_('PlayList Name'), max_length=100)
    user = models.ForeignKey(User)
    playlist_type = models.IntegerField(choices=PLAYLIST_CHOICES)

class PlayListContentType(TimeStampedModel):
    playlist = models.ForeignKey(PlayList)
    content_type = models.ForeignKey(ContentType, related_name="likes")
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()

A: I think you are better off creating separate models, PlayListSong and PlayListMovies, that are inherited from the PlayList model.
If you go with the PlayListContentType model, you will likely have to perform an if/else check in every function you define that first determines what content_type you are dealing with before doing anything with it...
...for [a very simple] example:
class PlayListContentType(TimeStampledModel):
    // Attributes here.

    def get_favorite_movie(self):
      if self.content_type.name == "movie":
          // Get movie from playlist.
      else:
          // Return error message/exception/etc.

This is just one of the drawbacks that immediately comes to mind.  You can code/design around it - but if you are immediately forcing restrictions like this on yourself, then you are setting yourself up for failure down the road (what happens when you want to support a new content type?).


text:
Q: How do i calculate the size of a tag field? I'm revising for an exam and i've came across a question that I have no idea how to do, i've looked through my notes and cant seem to find anything on it, can anyone help me?
Given a 64KB cache that contains 1024 blocks with 64 bytes per block, what is the size of the tag field for a 32-bit architecture?
The question is only worth 1 mark so i cant imagine the answer is too hard, but i cant seem to find anthing on it.

A: You need 32 bits for the address. You need 6 bits for the offset within a block. You need 10 bits to identify one of the 1,024 possible blocks in the cache. That's 16 bits in total. Therefore the tag needs to be 32 bits - 16 bits = 16 bits.
I recommend following the link that aruisdante provided and look at how to calculate this yourself.


text:
Q: Find text in my tables, stored procedures, and views in SQL Server I am able to search for specific text in my views and stored procedure, but I'm not able to search through my tables at the same time.
Here is what I have:
DECLARE @cmd           VARCHAR(1000),
        @search_string VARCHAR(200)

CREATE TABLE #temp
(
    [Database_Name]     sysname,
    [Schema_Name]       sysname,
    [Object_Name]       sysname,
    [Object_Type]       nvarchar(60)
)

-- Set the search string
SET @search_string = 'text'

SET @cmd = 'INSERT INTO #temp SELECT DISTINCT ''?'', s.name AS Schema_Name, o.name AS Object_Name, o.type_desc FROM [?].sys.sql_modules m INNER JOIN [?].sys.objects o ON m.object_id = o.object_id INNER JOIN [?].sys.schemas s ON o.schema_id = s.schema_id WHERE m.definition Like ''%' + @search_string + '%'''

-- Uncomment the following if you have problems with your command and want to see the command
--PRINT @cmd

-- Run for every database on the server
EXEC sp_MSforeachdb @cmd

-- Retrieve your results from the temp table
SELECT *
FROM #temp
ORDER BY [Database_Name], [Object_Name], [Object_Type]

-- If you want to omit certain databases from your results, simply add
-- the appropriate WHERE clause, as in the following:
--SELECT *
--FROM #temp
--WHERE db NOT IN ('DB1', 'DB4', 'DB7')
--ORDER BY db, obj_type, obj_name

DROP TABLE #temp

A: Please try this query for column search
SELECT
    t.[name]    TableName
    , c.[name]  ColumnName
FROM sys.columns c
INNER JOIN sys.tables t on t.object_id = c.object_id
WHERE t.[type] = 'U'
AND c.[name] LIKE '%Text%'

Below script will get result for all the databases for both Tables and other obejcts.  Hope this will help.
DECLARE @command varchar(1000)
DECLARE @SearchWord VARCHAR(20) = 'Text'
CREATE TABLE #Search (DatabaseName VARCHAR(255),SchemaName VARCHAR(50),ObjectName VARCHAR(255),ObjectType VARCHAR(50))

SET @command = 'USE ? INSERT INTO #Search
                    SELECT DB_NAME(), SCHEMA_NAME(t.schema_id),t.[name] TableName, ''Table'' FROM sys.columns c INNER JOIN sys.tables t on t.object_id = c.object_id WHERE t.[type] = ''U'' AND c.[name] LIKE ' + '''%' + @SearchWord + '%'''
EXEC sp_MSforeachdb @command;

SET @command = 'USE ? INSERT INTO #Search
                SELECT DISTINCT DB_Name(),s.name AS Schema_Name, o.name AS Object_Name, o.type_desc FROM sys.sql_modules m INNER JOIN sys.objects o ON m.object_id = o.object_id INNER JOIN sys.schemas s ON o.schema_id = s.schema_id WHERE m.definition Like ''%' + @SearchWord + '%'''
EXEC sp_MSforeachdb @command
SELECT * FROM #Search;
DROP TABLE #Search

A: There is an easy way
select
 object= object_name(c.id), o.name , o.type
from sys.syscomments as c
join sys.objects as o on c.id = o.object_id
where c.text like '%Id%'

All compiled objects are in sys.comments, the name changed a few times depending on the version of SQL you have, the sample is from the current version.
Now, one doesn't need to join sys.object as the TSQL is in the text column.
You can look for any string that you have used, table names, field names or code comments. the sample shows %ID% looking for all function, trigger, views procedures that have something that contains the letters ID.
You know that when clicking on an object in SSMS you can select show Dependencies right?


text:
Q: What is the search function called when i press the windows key on my laptop? I'm on Ubuntu 21.10, and I'm just wondering, when I press the Windows key on my laptop, it brings up a search window where I can search my entire computer. Does this search have a name? What do we call it?
thank you

A: It's called the "Activities overview" (https://help.gnome.org/users/gnome-help/stable/shell-introduction.html#activities). This includes the Exposé-style window grid, the workspace switcher, and the system search.


text:
Q: Ruby on rails installation error in windows 7 rails new my_app is throwing following error
An error occurred while installing rake 0.9.2.2 and bundle can not continue. Make sure that  gem install rake -v '0.9.2.2' succeeds before bundling.

I've installed latest version of Ruby on Rails in window 7.

A: use rails new my_project to generate your project. also run rails -v to ensure rails is installed


text:
Q: JavaFX launch inner Application class I am trying to launch an inner Application class from the enclosing class, which does not work.
I already tried removing the static modifier from Window and launching it from an instance of Main.
Code:
import javafx.application.Application;
import javafx.stage.Stage;

public class Main {
    private static class Window extends Application {
        @Override
        public void start(Stage stage) {
            stage.show();
        }
    }

    public static void main(String args[]) {
        Application.launch(Window.class, args);
    }
}

Exception:
Exception in Application constructor
Exception in thread "main" java.lang.RuntimeException: Unable to construct Application instance: class VirtualLaunchpad$Window
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:907)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$1(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NoSuchMethodException: VirtualLaunchpad$Window.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getConstructor(Class.java:1825)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$7(LauncherImpl.java:818)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$null$5(GtkApplication.java:139)
    ... 1 more

A: The Application subclass (and its no-arg constructor) must be public. The Application.launch() method only searches for public no-arg constructors when it instantiates the application class by reflection.
import javafx.application.Application;
import javafx.stage.Stage;

public class Main {
    public static class Window extends Application {
        @Override
        public void start(Stage stage) {
            stage.show();
        }
    }

    public static void main(String args[]) {
        Application.launch(Window.class, args);
    }
}


text:
Q: How to extract all 2nd level values (leaf nodes) from a 2-dimensional array and join with commas? How can I get the list of values from my array:
[data] => Array
        (
            [5] => Array
                (
                    [0] => 19
                    [1] => 18
                    [2] => 20
                )

            [6] => Array
                (
                    [0] => 28
                )

        )

Expected output result string will be: 19,18,20,28
Thanks!

A: Use following php code:
$temp = array();
foreach($data as $k=>$v){
    if(is_array($v)){
        foreach($v as $key=>$value){
            $temp[] = $value;
        }
    }
}
echo implode(',',$temp);

A: With one line, no loop.
echo implode(',', call_user_func_array('array_merge', $data));

Try it here.

A: try with this..
foreach($data as $dataArr){
    foreach ($subArray as $value) {
        $res[] = $value;
    }
}
echo implode(',', $res);

A: Use following code.
$string = '';
foreach($yourarray as $k){
  foreach($k as $l){
     $string. = $l.",";
  }
}

A: Just loop over sub arrays. Store values to $result array and then implode with ,
$result = array();
foreach ($data as $subArray) {
    foreach ($subArray as $value) {
        $result[] = $value;
    }
}
echo implode(',', $result);

A: $data = array(5 => array(19,18,20), 6 => array(28));
foreach ($data as $array) {
    foreach ($array as $array1) {
        echo $array1.'<br>';
    }
}

Try this one. It will help you

A: I haven't really taken the time to consider any fringe cases, but this is an unorthodox method that will directly provide the desired output string without loops or even generating a new, temporary array.  It's a tidy little one-liner with a bit of regex magic.  (Regex Demo)  It effectively removes all square & curly brackets and double-quoted keys with trailing colons.
Code: (Demo)
$data=[5=>[19,18,20],6=>[28]];
echo preg_replace('/[{}[\]]+|"\d+":/','',json_encode($data));

Output:
19,18,20,28

To be clear/honest, this is a bit of hacky solution, but I think it is good for SO researchers to see that there are often multiple ways to achieve any given outcome.

A: Since all of the data that you wish to target are "leaf nodes", array_walk_recursive() is a handy function to call.
Code: (Demo)
$data=[5=>[19,18,20],6=>[28]];
array_walk_recursive($data,function($v){static $first; echo $first.$v; $first=',';});

Output:
19,18,20,28

This method uses a static declaration to avoid the implode call and just iterates the call of echo with preceding commas after the first iteration. (no temporary array generated)

A: Just use nested foreach Statements
$values = array();
foreach($dataArray as $key => $subDataArray) {
   foreach($subDataArray as $value) {
       $values[] = $value;
   }
}
$valueString = implode(',', $values);

Edit: Added full solution..


text:
Q: How to access bundled files with exe batch So here goes.. I have grown weary of setting up wireless network profiles on computers and instead would like to just import these settings via the command line. After some research, I decided that I would export my already created profiles in netsh and then create a batch file to run the commands to create the profiles for the user. Then I thought I would wrap it all up as an exe for ease of access for others. What I have is this for a bat file:
@echo off
netsh wlan add profile filename="Wi-Fi-linksys3.xml"
netsh wlan add profile filename="Wi-Fi-linksys2.xml"
netsh wlan add profile filename="Wi-Fi-linksys1.xml"

This fails to import the xml files that are in the same folder. It does not call to the correct folder path to import the files, instead it reports:
"The system cannot find the file supported"

Or if I try something like:
@echo off
netsh wlan add profile filename="%TEMP%\Wi-Fi-linksys3.xml"
netsh wlan add profile filename="%TEMP%\Wi-Fi-linksys2.xml"
netsh wlan add profile filename="%TEMP%\Wi-Fi-linksys1.xml"

It does the same thing.
I think that for some reason netsh is not calling to the correct location. If I put something like "c:[filename]" it will import just fine, but I cannot get something like that to work once it is wrapped up in the exe.
Any suggestions would be amazing. I am even open to trying a different method, just has to be able to run out of box on Windows machines.

A: This is working here:
netsh wlan add profile Wi-Fi-linksys3.xml

A: Assuming you are using iexpress.exe to bundle your bat and xml files, the exe should extract them to a temporary location (somewhere in %appdata%, local temp most likely), but since you probably wont know what the actual path is, try using %~dp0 in place of the path and that should work.
@echo off
netsh wlan add profile %~dp0Wi-Fi-linksys1.xml
netsh wlan add profile %~dp0Wi-Fi-linksys2.xml
netsh wlan add profile %~dp0Wi-Fi-linksys3.xml

When going through the iexpress process, make sure to check the box to keep the long file names or save the xml files with shorter names like conf1.xml and etc (and reflect the changes in your bat).
update
here's where I pulled the %dp0 from if you want to know a little more: https://serverfault.com/a/255294/144813


text:
Q: In Flutter How to use Providers with AMQP? in Flutter -which I just recently begin to use-, I am trying to use an AMQP stream using dart_amqp: ^0.1.4 and use providers provider: ^3.1.0+1 to make the data available throughout the app.
Only after logging in I start the AMQP service.
The AMQP part works without any issues, I get the data but I never manage to use it with Providers.
main.dart
class BigBrother extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<EventsModel>(create: (_) => EventsModel()),
        ChangeNotifierProxyProvider<EventsModel, DeviceState>(
          create: (_) => new DeviceState(),
          update: (context, eModel, deviceState) {
            deviceState.updateFromEvent(eModel.value);
          },
       ),
     ],

My models in models.dart
(As seen in below code, I also tried to used StreamProvider and commented it out)
// Global data model
class DeviceState with ChangeNotifier {
  Map<String, Map<String, dynamic>> state = {};
  DeviceState() {
    this.state['xxx'] = {};
    this.state['yyy'] = {};
  }

  updateFromEvent(EventsItemModel event) {
    if (event != null && event.type != null) {
      switch (event.type) {
        case 'heartbeat':
          this.state[event.device][event.type] = event.createdAt;
          break;
        case 'metrics':
          this.state[event.device][event.type] = {}
            ..addAll(this.state[event.device][event.type])
            ..addAll(event.message);
          break;
      }
      notifyListeners();
    }
  }
}

class EventsModel with ChangeNotifier {
  EventsItemModel value;
  bool isSubscribed = false;
  AMQPModel _amqp = new AMQPModel();
  // final _controller = StreamController<EventsItemModel>();

  EventsModel();

  // Stream<EventsItemModel> get stream => _controller.stream;

  _set(String jsonString) {
    value = new EventsItemModel.fromJson(jsonString);

//    _controller.sink.add(value); // send data to stream
//    Provider.of<DeviceState>(context, listen: false).updateFromEvent(value);

    notifyListeners();
  }

  subscribe() {
    if (!this.isSubscribed) {
      this.isSubscribed = true;
      this._amqp.subscribeEvents(_set); // start AMQP service after login
    }
  }
}

So on the login.dart view, on button pressed and validating the login, I start the AMQP stream:
onPressed: () {
  if (_formKey.currentState.validate()) {
    print("Login button onPressed");
    Provider.of<EventsModel>(context, listen: false)
                          .subscribe();
    Navigator.pushReplacementNamed(context, Routes.live);
}

And lastly the view after successful login:
class _LivePageState extends State<LivePage> {
  @override
  Widget build(BuildContext context) {
    DeviceState deviceState = Provider.of<DeviceState>(context);

    print('#### Device state updated');
    print(deviceState.state['xxx']);

In the above code, deviceState is always null.
So after trying many combination of various Providers, I am still unable to make this work.
Would be glad to have someone's insight on this.
Best regards!


text:
Q: Laravel 7, How add and change key field login auth I want to add and use a field DNI instead of email as key of login.
Something goes wrong, becouse I get this error message after write values on view login:
Illuminate\Database\QueryException SQLSTATE[HY000]: General error: 1364
Field 'dni' doesn't have a default value
(SQL: insert into users (name, email, password, updated_at, created_at) values (MAU, mau@mau.com, $2y$10$Je2/mfz40q/QApBhkA0fMOiYKy1f/ZHizHW2d8XQS7.5763bclYbq, 2020-07-22 03:31:32, 2020-07-22 03:31:32))

What I did,
I changed the users migration in order to add DNI field.
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('dni')->unique();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

Then I changed the model, line in app/User.php to:
protected $fillable = [
      'dni', 'name', 'email', 'password',
];

I has changed app/database/factories/UserFactory.php (I dont sure if it is necesary):
$factory->define(User::class, function (Faker $faker) {
    return [
        'dni' => $faker->unique(),
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
    ];
});

I change the login and register views too, adding DNI field before email field ( app/resources/views/auth/register.blade.php):

                            {{ __('DNI') }}

                                <input id="dni" type="text" class="form-control @error('dni') is-invalid @enderror" name="dni" value="{{ old('dni') }}" required autocomplete="dni">

                                @error('dni')

                                        {{ $message }}

                                @enderror

and after that, the error ocurrs.
It seems like the field "dni" is not in the model, the mysql insert not include the dni field.

Thank you for any help.

A: If you're using native Laravel auth components, you will need to override a few things.
There is a RegisterController in app/Http/Controllers/Auth, and you need to tell Laravel to create a user using your additional properties:
protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'dni' => $data['dni'],
    ]);
}

And you could also override the validation in the same fashion if you need it (not required though):
protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
        'dni' => ['required'],
    ]);
}

If you need login to function with DNI as being mandatory, you will also need to change LoginController by overriding some of the default methods. This is a bit more complex in a way that I can't really test and verify it for your case, so you'd have to play around. But for starters:
protected function validateLogin(Request $request)
{
    $request->validate([
        $this->username() => 'required|string',
        'password' => 'required|string',
        'dni' => 'required|string',
    ]);
}

protected function credentials(Request $request)
{
    return $request->only($this->username(), 'password', 'dni');
}

If you'd like to see where does it come from, it is from an AuthenticatesUsers trait in vendor/laravel/ui/auth-backend/.


text:
Q: ADOConnection cant get table names on SQL LocalDB I have a SQL Database MDF file , I want to connect to that file with ADOConnection and SQL Client 11.0 as provider
ADOConnection connects successfully but there is no Table !
ADOConnection.GetTableNames() returns ""
My code is like this :
 ADOConnection1.ConnectionString := 'Provider=SQLNCLI11.1;Integrated Security=SSPI;Persist Security Info=False;User ID="";Data Source=(localdb)\v11.0;Initial File Name="";Server SPN="";'
               +'AttachDbFileName="G:\Projects\Delphi\Pasargad Insurance\DB\Main.mdf";';
 ADOConnection1.Connected := True;

 ADOConnection1.GetTableNames(REdit.Lines);

When I connect to Database with SQL Server Managment Studio, tables are exists
Edit :
I removed "Initial File Name" and now the ADOConnection failed to connect :

An attempt to attach an auto-named database for file "G:\Projects\Delphi\Pasargad Insurance\DB\Main2.mdf" failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share

I switched tracing of LocalDB to off, copied my database file and deleted main database with SQLServer Managment Studio , and tried again to connect but the same error shown.


text:
Q: Sahi OS: Install certificate option is not showing on IE9 (Certificate error) Whenever i go to the browser through sahi os and i run the script then in between certificate error comes and when I hit continue then only am able to proceed. Can you please advise me how to get rid of this "certificate error" issue?
I am testing in IE9, with Windows 7 OS.

A: Usually, adding the certificat to your trusted certificates for this specific browser solves the issue. Check your SSLManager for the cert in question. And then google for something like "adding certificate exception [browser]"
Regards
Wormi


text:
Q: Compile Error: Else without If Vb6 Un proyecto bastante antiguo tengo que quitar los descuentos de una sucursal ... pero al agregar el código (que es exactamente igual a los demás solo con una condición si un lblSucursal es X pasa ahi..
Queda constar que este lenguaje casi no lo conocí..
'Si la sucursal es San Lorenzo quita los descuentos
        If lblSucursal.Caption = "SAN LORENZO" Then
            .Open "SELECT * FROM CATALOGO_DescuentosParaArticulosOrdinariosGeneral WHERE Id ='2' ORDER BY MinimoEnUnidades DESC", cnnPv, adOpenStatic, adLockReadOnly
                Do While Not .EOF
                    m_PrecioFinal = Art(ArtAct).PrecioSinIva - (Art(ArtAct).PrecioSinIva * (Val(NoNull(.Fields("Descuento").Value, "0")) / 100))
                    If Val(NoNull(.Fields("MinimoEnUnidades"), "0")) <= Art(ArtAct).cantidad And Val(NoNull(.Fields("MinimoEnDinero"), "0")) <= Art(ArtAct).cantidad * m_PrecioFinal Then ' Art(ArtAct).PUnitario Then
                        If Art(ArtAct).costo > 0 Then
                            m_PorcentajeDeDiferencia = ((m_PrecioFinal / Art(ArtAct).costo) - 1) * 100
                            If m_PorcentajeDeDiferencia >= m_PorcentajeMinimoDeUtilidad Then
                                Art(ArtAct).DescPorTabla = Val(NoNull(.Fields("Descuento"), "0")) / 100
                                LblDescto(RengAct).Caption = Format(Art(ArtAct).DescPorTabla * 100, "#0.0")
                                Exit Do
                            End If
                        Else
                            Art(ArtAct).DescPorTabla = Val(NoNull(.Fields("Descuento").Value, "0")) / 100
                            LblDescto(RengAct).Caption = Format(Art(ArtAct).DescPorTabla * 100, "#0.0")
                            Exit Do
                        End If
                    End If
                    .MoveNext
                Loop
                If .State <> adStateClosed Then .Close
            End If
         Else
                'Si no sigue con los descuentos normales
                .Open "SELECT * FROM CATALOGO_DescuentosParaArticulosOrdinariosGeneral ORDER BY MinimoEnUnidades DESC", cnnPv, adOpenStatic, adLockReadOnly
                Do While Not .EOF
                    m_PrecioFinal = Art(ArtAct).PrecioSinIva - (Art(ArtAct).PrecioSinIva * (Val(NoNull(.Fields("Descuento").Value, "0")) / 100))
                    If Val(NoNull(.Fields("MinimoEnUnidades"), "0")) <= Art(ArtAct).cantidad And Val(NoNull(.Fields("MinimoEnDinero"), "0")) <= Art(ArtAct).cantidad * m_PrecioFinal Then ' Art(ArtAct).PUnitario Then
                        If Art(ArtAct).costo > 0 Then
                            m_PorcentajeDeDiferencia = ((m_PrecioFinal / Art(ArtAct).costo) - 1) * 100
                            If m_PorcentajeDeDiferencia >= m_PorcentajeMinimoDeUtilidad Then
                                Art(ArtAct).DescPorTabla = Val(NoNull(.Fields("Descuento"), "0")) / 100
                                LblDescto(RengAct).Caption = Format(Art(ArtAct).DescPorTabla * 100, "#0.0")
                                Exit Do
                            End If
                        Else
                            Art(ArtAct).DescPorTabla = Val(NoNull(.Fields("Descuento").Value, "0")) / 100
                            LblDescto(RengAct).Caption = Format(Art(ArtAct).DescPorTabla * 100, "#0.0")
                            Exit Do
                        End If
                    End If
                    .MoveNext
                Loop
                If .State <> adStateClosed Then .Close
        End If ' DE METREABLE
End If       ' DE CONTINUA BUSCANDO
End With

On Error GoTo 0
   Exit Sub
DeterminaTipoDeDescuento2_Error:

    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure DeterminaTipoDeDescuento2 of Formulario Form_PV"
    SendErr "Error " & Err.Number & " (" & Err.Description & ") in procedure DeterminaTipoDeDescuento2 of Formulario Form_PV"
End Sub

Es la parte del codigo encargada de calcular el descuento del PV pero actualmente esta con las condiciones adecuadas...

A: Tienes
[snip]
               Loop
                If .State <> adStateClosed Then .Close
            End If
else
[snip]

Cuando el parte despues del "Then" aparece en la misma linea como el "if", termina el "if." (Es decir, el fin de la linea termina el "if", no el "end if".)  Significa el siguiente "End If" pertenece al primer "If", o mejor dicho
If lblSucursal.Caption = "SAN LORENZO" Then

Entonces, el "else" no pertence a nada.
Si escribe
If .State <> adStateClosed then
    .Close
End If

tambien resuelva el problema.
Semejante, tiene el mismo problema en el fondo del código.


text:
Q: Zend Framework 2 controller action returning javascript file: error 500 I'm trying to do in ZF2 a simple controller action that returns a javascript file.
Simply, what I want to do is something that with PHP you can do in the following way:
<?php header('Content-Type: text/javascript'); ?>
var foo = '<?php echo $bar; ?>';

Now, in ZF2 I've an action function of an ActionController like that:
public function environmentAction()
{
    $headers = new Headers();
    $headers->addHeaderLine('Content-Type', 'text/javascript');

    $this->getResponse()->setHeaders($headers);

    $this->layout()->setTemplate('js/environment');

    $view = new ViewModel();
    return $view;
}

Then, the route is configured in the following way:
'environment' => array(
    'type' => 'Literal',
    'options' => array(
        'route'    => '/js/environment.js',
        'defaults' => array(
            'controller' => 'Application\Controller\Index',
            'action'     => 'environment',
        ),
    ),
)

In the end, the view is a .phtml file (the one that is defined in the template_map section under the js/environment key) like in the simple PHP case:
var foo = '<?php echo $bar; ?>'

So, all should be done. I simply add a <script> element in the head section of my layout.phtml:
<script type="text/javascript" src="/js/environment.js"></script>

The problem is that in my browser console I get the following error when loading the page:
GET ***/js/environment.js 500 (Internal Server Error)

but if I try to open the same link in a new page, I success to get the script.
What's the difference? In the network section of the developer tools of my browser I see that the http get request for this script and its headers are the same of all the other requests, so why is it acting differently? Why am I getting this error? And in my php log there is nothing about this event. Any idea?

Solved modifying the action function like that:
public function environmentAction()
{
    $headers = new Headers();
    $headers->addHeaderLine('Content-Type', 'text/javascript');

    $this->getResponse()->setHeaders($headers);

    $view = new ViewModel();
    $view->setTemplate('js/environment');
    $view->setTerminal(true);
    return $view;
}

A: This is a really bad way of doing things.
<script type="text/javascript" src="/js/environment.js"></script>

This will make the browser make a new request for the file '/js/environment.js' which will again match the route:
'route'    => '/js/environment.js'

You will get a race condition / endless loop.
Depending on your web server setup, if you request '/js/environment.js' and the file really exists (that is a phyical directory alled js containing environment.js) , then the file will be passed back rather than going to your route anyway which is another undesired effect.


text:
Q: Do a demonstrative and a possessive pronoun make it offensive (if so, what is the alternative)? In a Japanese Language question, I was informed that English construction such as

*

*That son of yours

*These cats of hers

would have an extra offensive connotation outside of a neutral combination of determinatives.
Is that generally true, or when (collocation or situation) can it be? And if possible, how come?
Edit: In a comment I got an observation about my examples:

since the "standard" versions are your son / her cats, native speakers automatically assume the "marked" forms convey some specific sense or nuance

It actually adds to this question:

*

*Doesn't English have an neutral way to add both information carried by "this/that" and "my/your/their" to a noun?

*Isn't such a manner of specification meaningful in English?

A: There is a negative or pejorative aspect to the construction, 'That son of yours,' or 'those cats of yours.' It may - in fact probably would - be considered offensive, but it's possible that that is your intent. You could be intending disparagement as one comment notes. Another intention may be empathy. Without context we can't know.
You are pointing out something (a son or cat/s) to someone who is specifically the owner of or is considered responsible for that thing. The reason for doing so using this construction is not to distinguish them from among other things, as in:

*

*That son of yours: the one with long hair, not the son with short hair.

*Those young cats of yours, not the elderly cats on the couch.

Your are probably either:

*

*Identifying them to the parent/owner pointedly (an adverb meaning 'in a direct and unambiguous way, often indicating criticism or displeasure')

*

*Because they are offense to you

*

*For example, you don't like long hair on boys, or the cats kill song birds

or;

*

*Identifying them regretfully

*

*Because you know the son or the cats have given trouble or pain to them

*

*For example, the son is disrespectful, or the cats ruin the furniture

This situation is most likely to occur in direct communication between people, where the verbal clues like word  emphasis or visual clues like facial expression will help convey the unspoken negative emotion. It might also occur in written dialogue between characters, in which case the context will be known.
It's definitely important to be aware of the possibility of offending someone unintentionally. But it's also good to know the construction can be used as an indirect way to convey displeasure or sympathy. You can use it to alert someone to something that is bothering you, which may prompt them to enquire further, or to offer emotional support to them.

A: "That son of yours got into a fantastic college."
Is a positive statement. It emphasizes the responsibility aspect of ownership or possessiveness. A parent would be proud of a student in this case.
"That cat of yours was digging in the garbage again."
If your neighbor said this, they would be emphasizing your responsibility for the cat. She would probably be less frustrated if she had said "Your cat was digging in the garbage again." Because you own the cat, you are responsible for its actions.
—
For your followup question, there is a neutral way to do this, but I don't think it is accepted across all varieties of English.
"Your daughter over there is a great athlete."
"His cat, here, is causing a lot of trouble."
Even less accepted across different Englishes:
"Them's my apples and I am taking them down to the market."


text:
Q: How can I show .PARAMETER help messages for dynamic paramters in Powershell? I make benefit of lots of dynamic parameters in various modules for many functions.
However, .PARAMETER comment blocks for the dynamic parameters are not shown in get-help.
.PARAMETER
Some details of the dynamic parameter that is defined in dynamicParam { block}

Is there any work around to provide dynamic parameter details to the user when the get-help cmdlet is called over a such a function?
Thanks!

A: You can get-halfway there if you cheat by duplicating the parameter name with a space after it:
param ([string]${Name })

DynamicParam{
    #insert usual stuff here
    New-Object System.Management.Automation.RuntimeDefinedParameter(
        'Name',  [string], $attributeCollection
    )
    # more stuff
}
begin
{
    $name = $PSBoundParamters.'Name '
}

This means you get the parameter name with Get-Help, but not the actual text. It's a horrible hack, but it gets you halfway there...

A: There is a HelpMessageproperty on System.Management.Automation.ParameterAttribute which you can use to set the help text within your dynamic parameter:
# Create a collection of attributes
$AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]

$ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$ParameterAttribute.Mandatory = $true
$ParameterAttribute.Position = 0
$ParameterAttribute.HelpMessage = "YOUR_HELP_MESSAGE"

# Add the attributes to the attributes collection
$AttributeCollection.Add($ParameterAttribute)


text:
Q: Быстрая отработка запросов python Нужно при парсинге, отправить около 4.000 запросов, но если делать это с помощью процессов, то из-за долгого ответа сервера, падает все и парсится дольше обычного, но я прочитал, про аiohttp, что там можно ограничить одновременное кол-во запросов, но у меня так и не вышло, я не смог передать json параметры в запрос, кто может помогите!
import json
import asyncio
import aiohttp

conn = aiohttp.TCPConnector(limit_per_host=100, limit=0, ttl_dns_cache=300)
PARALLEL_REQUESTS = 100
results = []
urls = ['https://ru.stackoverflow.com' for i in range(50)]

async def gather_with_concurrency(n):
    semaphore = asyncio.Semaphore(n)
    session = aiohttp.ClientSession(connector=conn)

    async def get(url):
        async with semaphore:
            async with session.get(url, ssl=False) as response:
                obj = json.loads(await response.read())
                print(obj)
                results.append(obj)

    await asyncio.gather(*(get(url) for url in urls))
    await session.close()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(gather_with_concurrency(PARALLEL_REQUESTS))
    # conn.close()


text:
Q: Get exact syntax of javascript base functions Is there a way to know how test (for regex) or cos (for math) or substring (for string) or splice (for array) have been coded in the exact syntax either by a way in Javascript (like alert(function)) or by seeking in the files that come with Firefox?

A: Well, the source code of javascript likely isn't written in javascript itself, so you would be unable to just print it to the browser console or alert.
You can browse the source code of google's V8 engine, and see if it helps you ;)
http://code.google.com/p/v8/

A: These functions are actually implemented differently by browsers in one of the OS native languages.
So these algorithms are written in c, c++, c#, java etc. but not in JavaScript.


text:
Q: How to read available audio tracks in a video file? Some video files contain multiple audio tracks. Multiple languages for example. Is there a command line tool which gets information about these audio tracks? Names of the audio tracks would be sufficient.
It should support common formats (mkv, avi,...).

A: From the top of my head:
ffmpeg -i <file> 2>&1 | grep 'Audio:'


text:
Q: Calling a command line utility from Python I am currently trying to utilize strace to automatically trace a programm 's system calls. To then parse and process the data obtained, I want to use a Python script.
I now wonder, how would I go about calling strace from Python?
Strace is usually called via command line and I don't know of any C library compiled from strace which I could utilize.
What is the general way to simulate an access via command line via Python?
alternatively: are there any tools similar to strace written natively in Python?
I'm thankful for any kind of help.
Nothing, as I'm clueless

A: You need to use the subprocess module.
It has check_output to read the output and put it in a variable, and check_call to just check the exit code.
If you want to run a shell script you can write it all in a string and set shell=True, otherwise just put the parameters as strings in a list.
import subprocess
# Single process
subprocess.check_output(['fortune', '-m', 'ciao'])
# Run it in a shell
subprocess.check_output('fortune | grep a', shell=True)

Remember that if you run stuff in a shell, if you don't escape properly and allow user data to go in your string, it's easy to make security holes. It is better to not use shell=True.

A: You can use commands as the following:
import commands
cmd = "strace command"
result = commands.getstatusoutput(cmd)
if result[0] == 0:
   print result[1]
else:
   print "Something went wrong executing your command"

result[0] contains the return code, and result[1] contains the output.

A: Python 2 and Python 3 (prior 3.5)
Simply execute:
subprocess.call(["strace", "command"])

Execute and return the output for processing:
output = subprocess.check_output(["strace", "command"])

Reference: https://docs.python.org/2/library/subprocess.html
Python 3.5+
output = subprocess.run(["strace", "command"], caputure_output=True)

Reference: https://docs.python.org/3.7/library/subprocess.html#subprocess.run


text:
Q: rotate text in tabular array I have the following table:
\documentclass{article}
\usepackage{caption}
%------ tables
\usepackage{rotating}
\usepackage{makecell}
\usepackage{xcolor}
    \colorlet{bgodd}{black!10}
\usepackage{tabularray}
     \UseTblrLibrary{booktabs}
%------

\begin{document}

bla bla bla

\clearpage
\newpage

\clearpage
\newpage

\begin{sidewaystable*}[ht]

    \centering
    \caption{Papers analyzed in the survey grouped by data sources employed, and techniques used to detect anomalies.}
    %\caption{Papers analyzed in the survey grouped by data sources employed, and techniques used to detect anomalies}
    % from makecell
    \settowidth\rotheadsize{\small Monitoring-Based}
    \footnotesize
    \setlength\tabcolsep{0.1mm} % let LaTeX calculate intercolumn whitespace
    \begin{tblr}{
        width=\textheight-3\baselineskip,  % <--- added
        colspec = {l *{13}{X[c]}},
        vline{2-Y} = {2-Z}{dotted},
        vline{2,5} = {1-Z}{solid, \lightrulewidth}, % \lightrulewidth is defined in booktabs
        colsep = 1pt,                               % <--- changed
        row{1} = {font=\bfseries, c, m},
        row{2} = {cmd=\rotcell},
        row{odd [3-Y]} = {bg=bgodd},                % <--- changed
        }
        \toprule
        \SetRow{bg=white}
        Paper(s) &
        \SetCell[c=3]{c, m} {Data\\ Sources} &&&
            \SetCell[c=10]{c, m} Technique &&&&&&&&& \\
        \midrule
        & Log-based
            & Distributed Tracing-based
            & Monitoring-Based
            & {Unsupervised\\ learning}
            & {Supervised\\ learning}
            & Reinforcement learning
            & Semi-supervised learning
            & Hybrid learning
            & {Statistical\\ Approach}
            & Causal Inference
            & {Trace\\ comparison}
            & Heart Beating
            & SLO checks \\
        \midrule
        \cite{liu2020unsupervised, pahl2018all, jin2020anomaly, bogatinovski2020self} &
        &  % Log-based
        \textbullet &   % Distributed Tracing-based
        &   % Monitoring-Based
        \textbullet &   % Unsupervised learning
        &   % Supervised learning
        &   % Reinforcement learning
        &   % Semi-supervised learning
        &   % Hybrid learning
        &   % Statistical Approach
        &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
           % SLO checks
        \\
        \cite{nedelkoski2019anomaly, gan2019leveraging, zhou2019latent} &
        &  % Log-based
        \textbullet &   % Distributed Tracing-based
        &   % Monitoring-Based
        &   % Unsupervised learning
        \textbullet &   % Supervised learning
        &   % Reinforcement learning
        &   % Semi-supervised learning
        &   % Hybrid learning
        &   % Statistical Approach
        &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
         % SLO checks
        \\
        \cite{wang2020workflow, chen2020framework, meng2021detecting} &
        &  % Log-based
        \textbullet &   % Distributed Tracing-based
        &   % Monitoring-Based
        &   % Unsupervised learning
        &   % Supervised learning
        &   % Reinforcement learning
        &   % Semi-supervised learning
        &   % Hybrid learning
        &   % Statistical Approach
        &   % Causal Inference
        \textbullet &   % Trace comparison
        &   % HeartBeating
         % SLO checks
        \\
        \cite{li2021microservice} &
        &  % Log-based
        \textbullet &   % Distributed Tracing-based
        &   % Monitoring-Based
        &   % Unsupervised learning
        &   % Supervised learning
        &   % Reinforcement learning
        \textbullet &   % Semi-supervised learning
        &   % Hybrid learning
        &   % Statistical Approach
        &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
         % SLO checks
        \\
        \cite{chow2014mystery} &
        &  % Log-based
        \textbullet &   % Distributed Tracing-based
        &   % Monitoring-Based
        &   % Unsupervised learning
        &   % Supervised learning
        &   % Reinforcement learning
        &   % Semi-supervised learning
        &   % Hybrid learning
        &   % Statistical Approach
        \textbullet &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
         % SLO checks
        \\
        \cite{belhadi2021reinforcement} &
        &  % Log-based
        \textbullet &   % Distributed Tracing-based
        &   % Monitoring-Based
        &   % Unsupervised learning
        &   % Supervised learning
        \textbullet &   % Reinforcement learning
        &   % Semi-supervised learning
        &   % Hybrid learning
        &   % Statistical Approach
        &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
         % SLO checks
        \\
        \cite{sharma2013cloudpd, zhang2016taskinsight, xu2018unsupervised, gulenko2018detecting, mariani2018localizing, wu2020microrca, wu2020performance, wang2018cloudranger, vallis2014novel, su2019robust, huang2013lof, bhaduri2011detecting,wang2012workload, lazarevic2003comparative} &
        &  % Log-based
        &   % Distributed Tracing-based
        \textbullet &   % Monitoring-Based
        \textbullet &   % Unsupervised learning
        &   % Supervised learning
        &   % Reinforcement learning
        &   % Semi-supervised learning
        &   % Hybrid learning
        &   % Statistical Approach
        &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
         % SLO checks
        \\
        \cite{sauvanaud2018anomaly, liu2015opprentice, du2018anomaly, mariani2020predicting} &
        &  % Log-based
        &   % Distributed Tracing-based
        \textbullet &   % Monitoring-Based
        &   % Unsupervised learning
        \textbullet &   % Supervised learning
        &   % Reinforcement learning
        &   % Semi-supervised learning
        &   % Hybrid learning
        &   % Statistical Approach
        &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
         % SLO checks
        \\
        \cite{magalhaes2010detection, peiris2014pad, abdelrahman2016detection, kang2012dapa, yang2007anomaly, wang2013energy, ahad2015toward, nguyen2013fchain, tan2012prepare, gu2009online, samir2019dla} &
        &  % Log-based
        &   % Distributed Tracing-based
        \textbullet &   % Monitoring-Based
        &   % Unsupervised learning
        &   % Supervised learning
        &   % Reinforcement learning
        &   % Semi-supervised learning
        &   % Hybrid learning
        \textbullet &   % Statistical Approach
        &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
         % SLO checks
        \\
        \cite{wu2021causal, chen2014causeinfer, chen2016causeinfer, lin2018microscope} &
        &  % Log-based
        &   % Distributed Tracing-based
        \textbullet &   % Monitoring-Based
        &   % Unsupervised learning
        &   % Supervised learning
        &   % Reinforcement learning
        &   % Semi-supervised learning
        &   % Hybrid learning
        &   % Statistical Approach
        \textbullet &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
         % SLO checks
        \\
        \cite{shan2019diagnosis} &
        &  % Log-based
        &   % Distributed Tracing-based
        \textbullet &   % Monitoring-Based
        &   % Unsupervised learning
        &   % Supervised learning
        &   % Reinforcement learning
        &   % Semi-supervised learning
        &   % Hybrid learning
        &   % Statistical Approach
        &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
        \textbullet  % SLO checks
        \\
        \cite{zang2018fault} &
        &  % Log-based
        &   % Distributed Tracing-based
        \textbullet &   % Monitoring-Based
        &   % Unsupervised learning
        &   % Supervised learning
        &   % Reinforcement learning
        &   % Semi-supervised learning
        &   % Hybrid learning
        &   % Statistical Approach
        &   % Causal Inference
        &   % Trace comparison
        \textbullet  &   % HeartBeating
        % SLO checks
        \\
        \cite{yagoub2018equipment, brown2018recurrent, nandi2016anomaly, jia2017logsed, fu2009execution, du2017deeplog} &
        \textbullet &  % Log-based
        &   % Distributed Tracing-based
        &   % Monitoring-Based
        \textbullet &   % Unsupervised learning
        &   % Supervised learning
        &   % Reinforcement learning
        &   % Semi-supervised learning
        &   % Hybrid learning
        &   % Statistical Approach
        &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
        % SLO checks
        \\
        \cite{fronza2013failure, zhang2016automated, zhang2019robust, liang2007failure} &
        \textbullet &  % Log-based
        &   % Distributed Tracing-based
        &   % Monitoring-Based
        &   % Unsupervised learning
        \textbullet &   % Supervised learning
        &   % Reinforcement learning
        &   % Semi-supervised learning
        &   % Hybrid learning
        &   % Statistical Approach
        &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
        % SLO checks
        \\
        \cite{meng2019loganomaly} &
        \textbullet &  % Log-based
        &   % Distributed Tracing-based
        &   % Monitoring-Based
        &   % Unsupervised learning
        &   % Supervised learning
        &   % Reinforcement learning
        &   % Semi-supervised learning
        \textbullet &   % Hybrid learning
        &   % Statistical Approach
        &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
        % SLO checks
        \\
       \cite{meng2019loganomaly, yang2021semi, li2021microservice} &
        \textbullet &  % Log-based
        &   % Distributed Tracing-based
        &   % Monitoring-Based
        &   % Unsupervised learning
        &   % Supervised learning
        &   % Reinforcement learning
        \textbullet &   % Semi-supervised learning
        &   % Hybrid learning
        &   % Statistical Approach
        &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
        % SLO checks
        \\
        \cite{salfner2007using, beschastnikh2014inferring} &
        \textbullet &  % Log-based
        &   % Distributed Tracing-based
        &   % Monitoring-Based
        &   % Unsupervised learning
        &   % Supervised learning
        &   % Reinforcement learning
        &   % Semi-supervised learning
        &   % Hybrid learning
        \textbullet &  % Statistical Approach
        &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
        % SLO checks
        \\
        \cite{he2020loghub} &
        \textbullet &  % Log-based
        &   % Distributed Tracing-based
        &   % Monitoring-Based
        &   % Unsupervised learning
        &   % Supervised learning
        &   % Reinforcement learning
        &   % Semi-supervised learning
        \textbullet &   % Hybrid learning
        &  % Statistical Approach
        &   % Causal Inference
        &   % Trace comparison
        &   % HeartBeating
        % SLO checks
        \\
        \midrule
    \end{tblr}
    {\label{tab:tbl_results}}
\end{sidewaystable*}

\clearpage
\newpage

bla bla

\end{document}

Printscreen:

I have to rotate from the second row, so it is readable, i.e., 270 degrees. I am not succeeding with the rotcell command in line 41. Do you know how to rotate the text of this line?
The goal is :

Solution:
I have added @Celdor's solution:
\renewcommand\cellrotangle{270}

And it worked.
Thank you.

A: Why you think, that text rotated for 270 degree is more readable as when is rotated for 90 degree? For example, article are in journals or in proceedings are usual twoside. In such cases your document and table preamble is as follows:
\documentclass[twoside]{article}
\usepackage{caption}
%------ tables
\usepackage[clockwise]{rotating}
\usepackage{makecell}
\usepackage{xcolor}
    \colorlet{bgodd}{black!10}
\usepackage{tabularray}
     \UseTblrLibrary{booktabs}

\begin{document}
\begin{sidewaystable*}[ht]
    \centering
    \caption{Papers analyzed in the survey grouped by data sources employed, and techniques used to detect anomalies.}
\renewcommand\cellrotangle{270}
\settowidth\rotheadsize{\small Monitoring-Based}
    \footnotesize
    \begin{tblr}{
        width=\textheight,  % <--- added
        colspec = {l *{13}{X[c]}},
        vline{2-Y} = {2-Z}{dotted},
        vline{2,5} = {1-Z}{solid, \lightrulewidth}, % \lightrulewidth is defined in booktabs
        colsep = 2pt,                               % <--- changed
        row{1} = {font=\bfseries, c, m},
        row{2} = {cmd=\rotcell},
        row{odd [3-Y]} = {bg=bgodd},                % <--- changed
                }
% table body
...
    \bottomrule
    \end{tblr}
\end{sidewaystable*}
\end{document}

which gives (after two compilation) the following result:

As you can see, now rotated text start on odd pages at top of the second row, and on even pages at the bottom of the second table row. Is this, what you are after?
Addendum:
It may be handy the following solution:
\documentclass[twoside]{article}
\usepackage{caption}
%------ tables
\usepackage[clockwise]{rotating}
\usepackage{makecell}
\usepackage{xifthen}
%\ifthenelse{\isodd{thepage}}{\renewcommand\cellrotangle{90}}{\renewcommand\cellrotangle{270}} % start at top of row
\ifthenelse{\isodd{thepage}}{\renewcommand\cellrotangle{270}}{\renewcommand\cellrotangle{90}}  % start at bottom of row

\usepackage{xcolor}
    \colorlet{bgodd}{black!10}
\usepackage{tabularray}
     \UseTblrLibrary{booktabs}

\begin{document}
\begin{sidewaystable*}[ht]
    \centering
\caption{Papers analyzed in the survey grouped by data sources employed, and techniques used to detect anomalies.}
\label{tab:tbl_results}
\settowidth\rotheadsize{\small Monitoring-Based}
\footnotesize
    \begin{tblr}{
        width=\textheight,  % <--- added
        colspec = {l *{13}{X[c]}},
        vline{2-Y} = {2-Z}{dotted},
        vline{2,5} = {1-Z}{solid, \lightrulewidth}, % \lightrulewidth is defined in booktabs
        colsep = 2pt,                               % <--- changed
        row{1} = {font=\bfseries, c, m},
        row{2} = {cmd=\rotcell},
        row{odd [3-Y]} = {bg=bgodd},                % <--- changed
                }
% table body
        \toprule
...
    \bottomrule
    \end{tblr}
\end{sidewaystable*}
\end{document}


text:
Q: using commands: ">" and "<" to read/ write file I have a method that reads a file called personDataBase using args[0] with the command:
java names/Sort personDataBase
this is the method:
public static Person[] read(String s){
    String readPeople = IO.readFile(s);
    String[] people = readPeople.split("\n");
    Person[] personArray = new Person[people.length];

    for (int i = 0; i < people.length; i++){
        String person = people[i];
        String[] splitArray = person.split("\\s+");
        personArray[i] = new Person(splitArray[0], splitArray[1],
                                    splitArray[2]);
    }

    return personArray;
}

I have to change this so that it works with the command:
java names/Sort -h -stats < personDataBase
Does anyone know how to do this?

A: < and > are for standard input and standard output,
it wont work with commandline input
so change your code to take standard input
ex: read the System.in using a buffered reader


text:
Q: How to check if ajax request was aborted by browser I'm making long polling ajax requests to my server
$.ajax({
    url: "someurl.com",
    success: function(resp) { ... },
    error: function() { ... }
});

but if there is some internet connection problems for a short period of time
Firefox 10 aborts the request and hence my script doesn't receive response from the server
(in older versions of FF there were no such request aborting).
How can I found out that my ajax request was aborted by browser? Maybe there are some event for it? Or can I force browser not to abort my ajax requests if the network connection is down?

A: For XMLHTTPRequest, it gives status "0" saying that request not initialized. You can catch that status and know that req has been aborted.

A: Perhaps you could add a timeout to the call?
  $.ajax({
        url: "test.html",
        error: function(){
            // will fire when timeout is reached
        },
        success: function(){
            //do something
        },
        timeout: 3000 // sets timeout to 3 seconds
    });

A: Check the abort status of the jqXHR in the .fail (previously .error) function.
let request = $.ajax({
    // your options
})

request.fail(jqXHR,textStatus){
    if(jqXHR.abort){
        alert("Aborted")
    }else{
        alert("Other error")
    }
})


text:
Q: Не выходит вызвать метод из Activity в фрагменте В методе не выходит вызвать метод из Activity в фрагменте через код:
new ActivityOne().addString(myString.getText().toString());
Метод принимает строку через аргументы метода. Вот код метода onClick (при котором происходят все действия).
    public void onClick(View v) {
        EditText myString = (EditText) v.findViewById(R.id.et1);
        new ActivityOne().addString(myString.getText().toString());
        dismiss();
    }

Что тут не так и как вызвать метод?

A: Вы вызываете метод только что созданного экземпляра класса активити, тогда как вам надо вызывать метод действующей активити. Следовательно, вам надо сначала получить ссылку на действующую активити и уже на ней вызывать её метод.
//вместо new ActivityOne().addString(myString.getText().toString()); надо
//получить ссылку на активити из фрагмента. В классе фрагмента пишем:
ActivityOne actOne=(ActivityOne)getActivity();
//теперь, имея ссылку на действующую активити можно что-то с ней сделать
actOne.addString(myString.getText().toString());


text:
Q: OpenGL debug context warning - "Will use VIDEO memory as the source for buffer objection I'm jumping through the hoops right now to learn opengl and I've come across an issue. On my desktop computer with a nvidia gtx 780 opengl is printing out a warning via the glDebugMessageCallback mechanism:
"Buffer object 1 (bound to _GL_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations."
I'm rendering 1 cube with a vertex and index buffer so this message repeats for every buffer object I'm creating (2 of them). However, there is also one final warning at the end which states:
"Vertex shader in program 3 is being recompiled based on GL State."
I'm still able to render my cube I was rendering before, but the color I had set is flashing between white and the color now. I searched online and found this answer - https://community.khronos.org/t/nvidia-output-debug-error-131185/66033 - which basically said this is nothing but a warning and everything should be fine but that wouldn't explain why my cube is flashing between white and my color now. This same code is working fine on my laptop (2019 Asus laptop which also has a nvidia GTX graphics chip). Anyone come across this issue before? Here is the relevant code:
const char* vertexShaderCode =
R"HereDoc(

#version 430

in layout(location=0) vec3 position;
in layout(location=1) vec3 color;
out vec3 fragColor;

uniform mat4 transformationMatrix;

void main()
{
vec4 newPos = vec4(position, 1.0) * transformationMatrix;//vector is on the left side because my matrices are row major
gl_Position = newPos;

    vec3 changedColors;
    changedColors.r += color.r + 0;
    changedColors.g += color.g + 0;
    changedColors.b += color.b + 0;
    fragColor = changedColors;
};

)HereDoc";

const char* fragmentShaderCode =
R"HereDoc(

#version 430

out vec4 color;
in vec3 fragColor;

void main()
{
    color = vec4(fragColor, 1.0f);
};

)HereDoc";

void GLAPIENTRY MyOpenGLErrorCallbackFunc(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam)
{
    BGZ_CONSOLE("%s type=0x%x %s\n", ( type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : "" ), type, message);
};

void CheckCompileStatus(GLuint shaderID)
{
    GLint compileStatus;
    glGetShaderiv(shaderID, GL_COMPILE_STATUS, &compileStatus);

    if(compileStatus != GL_TRUE)
    {
        GLint infoLogLength;
        glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &infoLogLength);

        GLchar buffer[512] = {};
        GLsizei bufferSize;
        glGetShaderInfoLog(shaderID, infoLogLength, &bufferSize, buffer);

        BGZ_CONSOLE("%s", buffer);
        InvalidCodePath;
    };
};

void CheckLinkStatus(GLuint programID)
{
    GLint linkStatus;
    glGetProgramiv(programID, GL_LINK_STATUS, &linkStatus);

    if(linkStatus != GL_TRUE)
    {
        GLint infoLogLength;
        glGetProgramiv(programID, GL_INFO_LOG_LENGTH, &infoLogLength);

        GLchar buffer[512] = {};
        GLsizei bufferSize;
        glGetProgramInfoLog(programID, infoLogLength, &bufferSize, buffer);

        BGZ_CONSOLE("%s", buffer);
        InvalidCodePath;
    };
};

local_func void InstallShaders()
{
    GLuint vertexShaderID = glCreateShader(GL_VERTEX_SHADER);
    GLuint fragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);

    const char* adapter[1];
    adapter[0] = vertexShaderCode;
    glShaderSource(vertexShaderID, 1, adapter, 0);
    adapter[0] = fragmentShaderCode;
    glShaderSource(fragmentShaderID, 1, adapter, 0);

    glCompileShader(vertexShaderID);
    glCompileShader(fragmentShaderID);

    CheckCompileStatus(vertexShaderID);
    CheckCompileStatus(fragmentShaderID);

    GLuint programID = glCreateProgram();
    glAttachShader(programID, vertexShaderID);
    glAttachShader(programID, fragmentShaderID);
    glLinkProgram(programID);

    CheckLinkStatus(programID);

    glUseProgram(programID);
};

local_func void
GLInit(int windowWidth, int windowHeight)
{
    glEnable(GL_DEBUG_OUTPUT);
    glDebugMessageCallback(MyOpenGLErrorCallbackFunc, 0);

    glViewport(0, 0, windowWidth, windowHeight);

    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);//Defaults to CCW ordering of indicies meaning all indicies that, from the viewers perspective, creating triangles in a CW manner repsrent visible triangles.
    glCullFace(GL_BACK);//Culls only back faces (faces facing away from viewer)
    InstallShaders();
}

void Draw(Memory_Partition* memPart, s32 id, RunTimeArr<s16> meshIndicies)
{
    glDisable(GL_TEXTURE_2D);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 2);
    glDrawElements(GL_TRIANGLES, (s32)meshIndicies.length, GL_UNSIGNED_SHORT, 0);
    glEnable(GL_TEXTURE_2D);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
};

//This implements a discriminated union for buffering render commands that my game code layer uses.
void RenderViaHardware(Rendering_Info&& renderingInfo, Memory_Partition* platformMemoryPart, int windowWidth, int windowHeight)
{
    local_persist bool glIsInitialized { false };
    if (NOT glIsInitialized)
    {
        GLInit(windowWidth, windowHeight);
        glClearColor(0.0f, 0.0f, 1.0f, 0.0f);
        glIsInitialized = true;
    };

    u8* currentRenderBufferEntry = renderingInfo.cmdBuffer.baseAddress;
    Camera3D camera3d = renderingInfo.camera3d;

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glEnable(GL_TEXTURE_2D);

    for (s32 entryNumber = 0; entryNumber < renderingInfo.cmdBuffer.entryCount; ++entryNumber)
    {
        RenderEntry_Header* entryHeader = (RenderEntry_Header*)currentRenderBufferEntry;
        switch (entryHeader->type)
        {
            case EntryType_InitBuffer:{
                RenderEntry_InitBuffer bufferData = *(RenderEntry_InitBuffer*)currentRenderBufferEntry;

                ScopedMemory scope{platformMemoryPart};

                RunTimeArr<GLfloat> verts{};
                InitArr(verts, platformMemoryPart, bufferData.verts.length * 6);
                s32 i{};
                f32 colorR{1.0f}, colorG{}, colorB{};//Im just hard coding color data right now while I'm learning
                for(s32 j{}; j < bufferData.verts.length; ++j)
                {
                    verts.Push(bufferData.verts[j].x);
                    verts.Push(bufferData.verts[j].y);
                    verts.Push(bufferData.verts[j].z);
                    verts.Push(colorR);
                    verts.Push(colorG);
                    verts.Push(colorB);
                };

                u32 vertexArrayID{};
                glGenVertexArrays(1, &vertexArrayID);
                glBindVertexArray(vertexArrayID);

                GLuint bufferID;
                glGenBuffers(1, &bufferID);
                glBindBuffer(GL_ARRAY_BUFFER, bufferID);
                glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * verts.length, verts.elements, GL_DYNAMIC_DRAW);
                glEnableVertexAttribArray(0);
                glEnableVertexAttribArray(1);
                glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, 0);
                glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, (char*)(sizeof(GLfloat)*3));

                GLuint indexBufferID;
                glGenBuffers(1, &indexBufferID);
                glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
                glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(s16) * bufferData.indicies.length, bufferData.indicies.elements, GL_DYNAMIC_DRAW);

                currentRenderBufferEntry += sizeof(RenderEntry_InitBuffer);
            }break;

            //...other cases for entries which are irrelevant to problem

            case EntryType_Geometry: {
                ScopedMemory scope{platformMemoryPart};

                RenderEntry_Geometry geometryEntry = *(RenderEntry_Geometry*)currentRenderBufferEntry;

                //camera transform setup
                Mat4x4 xRotMatrix = XRotation(camera3d.rotation.x);
                Mat4x4 yRotMatrix = YRotation(camera3d.rotation.y);
                Mat4x4 zRotMatrix = ZRotation(camera3d.rotation.z);
                Mat4x4 fullRotMatrix = xRotMatrix * yRotMatrix * zRotMatrix;
                v3 xAxis = GetColumn(fullRotMatrix, 0);
                v3 yAxis = GetColumn(fullRotMatrix, 1);
                v3 zAxis = GetColumn(fullRotMatrix, 2);

                //Setup full transform matrix
                Mat4x4 camTransform = ProduceCameraTransformMatrix(xAxis, yAxis, zAxis, camera3d.worldPos);
                Mat4x4 projectionTransform = ProduceProjectionTransformMatrix_UsingFOV(renderingInfo.fov, renderingInfo.aspectRatio, renderingInfo.nearPlane, renderingInfo.farPlane);
                Mat4x4 fullTransformMatrix = projectionTransform * camTransform * geometryEntry.worldTransform;

                //Send transform matrix to vertex shader
                GLint transformMatrixUniformLocation = glGetUniformLocation(3, "transformationMatrix");
                glUniformMatrix4fv(transformMatrixUniformLocation, 1, GL_FALSE, &fullTransformMatrix.elem[0][0]);

                Draw(platformMemoryPart, geometryEntry.id, geometryEntry.indicies);

                currentRenderBufferEntry += sizeof(RenderEntry_Geometry);
            }break;

            InvalidDefaultCase;
        };
    }

    renderingInfo.cmdBuffer.entryCount = 0;
};

EDIT:
I figured out the issue with the colors not working which was answered in the comments below. However, I still don't know what these warnings are trying to tell me and if they are anything I should be looking to fix.

A: You variable vec3 changedColors; is uninitialized. Initialize it with vec3 changedColors = vec3(0);. The reason why it works on your laptop might be that its graphics driver will initialize it to zero by default, while your other graphics driver won't.
Regarding the warning (not error). It just warns you that your buffer will be put in video memory since you're using GL_STATIC_DRAW for your buffer. It's actually more of a log and you can safely ignore it. If you want to get rid of it you have to filter it away in your callback (which you passed to glDebugMessageCallback). Your callback will have a severity parameter that lets you to filter messages with a certain severity.
Or, if you only want to get rid of that specific message, filter on its id value.
Here's an example taken from blog.nobel-joergensen.com:
void APIENTRY openglCallbackFunction(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam)
{
    cout << "---------------------opengl-callback-start------------" << endl;
    cout << "message: "<< message << endl;
    cout << "type: ";
    switch (type) {
    case GL_DEBUG_TYPE_ERROR:
        cout << "ERROR";
        break;
    case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
        cout << "DEPRECATED_BEHAVIOR";
        break;
    case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
        cout << "UNDEFINED_BEHAVIOR";
        break;
    case GL_DEBUG_TYPE_PORTABILITY:
        cout << "PORTABILITY";
        break;
    case GL_DEBUG_TYPE_PERFORMANCE:
        cout << "PERFORMANCE";
        break;
    case GL_DEBUG_TYPE_OTHER:
        cout << "OTHER";
        break;
    }
    cout << endl;

    cout << "id: " << id << endl;
    cout << "severity: ";
    switch (severity){
    case GL_DEBUG_SEVERITY_LOW:
        cout << "LOW";
        break;
    case GL_DEBUG_SEVERITY_MEDIUM:
        cout << "MEDIUM";
        break;
    case GL_DEBUG_SEVERITY_HIGH:
        cout << "HIGH";
        break;
    }
    cout << endl;
    cout << "---------------------opengl-callback-end--------------" << endl;
}


text:
Q: Sort table on click of the table header: Issue with asp:repeater maybe? I'm trying to build a sorting function to sort my tables based on which row I click. The problem I am running into is that when I click the row, it returns way too much data, the same data just repeated a couple hundred times. I think it's an issue with the asp:Repeater I use to pull the data, but can't think of a way to fix the issue. If you have any ideas how to fix this, I would appreciate it.If you have a better solution that what I'm trying, let me know, I'm okay with starting over.
The sorting itself doesn't work yet, but I can work on that later. I just need to know how to make it not post the same data hundreds of times. It loads fine the first time, but after a row is clicked it adds too much data.
Here is the code.

        Ip_prefix
        Peer_ip_src
        Comms
        Event_type
        As_path
        Local_pref
        Created

    <asp:Repeater runat="server" ID="dumpRptr">
        <HeaderTemplate>
        </HeaderTemplate>
        <ItemTemplate>

                <%#Eval("ip_prefix")%>
                <%#Eval("peer_ip_src")%>
                <%#Eval("comms")%>
                <%#Eval("event_type")%>
                <%#Eval("as_path")%>
                <%#Eval("local_pref")%>
                <%#Eval("Created")%>

        </ItemTemplate>
        <FooterTemplate>
        </FooterTemplate>
    </asp:Repeater>

I'm very new to all of this, so if you could explain the logic behind why it does what I don't want it to, I would be grateful. Answers are better of course.

A: I ended up making it so when the table row is clicked, the SQL code was changed to order them correctly. Everything can be sorted correctly now.