text:
Q: Using a for loop to display HTML element using JavaScript I'm currently working on a project where I have a gallery (Gallery.php) containing a carousel of images, if an image is clicked on, the ImageID (I have set) and the Image URL are added to a 2D array in the localStorage. I am attempting to retrieve the array from localStorage in the homepage (index.php) which works as confirmed by logging to the console, however I am struggling to find a way to loop through the array and display a bootstrap card where the header is the ImageID and the body is an image with the URL. I realise this would be easier in PHP, but the project briefing asks for this to be done explicitly in JavaScript.
Here is the psuedocode for what I am trying to achieve
FOR image IN ImageArray
   CREATE card
   SET card.header TO image.ImageID
   SET card.body TO img element SRC = ImageURL
   END CARD
ENDFOR

This is the function which sets the ImageID and URL, and then pushes to the localStorage array
function SetClickedPhotoURL(URL, ImageID) {
    //Check if item is already set
    for (let x = 0; x<images.length; x++) {
        if (images[x][0] == ImageID) {
            console.log("Image already added");
            //Cancel function
            return;
        }
    }
    images.push([ImageID, URL]);
    window.localStorage.setItem("images", JSON.stringify(images));
}

I am trying to achieve a similar effect of using a foreach loop in PHP, I am also using JQuery in this project if a solution is available through it.
The PHP for this solution would be something along the lines of this if it helps you understand what I am trying to achieve.
<?php
foreach ($ImageArray as $Image) {
   ?>

<?php echo $Image[0];?>

              <img src=<?php echo $Image[1];?> class="img-fluid" alt=<?php echo $ImageID;?>/>

    <?php
}
?>

Any help would be greatly appreciated!

A: Loop through the images, and for each element, create a card and append it to the destination (assume to be #target):
images.forEach(function(image) {
   $('#target').append(
   `

${image[0]}

    `
    );
});


text:
Q: Multiple execution of procedures in trigger database prevent LARAVEL Model I'm building a web application with Laravel and SQL Server. I created a trigger that every time I update or delete records on a table, it will add to another one according to this record. This action in trigger is done by a stored procedure that is called two times with different parameters. The trigger does its job when I manually interact with the query. But, it prevents all interactions from the Laravel controller. I think it's because of the multiple calls of a stored procedure because when I only call one time it works(both Laravel and query SQL).
Here is my trigger:
create trigger after_insert_update_delete_time_clock on time_clocks
after insert,update, delete as
begin
DECLARE @Action as char(1);
SET @Action = (CASE WHEN EXISTS(SELECT * FROM INSERTED)
                     AND EXISTS(SELECT * FROM DELETED)
                    THEN 'U'  -- Set Action to Updated.
                    WHEN EXISTS(SELECT * FROM INSERTED)
                    THEN 'I'  -- Set Action to Insert.
                    WHEN EXISTS(SELECT * FROM DELETED)
                    THEN 'D'  -- Set Action to Deleted.
                    ELSE NULL -- Skip. It may have been a "failed delete".
                END)

DECLARE @date date;
DECLARE @date2 date;
DECLARE @employeeId bigint;
IF (@Action = 'D')
BEGIN
    SET @date = cast((select access_datetime from deleted) as date)
    SET @employeeId = (select employee_id from deleted)
END
ELSE
BEGIN
    SET @date = cast((select access_datetime from inserted) as date)
    SET @employeeId = (select employee_id from inserted)
END

SET @date2 = DATEADD(DAY, -1, @date);

EXEC analyzeDayOfEmployee @employeeId, @date2;
EXEC analyzeDayOfEmployee @employeeId, @date;
end

And here is stored procedure:
create procedure [dbo].[analyzeDayOfEmployee](@employeeId bigint, @date date)
as
begin
-- Get Daily Schedule
declare @dailyScheduleId bigint;
set @dailyScheduleId = (select daily_schedule_id from getDailyScheduleByEmployee(@employeeId, @date));
--print N'Daily Schedule Id: ' + CAST(@dailyScheduleId as varchar);
if (@dailyScheduleId is null)
begin
    print 'No daily schedule set for this date';
    return
end
else
begin
    declare @dailySchedule table (
        id bigint,
        name nvarchar(max),
        color nvarchar(max),
        type nvarchar(max),
        abbreviation nvarchar(max),
        max_counted_time time,
        max_work_time time,
        min_work_time time,
        theorical_work_time time,
        delay_penalty_default time,
        early_departure_penalty_default time,
        time_clocks_day_1 int,
        time_clocks_day_2 int,
        total_time_clocks int
    );
    insert into @dailySchedule select * from (select * from getDailySchedule(@dailyScheduleId, @date)) as d;
    --select * from @dailySchedule;
    declare @totalTimeClocks int;
    set @totalTimeClocks = (select total_time_clocks from @dailySchedule);
    -- Get Timeslots
    declare @timeslots table (
        id bigint,
        time_start datetime,
        time_end datetime,
        delay_tolerance time,
        early_departure_tolerance time,
        variable_start time,
        variable_end time,
        delay_tolerance_default int,
        earl_departure_tolerance_default int
    );
    insert into @timeslots select * from (select * from getTimeslot(@dailyScheduleId, @date)) as ts;
    --select * from @timeslots;

    -- Get daily schedule theorical start
    declare @dailyScheduleStart datetime;
    set @dailyScheduleStart = (select tmp.time_start from (select top(1) * from @timeslots) as tmp);
    declare @dateDiff int;
    set @dateDiff = ABS(DATEDIFF(day, @date, @dailyScheduleStart));
    set @dailyScheduleStart = DATEADD(day, @dateDiff, @dailyScheduleStart);
    print @dailyScheduleStart;
    -- Get First timeclock
    declare @firstTimeClockId bigint;
    set @firstTimeClockId = (select ft.id from (select * from getFirstTimeClock(@employeeId, @dailyScheduleStart)) as ft);

    declare @firstTimeClockAccessTime datetime;
    set @firstTimeClockAccessTime = (select access_datetime from getFirstTimeClock(@employeeId, @dailyScheduleStart));
    --print @firstTimeClockId;

    -- Get all timeclocks of this day
    declare @timeclocks table(
        id bigint,
        access_datetime datetime,
        terminal_user_id nvarchar(max),
        terminal_serial_number nvarchar(max),
        device_id bigint,
        employee_id bigint,
        manually_added bit,
        created_at datetime,
        updated_at datetime,
        deleted_at datetime,
        device nvarchar(max)
    )
    insert into @timeclocks select * from (select * from getTimeClocksByDailySchedule(@employeeId, @totalTimeClocks, @firstTimeClockId, @firstTimeClockAccessTime)) as tmp;

    declare @nbTimeClocks int;
    set @nbTimeClocks = (select count(*) from @timeclocks);
    -- Declare temporary table anomalies
    declare @anomalies table (
            employee_id bigint,
            anomaly_type_id bigint,
            date date,
            level nvarchar(max),
            description nvarchar(max),
            validated bit
        )
    -- Missing checks
    if (@nbTimeClocks < @totalTimeClocks and @nbTimeClocks != 0)
    begin
        insert into @anomalies
        select @employeeId, 8, @date,
        'Daily schedule',
        'Theorical checks: ' + cast(@totalTimeClocks as nvarchar) +
        ', Practical checks: ' + cast(@nbTimeClocks as nvarchar), 0
    end

    -- Absence
    if (@nbTimeClocks = 0 and cast(GETDATE() as date) > cast(@date as date))
    begin
        insert into @anomalies
        select @employeeId, 1, @date,
        'Daily schedule',
        'Absence', 0
    end

    declare @timeslots_with_timeclocks table(
        row_num int,
        time_start datetime,
        time_end datetime,
        delay_tolerance time,
        early_departure_tolerance time,
        break_duration time,
        break_type nvarchar(max),
        break_start datetime,
        break_end datetime,
        time_clock_start datetime,
        time_clock_end datetime,
        time_clock_break_start datetime,
        time_clock_break_end datetime,
        num int
    );
    insert into @timeslots_with_timeclocks (row_num, time_start, time_end, delay_tolerance, early_departure_tolerance, break_duration, break_type, break_start, break_end)
    select * from (select ROW_NUMBER() over (order by ts.id) as row_num,
                            ts.time_start, ts.time_end, ts.delay_tolerance, ts.early_departure_tolerance, b.duration as break_duration, b.type as break_type,
                            fb.time_start as break_start, fb.time_end as break_end
                    from @timeslots ts
                    outer apply getBreak(ts.id, @date) b
                    outer apply getFixedBreak(b.id, @date) fb) as d;

    -- variable incrementing for every single timeslot
    declare @numRowTimeClock int;
    set @numRowTimeClock = 1;

    -- update @timeslots_with_timeclocks by inserting timeclocks
    UPDATE @timeslots_with_timeclocks
    SET @numRowTimeClock = num = @numRowTimeClock + (case when row_num = 1 then 0
                                                            when row_num != 1 and break_type = 'No break' then 2
                                                            when row_num != 1 and break_type != 'No break' then 4 end);

    UPDATE @timeslots_with_timeclocks
    SET time_clock_start = (Select access_datetime from (Select Row_Number() Over (Order By id) As RowNum, * from @timeclocks) t2 Where RowNum = num),
        time_clock_end = (Select access_datetime from (Select Row_Number() Over (Order By id) As RowNum, * from @timeclocks) t2 Where RowNum = num + (case when break_type = 'No break' then 1 else 3 end)),
        time_clock_break_start = (case when break_type = 'No break' then null else (Select access_datetime from (Select Row_Number() Over (Order By id) As RowNum, * from @timeclocks) t2 Where RowNum = num + 1) end),
        time_clock_break_end = (case when break_type = 'No break' then null else (Select access_datetime from (Select Row_Number() Over (Order By id) As RowNum, * from @timeclocks) t2 Where RowNum = num + 2) end);

    select * from @timeslots_with_timeclocks;

    -- TEMPORARY TABLE LEVEL TIMECLOCKS AND RESULTS OF CALCULATIONS
    select lvl1.*, lvl1.duration_start_end - lvl1.break_duration as practical_duration
    into #lvl1
    from (select ts.row_num as timeslot,
            -- Delay
            DATEDIFF(minute, DATEADD(day, @dateDiff, ts.time_start), ts.time_clock_start) as delay,
            DATEDIFF(mi,convert(datetime,'00:00:00',108), convert(datetime, ts.delay_tolerance,108)) as theorical_delay_tolerance,
            (case when DATEDIFF(minute, DATEADD(day, @dateDiff, ts.time_start), ts.time_clock_start) > DATEDIFF(mi,convert(datetime,'00:00:00',108), convert(datetime, ts.delay_tolerance,108)) then 1 else 0 end) as delay_tolerance_unrespected,
            -- Early departure
            DATEDIFF(minute, ts.time_clock_end, DATEADD(day, @dateDiff, ts.time_end)) as early_departure,
            DATEDIFF(mi,convert(datetime,'00:00:00',108), convert(datetime, ts.early_departure_tolerance,108)) as theorical_early_departure_tolerance,
            (case when DATEDIFF(minute, ts.time_clock_end, DATEADD(day, @dateDiff, ts.time_end)) >  DATEDIFF(mi,convert(datetime,'00:00:00',108), convert(datetime, ts.early_departure_tolerance,108)) then 1 else 0 end) as early_departure_tolerance_unrespected,
            -- Break duration
            DATEDIFF(minute, ts.time_clock_break_start, ts.time_clock_break_end) as break_duration,
            DATEDIFF(mi,convert(datetime,'00:00:00',108), convert(datetime, ts.break_duration,108)) as theorical_break_duration,
            (case when ts.break_type = 'No break' and ts.time_clock_break_start IS NULL and ts.time_clock_break_end IS NULL then 0 else
                (case when DATEDIFF(minute, ts.time_clock_break_start, ts.time_clock_break_end) > DATEDIFF(mi,convert(datetime,'00:00:00',108), convert(datetime, ts.break_duration,108)) then 1 else 0 end) end) as break_duration_exceeded,
            -- Fixed break
            ts.time_clock_break_start,
            ts.time_clock_break_end,
            DATEADD(day, @dateDiff, ts.break_start) as break_start,
            DATEADD(day, @dateDiff, ts.break_end) as break_end,
            (case when ts.break_type != 'Fixed break' then 0 else
                (case when DATEDIFF(minute, ts.time_clock_break_start,  DATEADD(day, @dateDiff, ts.break_start)) > 0
                        or DATEDIFF(minute, DATEADD(day, @dateDiff, ts.break_end) ,ts.time_clock_break_start) > 0
                        or DATEDIFF(minute, DATEADD(day, @dateDiff, ts.break_end),ts.time_clock_break_end) > 0
                        or DATEDIFF(minute, ts.time_clock_break_end,  DATEADD(day, @dateDiff, ts.break_start)) > 0 then 1 else 0 end) end) as fixed_break_not_respected,
            -- Practical duration
            DATEDIFF(minute, ts.time_clock_start, ts.time_clock_end) as duration_start_end
            from @timeslots_with_timeclocks ts) as lvl1

    select * from #lvl1

    -- TEMPORARY TABLE LEVEL DAILY SCHEDULE
    select (select sum(practical_duration) from #lvl1) as total_practical_duration,
    (select Datediff(mi,convert(datetime,'00:00:00',108), convert(datetime, min_work_time,108))
    from daily_schedules where id = @dailyScheduleId) as min_work_time,
    (select Datediff(mi,convert(datetime,'00:00:00',108), convert(datetime, max_work_time,108))
    from daily_schedules where id = @dailyScheduleId) as max_work_time,
    (select Datediff(mi,convert(datetime,'00:00:00',108), convert(datetime, theorical_work_time,108))
    from daily_schedules where id = @dailyScheduleId) as theorical_work_time,
    (select Datediff(mi,convert(datetime,'00:00:00',108), convert(datetime, max_counted_time,108))
    from daily_schedules where id = @dailyScheduleId) as max_counted_time
    into #lvl2

    select #lvl2.*, (case when total_practical_duration < min_work_time then 1 else 0 end) as min_unrespected
    into #lvl3
    from #lvl2

    select * from #lvl3

    -- Daily Schedule : Min unrespected
    if exists (select * from #lvl3 where min_unrespected = 1)
    begin
        insert into @anomalies values (@employeeId, 9, @date, 'Daily schedule', 'Practical: ' + cast((select total_practical_duration from #lvl3) as nvarchar) + ' , Theorical: ' + cast ((select min_work_time from #lvl3) as nvarchar), 0)
    end

    -- Timeslots: delay tolerance unrespected
    insert into @anomalies
    select @employeeId, 2, @date,
    'Timeslot ' + cast(timeslot as nvarchar),
    'Delay departure tolerance: ' + cast(theorical_delay_tolerance as nvarchar) +
    ', Exceed: ' + cast(delay - theorical_delay_tolerance as nvarchar), 0
    from #lvl1
    where delay_tolerance_unrespected = 1

    -- Timeslots: early departure tolerance unrespected
    insert into @anomalies
    select @employeeId, 3, @date,
    'Timeslot ' + cast(timeslot as nvarchar),
    'Early departure tolerance: ' + cast(theorical_early_departure_tolerance as nvarchar) +
    ', Exceed: ' + cast(early_departure - theorical_early_departure_tolerance as nvarchar), 0
    from #lvl1
    where early_departure_tolerance_unrespected = 1

    -- Timeslots: fixed break unrespected
    insert into @anomalies
    select @employeeId, 4, @date,
    'Timeslot ' + cast(timeslot as nvarchar),
    'Theorical fixed break start: ' + cast(break_start as nvarchar) +
    ', Theorical fixed break end: ' + cast(break_end as nvarchar) +
    ', Practical fixed break start: ' + cast(time_clock_break_start as nvarchar) +
    ', Practical fixed break end: ' + cast(time_clock_break_end as nvarchar)
    , 0
    from #lvl1
    where fixed_break_not_respected = 1

    -- Timeslots: break duration exceed
    insert into @anomalies
    select @employeeId, 5, @date,
    'Timeslot ' + cast(timeslot as nvarchar),
    'Theorical duration: ' + cast(theorical_break_duration as nvarchar) +
    ', Practical duration: ' + cast(break_duration as nvarchar) +
    ', Exceed: ' + cast(break_duration - theorical_break_duration as nvarchar) +
    ', Practical fixed break start: ' + cast(time_clock_break_start as nvarchar) +
    ', Practical fixed break end: ' + cast(time_clock_break_end as nvarchar), 0
    from #lvl1
    where break_duration_exceeded = 1

    select * from @anomalies

    -- Insert or update or delete in table anomalies
    MERGE anomalies as origin
    USING @anomalies as tmp
    ON (origin.date = tmp.date AND origin.employee_id = tmp.employee_id AND origin.anomaly_type_id = tmp.anomaly_type_id AND origin.level = tmp.level)
    WHEN MATCHED
        THEN UPDATE SET
            origin.description = tmp.description
    WHEN NOT MATCHED BY TARGET
        THEN INSERT (employee_id, anomaly_type_id, date, level, description, validated)
        VALUES (tmp.employee_id, tmp.anomaly_type_id, tmp.date, tmp.level, tmp.description, tmp.validated)
    WHEN NOT MATCHED BY SOURCE AND origin.date = @date
        THEN DELETE;
end;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regular expression: Should not start with 5 digits (or more) in a row I need to generate a regular expression to validate that the string does not start with 5 digits.
NOT VALID: 12345testing123asd

VALID: 1234testing1234
testing12345
testing

I tried to get the first five chars ^.{0,5} but I do not know hot to add the restriction of \D to those first 5 chars
Also, I tried with this [^0-9][^0-9][^0-9][^0-9][^0-9] but I do not know how to do to include the strings that starts with 4 or less numbers
Could you please help me with this? I am a rookie :(

A: If your RegExp flavor of choice supports negative lookaheads, this pattern will match if the string is valid (does not start with 5 or more consecutive digits):
^(?!\d{5,})

Regex101
Matches:

*

*1234testing1234

*testing12345

*testing

Does not match:

*

*12345testing123asd


text:
Q: How to chmod +x a file in Windows, for use in Linux? I have a file that needs to be executable in Linux, which I'd do by using chmod +x when using Linux.
My problem is: this file is compiled in Windows, and it's a pain to have to open my Ubuntu VM to just chmod it.
Is there a tool, or a method in Windows to allow me to add the +x permission to the file, so it is executable upon receipt to a Linux machine?
I've tried searching SU and Google, but I'm only seeing irrelevant results about how chmod doesn't exist on Windows, and to use file permissions instead - but this isn't what I'm looking for.

A: git update-index --chmod=+x myfile.sh

from https://www.scivision.dev/git-windows-chmod-executable/

A: chmod +x sets attribute in the filesystem and is not assiciated with the file itself. So, there is no way to do that you want.

A: The key phrase in your question is "executable upon receipt", and the answer depends on how it's being received. If you send a tarball, you can have some executable files in it. A single file could be mailed in uuencode format with begin 755 filename in the header. If you provide more details on what tools you have available on the sending side, we might be able to find a way to make it work.


text:
Q: How to differ between empty Platform.String and null Platform.String^ We're verifying that method arguments aren't null upon function entry, but this doesn't work for Platform::String (or Platform.String, no difference between C# or C++), since they overload the semantics of an empty string with a null instance.
Consider this, where the exception will always be thrown:
auto emptyString = ref new Platform::String();

// Now, emptyString.IsEmpty() will be true

if (emptyString == nullptr)
{
    throw ref new Platform::InvalidArgumentException();
}

The variable has a non-null value, but the == comparison operator is overloaded so comparing it to nullptr returns true since the String instance is empty.
As far as I can see this makes it impossible for us to make proper null checks at function entry for Strings. Is that really so?

A: Seems that you are right. Any string which is set to nullptr is treated as an empty string. And if you even pass nullptr to the function you will never get the NullReferenceException.
bool NullPtrTest(Platform::String^ value)
{
  return value == nullptr;
}

bool EmptyTest(Platform::String^ value)
{
  return value->IsEmpty();
}

bool ReferenceEqualsWithNullPtrTest(Platform::String^ value)
{
  return Platform::String::ReferenceEquals(nullptr, value);
}

bool EqualsWithValueTest(Platform::String^ value)
{
  return value->Equals("test");
}

//...

NullPtrTest(nullptr); // true
NullPtrTest(ref new Platform::String()); // true
NullPtrTest("test"); // false

EmptyTest(nullptr); // true - no exception
EmptyTest(ref new Platform::String()); // true
EmptyTest("test"); // false

ReferenceEqualsWithNullPtrTest(nullptr); // true
ReferenceEqualsWithNullPtrTest(ref new Platform::String()); // true
ReferenceEqualsWithNullPtrTest("test"); // false

EqualsWithValueTest(nullptr); // false - no exception
EqualsWithValueTest(ref new Platform::String()); // false
EqualsWithValueTest("test"); // true

So, I see no way to find out whether the string was ever nullptr.

A: There are no "null strings" in Windows Runtime.  "Null" and "empty" mean the same thing with respect to strings.
Despite the fact that Platform::String uses the ^ syntax and looks like a reference type, it's not:  it's a projection of a Windows Runtime fundamental type, HSTRING.  A "null" HSTRING is indistinguishable from an empty HSTRING.
Even if a Platform::String^ appears to be "null" (e.g. in the debugger), it is safe to treat it as if it were an empty string.  You can use it for concatenation, call s->Length(), etc.

In C#, a string can be null (and you can thus test it for null), but you will never get a null string from a Windows Runtime call and you cannot pass a null string as an argument to a Windows Runtime function (doing so will yield an exception at the ABI boundary).


text:
Q: "Given 2 ints, a and b, return true if one if them is 10 or if their sum is 10." How can I apply real numbers  package cornett1;

import java.util.Scanner;

public class CodeRat {

    public static boolean makes10(int a  , int b)
    {
         return (a + b == 10 || a == 10 || b == 10);

        }

        public static void main (String[] args) {
            Scanner s = new Scanner(System.in);
            System.out.print(makes10(s.nextInt(),s.nextInt());
        }
}

I am using a website called codingbat to do programming exercises and I solved the question
"Given 2 ints, a and b, return true if one of them is 10 or if their sum is 10." How can I apply this program and Input actual numbers.

A: Write a main method in the class, and pass in two numbers when invoking the program.
In the main method, Use
int a = Integer.parseInt(argument 0);
int b = Integer.parseInt(argument 1);

Now create a new instance of JOption class and invoke the method 'makes10' in the method with the arguments.
JOption opt = new JOption();
boolean answer = opt.makes10(a, b);

System.out.println(answer);

A: Read up on this:
http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
This tells you how to take arguments form the command line and use those as variables in your program.
public static void main (String[] args) {
    int a = Integer.parseInt(args[0]);
    int b = Integer.parseInt(args[1]);
    System.out.print(makes10(a,b));
}

If you want input at runtime, you can use the Scanner class or the Console class
Scanner s = new Scanner(System.in);
System.out.print(makes10(s.nextInt(),s.nextInt()));

A: You can use a Scanner to get input from a user :
Scanner sc = new Scanner(System.in);
System.out.println(makes10(sc.nextInt(),sc.nextInt()));

A: One of the easiest option you have is
java.util.Scanner

Defention: A simple text scanner which can parse primitive types and strings
  using regular expressions.

*

*A Scanner breaks its input into tokens
  using a delimiter pattern, which by default matches whitespace.

*The  resulting tokens may then be converted into values of different types
  using the various next methods.

Why using Scanner API?

1. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
2. A scanning operation may block waiting for input.
3 .A Scanner is not safe for multithreaded use without external synchronization.

For example:
 Scanner input = new Scanner(System.in);
 int i = sc.nextInt();
 System.out.println("the number you entered is " + i);

Explanation:
you read from console and feed scanner variable which is input and you just want to read int. at the end, you print the read number on the console
Resources

*

*first one

*second one
Another option is using BufferedReader API

Reads text from a character-input stream, buffering characters so as
  to provide for the efficient reading of characters, arrays, and lines.
  The buffer size may be specified, or the default size may be used. The
  default is large enough for most purposes.

take a look at this sample for your BufferReader need
BufferReader vs Scanner

*

*BufferedReader has significantly larger buffer memory than Scanner. Use BufferedReader if you want to get long strings from a stream, and use Scanner if you want to parse specific type of token from a stream.

*Scanner can use tokenize using custom delimiter and parse the stream into primitive types of data, while BufferedReader can only read and store String.

*BufferedReader is synchronous while Scanner is not. Use BufferedReader if you're working with multiple threads.
In your case:
    int a = 0;
    int b = 0;
    Scanner input = new Scanner(System.in);
    System.out.println("Please enter two numbers");
    a = input.nextInt();
    b = input.nextInt();
    JOption jp = new JOption();
    jp.makes10(a, b);
}

public boolean makes10(int a, int b) {
    return ((a + b) == 10 || a == 10 || b == 10);

}


text:
Q: Простейшая обработка данных Ajax. Есть плагин jQuery.Form
Я отправляю данныe из формы php-скрипту.
$('#form').ajaxForm(
    function() {
        $("#form").clearForm();
            alert("Запись добавлена");
        }
    );
Все работает. Но сервер возвращает данные. Одно-единственное слово. Как мне записать ответ в переменную JavaScript? Знаю что как то через options->success, но не получается.
P.S. Как вариант - можно просто на jQuery. Без плагина.
A: // Объект с опциями для плагина
var options = {
    target:     '#divToUpdate',
    url:        'comment.php',
    resetForm: true, // вместо вашего $('#myForm').clearForm()
    success:    function( data ) {
        alert(data);
    }
};

// скармливаем их плагину
$('#myForm').ajaxForm(options);


text:
Q: Check if file exist by API Revit I have a file that is a Hidden system file - it is placed in the program files folder.
I what to check if it exists, but I'm checking it from a dll run by Revit API.
I do it from computers in my firm but for some users, this doesn't work and I don't know why.
I change this file to be only hidden, but it didn't help,
I change place where this file is created, but it didn't help,
I try to reproduce it and I thought I find a solution. I end up doing this monstrosity
    private bool FileExist2(string path)
    {
        FileInfo fi = new FileInfo(path);
        if (fi.Exists)
            return true;
        else
        {
            try
            {
                if (fi.Attributes == (FileAttributes)(-1))
                {
                }
            }
            catch (System.UnauthorizedAccessException)
            {
                return true;
            }
            catch (Exception)
            {
            }
        }
        return false;
    }

but I still have the same tickets coming in. The problem is for windows 10.
Now I don't even know where to search for a solution, or what is the problem.
Is it possible to force one program to have zero access to other folders or files created by other programs?
I only want to know if this file exists.
I know that this file exists because other programs see it.
Help


text:
Q: System.Indexoutofrangeexception error not understood Hi i am a beginner at c# and i did not understand why the exception is thrown at the program shown below
PROGRAM:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, i, x=0, y=0;
            Console.WriteLine("Enter the degree of matrix:");
            n = int.Parse(Console.ReadLine());
            int[,] num = new int[n, n];
            int p = n * n;
            for (i = 1; i <= p; i++)
            {
                num[x, y] = i;
                if (num[x, y] % n == 0) { y++; }
                if (y % 2 == 0) { x++; }
                if (y % 2 != 0) { x--; }
            }
            for (i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    Console.Write(num[i, j] + " ");
                }
                Console.WriteLine();
            }
            Console.ReadLine();
        }
    }
}

REQUIRED RESULT:
Enter order of matrix:
4

1 8 9  16
2 7 10 15
3 6 11 14
4 5 12 13

But an exception as stated in the topic is thrown at num[x ,y]=i; . I do not understand why System.IndexOutOfRangeException occurs as the loop clearly ends at the end of the 2d array.
P.S. the program is meant to run only once.

A: Maybe I'm wrong, but if you insert 2 as degree of the matrix, the variable p equals 4.
The external for cycle
for (i = 1; i <= p; i++)

cycles 4 times, from 1 to 4. But when i == 4, X equals -1, and you cannot access a matrix with negative index. You get the same behavior with degree = 4, like in your example.

A: You must not change your x value in the same loop iteration where you change the y value because doing that, you don't fill the last position in the second column and subsequently iterate down to x = -1 which is an invalid index.
    for (i = 1; i <= p; i++)
    {
        num[x, y] = i;
        if (i % n == 0) {
            y++;
        }
        else {
            if (y % 2 == 0) { x++; }
            if (y % 2 != 0) { x--; }
        }
    }
    for (i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            Console.Write(num[i, j] + " ");
        }
        Console.WriteLine();
    }

A: You can try this one: you made just a basic mistake, here x is decrement at time of y increment, using continue statement skip loop after increment y, I guarantee this working 100%.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StackOverflow
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, i, x = 0, y = 0;
            Console.WriteLine("Enter the degree of matrix:");
            n = int.Parse(Console.ReadLine());
            int[,] num = new int[n, n];
            int p = n * n;

            for (i = 1; i <= p; i++)
            {
                try
                {
                    num[x, y] = i;
                    if (num[x, y] % n == 0) { y++; continue; }
                    if (y % 2 == 0) { x++; }
                    if (y % 2 != 0) { x--; }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }

            for (i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    Console.Write(num[i, j] + " ");
                }
                Console.WriteLine();
            }
            Console.ReadLine();
        }
    }
}


text:
Q: How to find $\frac{d}{dx}2x^{2x}$ by implicit differentiation?
Use logarithmic differentiation to differentiate the function with respect to $x$:  $$y=(2x)^{2x}$$

I took the natural logarithm of both sides to get
$$
\ln(y)=2x \ln(2x)
$$ And then the implicit differentiation is
$$\frac{d}{dy}(\ln(y)) \times \frac{dy}{dx}=\frac{d}{dx}2x\ln(2x)$$
That is,
$$\frac{1}{y} \times \frac{dy}{dx}=2 \times \ln(2x) + 2x \times \frac{1}{x}$$ Multiplying both sides by $y=2x^{2x}$ I get
$$\frac{dy}{dx}=2x^{2x} \times (2\ln(2x)+2)$$
 Factor out the $2$ to get
$$\frac{dy}{dx}=2x^{2x} \times 2(\ln(2x)+1)$$
The solution shows that

My question is in the solution: it's shown as $\ln(x)$ instead of $\ln(2x)$. I understand the derivatives are the same and that constant is just a multiplier for scaling, but I'm a little confused at that point.

A: 1) The problem on the worksheet is $2x^{2x}$ and not $(2x)^{2x}.$
This is your fundamental problem.
2) You have a big mistake in your simplification.
 $(2x)^{2x}(2f(x)) \ne (4x)^{2x}f(x)$
3) $\ln(2x) = \ln x + \ln 2$ so sometimes you will not agree with the answer sheet because of this. This is not your problem, but something to be aware of.


text:
Q: Image won't resize in height when it shrinks in width I have an image in a div which can be of various resolutions. If I have a wider image with low height (ex. 730x90) it doesn't show properly on mobile. It shrinks in width but the height remains the same. Here's the code (I'm writing CSS in JS using React so that's valid code, the exact synthax isn't the problem here). child is a span which only contains a single img inside.
    parent: {
        '@media(max-width:744px)': {
            minWidth: '100vw',
        },
        '@media(max-height:823px)': {
            minHeight: 'auto',
        }
    },
    child: {
        '@media(max-width:744px)': {
            maxWidth: '80vw',
            maxHeight: '100vw',
            width: 'auto',
            height: 'auto',
            display: 'block',
            margin: 'auto'
        }
    }

A: Try injecting some JQuery:
 window.onresize = function() {
    $(".thumb").each(function() {
        this.style.display = "none";
        this.offsetWidth;
        this.style.display= "block";
    })
}

Let me know your results!


text:
Q: Questions about special relativity, index in the Lorentz matrix I'm studying special relativity
I have read this:
We have $ x^u = (ct, x^1,x^2,x^3) $. If we apply Lorentz transformation we can write:
$x'^u = \Lambda^{u}_{\hspace{0,2 cm}\nu} x^{\nu} $
$x'_u = \Lambda_{u}^{\hspace{0,2 cm}\nu} x_{\nu} $
Where he have defined the Lorentz matrix:
$\Lambda^{u}_{\hspace{0,2 cm}\nu} (v) =  \begin{bmatrix} \gamma &  -\gamma \beta & 0 & 0 \\ -\gamma \beta & \gamma & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0& 1 \end{bmatrix}
$ ; $\qquad\Lambda_{u}^{\hspace{0,2 cm}\nu} (v) =  \begin{bmatrix} \gamma &  \gamma \beta & 0 & 0 \\ \gamma \beta & \gamma & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0& 1 \end{bmatrix}
$
Is the space between the $\Lambda$ and $ \nu$ (down in the former and up in the latter) written only to indicate that are two different matrix or is there something more?

A: The comment of gingras.ol is useful but this link is more useful to clarify my doubt
Difference between slanted indices on a tensor


text:
Q: How to refresh the workspace in eclipse after adding new files? I'm creating a web-app using Spring MVC. This app creates some images and saves them into a directory located in the webapp directory and then returns a view like the following:

The problem is I'm not getting the images, I have to do a refresh on Eclipse to get those images.
Any ideas?

A: Ok so to elaborate more on the links I put in the comments.
I stumble upon two ways of doing what you need (didn't actually do them but they seemed to work for others):
1) Refreshing Eclipse Workspace using ANT (Answer Link)
As stated in the link, Eclipse provides several ant tasks that you can use for various purposes, one of which is the <eclipse.refreshLocal /> tag:
<eclipse.refreshLocal resource="MyProject/MyFolder" depth="infinite"/>

*

*resource is a resource path relative to the workspace

*depth can be one of the following: zero, one or infinite

Furthermore, if you get a BUILD FAILED error, make sure you aren't running ANT outside of the Eclipse JRE. To fix this, go open up the External Tools Dialog (Run > External Tools > Open External Tools Dialog...) and make sure the JRE tab is set to "Run in the same JRE as workspace."
2) Refreshing Eclipse workspace programmatically using the IResource.refreshLocal() API (Answer Link)
As stated in the linked answer, you can do this at project root, a particular folder or an individual file.
To refresh all projects in a workspace, simply enumerate all projects using ResourcesPlugin.getWorkspace().getRoot().getProjects() API and refresh each in turn.
Here is another example (from the API website) that sets the contents of a file using a FileOutputStream, and then uses refreshLocal to synchronize the workspace.
   private void externalModify(IFile iFile) throws ... {
      java.io.File file = iFile.getLocation().toFile();
      FileOutputStream fOut = new FileOutputStream(file);
      fOut.write("Written by FileOutputStream".getBytes());
      iFile.refreshLocal(IResource.DEPTH_ZERO, null);
   }


text:
Q: has_one/has_many rails association with alternate source ID other then primary key I have 3 models.
Model A belongs to model B and model B has many model C
by using through I can set in model A class has_many :c,through: :b
Now whenever I call a_instance.cs It would JOIN with table B unnecessarily What I want is direct association of A & C using b_id in both A & C class.
So how can I write a has_one/has_many rails association without through clause when both Source and Destination entities has same foreign_key of 3rd entity?  (b_id for this example)
class C
  belongs_to :b #b_id column is there in DB
end

class B
  has_many :cs
end

class A
  belongs_to :b #b_id column is there in DB
  has_many :cs , through: :b #This is the association in Question

  #WHAT I WANT TO DO. So something in place of primary_key which would fetch C class directly.
  has_many :cs ,class_name: 'C',foreign_key: 'b_id',primary_key: 'b_id'
end

A: An example, Teacher and Student models belong to Group, Teacher has many Student:
class Group < ApplicationRecord
  has_many :teachers
  has_many :students
end

class Teacher < ApplicationRecord
  belongs_to :group
  has_many :students, :foreign_key => 'group_id', :primary_key => 'group_id'
end

class Student < ApplicationRecord
  belongs_to :group
end

And you can retrieve a teacher's students in a group like this:
teacher = Teacher.find(:teacher_id)
students = teacher.students

A: Following your example of classes A,B & C and changing only the implementation of class A.
class A
  belongs_to :b

  def cs
    self.id = b_id
    b_cast = self.becomes(B)
    b_cast.cs
  end
end

Console
A.first                    ==>#<A id: 105, b_id: 1 ...>
B.first                    ==>#<B id: 1 ...>
C.all                      ==>#<C id: 1, b_id: 1 ...>,
                              #<C id: 2, b_id: 1 ...>,
                              #<C id: 3, b_id: 1 ...>,
                              #<C id: 4, b_id: 1 ...>

A.first.cs
A Load (0.2ms)  SELECT  "as".* FROM "as" ORDER BY "as"."id" ASC LIMIT ?  [["LIMIT", 1]]
C Load (0.1ms)  SELECT  "cs".* FROM "cs" WHERE "cs"."b_id" = ? LIMIT ?  [["b_id", 1], ["LIMIT", 11]]

A.first.cs                 ==>#<C id: 1, b_id: 1 ...>,
                              #<C id: 2, b_id: 1 ...>,
                              #<C id: 3, b_id: 1 ...>,
                              #<C id: 4, b_id: 1 ...>

Official #becomes(klass) documentation can be found
here!
On other end, the same effect can be achieved creating an instance of the class B and giving it the id stored in A.first.b_id as follows:
B.new(id: A.first.b_id).cs
A Load (0.2ms)  SELECT  "as".* FROM "as" ORDER BY "as"."id" ASC LIMIT ?  [["LIMIT", 1]]
C Load (0.1ms)  SELECT  "cs".* FROM "cs" WHERE "cs"."b_id" = ? LIMIT ?  [["b_id", 1], ["LIMIT", 11]]

B.new(id: A.first.b_id).cs ==>#<C id: 1, b_id: 1 ...>,
                              #<C id: 2, b_id: 1 ...>,
                              #<C id: 3, b_id: 1 ...>,
                              #<C id: 4, b_id: 1 ...>


text:
Q: Github file exceed 100MB I know there is many many threads about this but being a noob to coding I do not understand what the codes people reply with...
My issue is the file is too big. Now during hours of searching, I found a solution, Github's LFS. The issue is that I can't manage to activate it. As well as I tried making a new repository to upload my project (hoping it will take the entire project).
Any sugestions?
Thanks in advance!

A: Github have documented this and set up restrictions against pushing files over 100mb.
And more info about it here
It seems like there is no way around this. You'll need to either break up the file into smaller pieces or look for other alternatives.
Other users have mention this:
https://stackoverflow.com/a/34780618/3010171
I'm not sure if that fits your project.


text:
Q: Is there a way to route all WIFI traffic through an SSH tunnel to the internet? I would like to secure all wireless traffic on my local network with ssh.
Tablet/Smartphone/Computer/etc ==> WIFI Router ==> SSH TUNNEL ==> Internet
Are there routers capable of this?


text:
Q: Accessing Data From ArrayList I m working on populating a list dynamically with dynamic rows and columns and showing them in UI.  All have been done accurately but i m unable to get value from a specified row and column e.g. row 4 and column 3.  Code is as under:-
    public LiveRangeService() {
    tableData = new ArrayList< Map<String, ColumnModel> >();

    //Generate table header.
    tableHeaderNames = new ArrayList<ColumnModel>();
    for (int j = 0; j < 10; j++) {
          tableHeaderNames.add(new ColumnModel("header "+j, " col:"+ String.valueOf(j+1)));
    }

    //Generate table data.
    for (int i = 0; i < 8; i++) {
        Map<String, ColumnModel> playlist = new HashMap<String, ColumnModel>();
        for (int j = 0; j < 10; j++) {
            playlist.put(tableHeaderNames.get(j).key, new ColumnModel(tableHeaderNames.get(j).key,"row:" + String.valueOf(i+1) +" col:"+ String.valueOf(j+1)));
        }
        tableData.add(playlist);
    }
    try {
        System.out.println( "Table Data Size " + tableData.size() );
        System.out.println( "Value Of Row 1 Col 2: " + tableData.get(1).get(2) );
    } catch (Exception e) {
        System.out.println( "Error!! " + e.getMessage() );
    }
}

may some body pls help me in understanding this chunk of code.  Error occurs on the following line:-
            System.out.println( "Value Of Row 1 Col 2: " + tableData.get(1).get(2) );

the result shown on page

A: tableData = new ArrayList< Map<String, ColumnModel> >();

you are storing maps in list and this map is of generic
means key in map is String.
tableData.get(1).get(2)

This above line get(1) will give you first Map object.
then get(2), means you are passing Integer as key to fetch value from map but your map needs String as key.
Its map and value can be retrieved using key and not based on index like arrayList. so you are getting error
pass something like
tableData.get(1).get(<some string key>)

it should work

A: Java counts starting from 0.
tableData.get(0).get(0) will get the element at row 1, and column 1. The ArrayList containing Maps starts from 0. However, tableData.get(tableData.size()) will throw an error, as it will contain the number of elements in the ArrayList. (So, if an array had 3 elements, tableData.size() would return 3 and you would be able to call for it by calling for tableData.get(2))
tableData.get(1).get(2) will get the element at row 2, and column 3.
To get the value of the element at row 1, column 2, call tableData.get(0).get(1).

A: Fianlly with the help of LHCHIN, the key was header 0, header 1 etc and it worked great. finally i wrote: tableData.get(1).get("header 2").getValue() and it worked perfectly.


text:
Q: PDO : Invalid parameter number: number of bound variables does not match number of tokens I can't figure out why I am getting the SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens error message with the following code:
$myArr = array(283908,283951,284024,284064,284076,284099);
$num = count($myArr);

$req = "select * from MyTable where Id in (?,?,?,?,?,?) limit ?,?";

$start = 0;
$limit = 3;

try {
   $sql = $pdo->prepare($req);
   $sql->bindParam($num+1, $start, PDO::PARAM_INT);
   $sql->bindParam($num+2, $limit, PDO::PARAM_INT);
   $sql->execute($myArr);
}
catch(PDOException $e) {
   pdo_error($e->getMessage());
}

The first 6 questions marks are bound with myArr content and the 2 last ones with limits. This is just an example, in the real life myArr can content more than 100 values and its size is not fixed.

A: When you call PDOStatement::execute() with an array of parameters, it will not use the parameters specified in calls to PDOStatement::bindParam(). Instead, just append the $start and $limit variable to the end of $myArr and call $sql->execute().
try {
   $sql = $pdo->prepare($req);
   $myArr[] = $start
   $myArr[] = $limit

   $sql->execute($myArr);
}

See this comment on the PHP PDO documentation.


text:
Q: What is the relative path for application.properies file below?
application.properties need to be loaded in LoadProperties.java file.
public static Properties loadProperties() {
    Properties props = new Properties();
    try{
        FileInputStream fis = new FileInputStream("application.properties");
        props.load(fis);
        fis.close();
    }catch(IOException ioe){
        ioe.printStackTrace();
    }
    return props;
}

The above code works fine in normal Java Project but when I add this in Dynamic Web project path not recognized because folder structure is differ
I tried in many ways and got java.io.FileNotFoundException: application.properties (The system cannot find the file specified) error
Any help would be appreciated!

A: You can try something like this:
Properties props = new Properties();

//with properties in the root dir
props.load(getClass().getResourceAsStream("/application.properties"));

A: Using classloader :
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("your.properties").getFile());

Using classloader with stream :
ClassLoader classLoader = getClass().getClassLoader();
InputStream in = classLoader.getResourceAsStream("your.properties");

Using ResourceBundle :
ResourceBundle labels = ResourceBundle.getBundle("your.properties", locale);
System.out.println(labels.getString("label1"));

A: If I add files at eclipse installation and give path like below It works fine for me.
FileInputStream fis = new FileInputStream("application.properties");


text:
Q: JSF h:outputStylesheet id attribute not working I have a strange behavior of h:outputStylesheet.
I need to give an Id to my stylesheet in order to change it via jQuery.
But the weird thing the tag doesn't render the "link" tag with an ID !
Here's my Code
<h:outputStylesheet  id="skinstyle" library="default" name="css/style.red.css" />

and the output is this
<link type="text/css" rel="stylesheet" href="/MyApp/faces/javax.faces.resource/css/style.red.css?ln=default">

I've got Mojarra 2.1.11 ,jBoss 7.1.3, Primefaces 3.5 (although Primefaces has nothing todo with this, just saying)!

A: It looks like a bug in jsf implementation...
Meanwhile as workaround to access your link and modify you can try using jquery selector
For example:
$(document).find("link[href*='part_of_your_css_name']").attr("new_css_name"),


text:
Q: Как реализовать изменение значений в полях в реальном времени (тег select)? Разрабатываю одно приложение на Django.
БД имеется.
Есть форма, в которой 3 поля (каждое из них - это select).
Выглядит она вот так:
<form action="{% url 'main:index' %}" method="post">
  <div class="form-group">
    <select class="form-control" name="country">
      {% for country in countries %}
        <option>{{ country }}</option>
      {% endfor %}
    </select>
    <select class="form-control" name="league">
      {% for ountry in countries %}
        <option>{{ country }}</option>
      {% endfor %}
    </select>
    <select class="form-control" name="team">
      {% for country in countries %}
        <option>{{ country }}</option>
      {% endfor %}
    </select>
  </div>
  <button class="btn btn-primary" type="submit">Найти</button>
</form>

Сейчас там просто 3 поля с выбором страны.
Я хочу реализовать следующее:

При выборе страны в первом поле, во втором появляются только элементы
принадлежащие к этой стране, а в третьем поле уже элементы
принадлежащие только к элементу из второго поля. Таким образом
выбирается один конкретный элемент.

Я примерно понимаю, что должно происходить в бэкенде. По значению из первого поля данные в базе фильтруются и передаются во второе поле, после - такая же процедура, только уже со вторым и третьим полями.
А вот как это реализовать так, чтобы значения в полях менялись, так сказать, в реальном времени - не понимаю.
Буду рад любым ответам и идеям.
Спасибо.

A: Нужно подписатся на событие onchange у первого и второго select. и вызывать вде функции. По смене первого (выборе страны), получать его значение и отправлять ajax запрос на сервер, сервер должен будет прислать нужные данные для второго select. Для их отображения можно сделать:
select2.innerHTML = "";
for (let i = 0; i < response; i++) {
    select2.innerHTML += <option>response[i]</option>;
}

*response - переменная с данными из ajax.
Таким образом, первым действием select2.innerHTML = ""; очищается все.
А циклом добавляются новые значения.


text:
Q: Euler Representation of the factorial I know that Euler proved that
$\displaystyle z! = \int_{0}^{1} \left(- \ln\left(t\right)\right)^z dt$
How can this be proven?

A: With definition of Gamma function
$$\Gamma(x)=\int_0^\infty e^{-t}t^{x-1}\ dt$$
let $e^{-t}=u$ then
$$\Gamma(x)=\int_1^0 u(-\ln u)^{x-1}\dfrac{-1}{u} du$$
and so
$$x!=\Gamma(x+1)=\int_0^1 (-\ln u)^{x} du$$


text:
Q: Data compression within Internal Tables in SQL server 2008R2 We are doing downgrade from enterprise to standard for couple of servers which are not using any enterprise features:
For one of our TFS(Team foundation server) database TFS_resx, when we ran
SELECT * FROM sys.dm_db_persisted_sku_features

it returns null value for each column specifying that this database is not using any of enterprise features:
However, when we run the query as shown below to find at object level for any kind of compression used, we found one for internal table:
select so.name,so.type,so.type_desc,
sp.data_compression,sp.data_compression_desc
from sys.partitions sp
inner join sys.objects so
on (so.object_id=sp.object_id)
where sp.data_compression!=0

it says row compression is being used for an internal table

So, i would like to know how come this is not captured as an enterprise feature when i ran SELECT * FROM sys.dm_db_persisted_sku_features. Or may be it is not one.
Just curious in case anyone has witnessed if we need to remove this row compression from internal table of the DB in question or we would be good to downgrade (restore the tfs db onto standard version).
Thanks!


text:
Q: Skip line after a pick with chosen jQuery I'm using chosen jQuery for multiple select. How can I skip a line after I select one value ?
<select class="form-control chosen-select" multiple  name="seguro_medico[]" >
  <option></option>
  <?php
    foreach($seguro_medico as $row) {
      echo '<option value="'.$row->medical_insurance.'">'.$row->medical_insurance.'</option>';
    }
  ?>
</select>

// jQuery
$(".chosen-select").chosen({
  no_results_text: "Oops, nada encontrado por : "
});

A: You can do this using CSS.
Use:
.chosen-choices li {
    display: block;
    width: 100% !important;
}


text:
Q: Adding different kinds of entities to table of contents I have a number of different kinds of entities in a document using the book documentclass.  There are Chapters, Labs, Appendices, etc.
Just taking labs as an example, I created a newcommand that defines labs and autonumbers them.
I would like them to be in the table of contents at the same level as a Chapter.  Right now, as a quick hack, I make labs chapters, which makes them show up, but they display a chapter number and a lab number.
\newcounter{lab}
\newcommand{\lab}[1]{\stepcounter{lab} \chapter{Lab \arabic{lab}: #1}}

How do I specify what entities go into a table of contents?
In addition, if I were to create my own independent equivalent of a chapter,
In this other question: Custom \chapter definition
In one of the answers, I saw reference to the definition of the chapter macro, and I am not seeing how chapter sets the font and text size?  Here is the code:
\newcommand\chapter{\if@openright\cleardoublepage\else\clearpage\fi
                    \thispagestyle{plain}%
                    \global\@topnum\z@
                    \@afterindentfalse
                    \secdef\@chapter\@schapter}

The upshot is, how can I create new entities to put into a table of contents, and how do those entities define their look?

A: \addtocontents write a record to the file toc which is read by \tableofcontents the next time latex is run. Examine the .toc file to see results.  \string\contentsline for example writes "\contentsline" but does not expand it.  The {chapter} entry has something to do with distinguishing chapters from sections, etc.  The rest is the same as with chapters except I use \thelab instead of \thechapter.
\documentclass{book}

\makeatletter
\newcounter{lab}% also defines \thelab

% roughly equivalent to \chapter
\newcommand{\lab}[1]{% #1 is lab heading
  \refstepcounter{lab}%
  \if@openright\cleardoublepage\else\clearpage\fi%
  \addtocontents{toc}{\string\contentsline {chapter}%
    {\hbox to .65in{Lab}\protect\numberline{\thelab}#1}{\thepage}}%
  \global\@topnum\z@% page number to bottom?
  \noindent%
  \@lab{#1}% fixed first character separation
}

% roughly equivalent to \@chapter
\def\@lab#1{% #1 is lab heading
  \if@twocolumn%
    \@topnewpage[{\huge\bfseries Lab \thelab: #1\par}]%
  \else{\huge\bfseries Lab \thelab: #1\par}%
  \@afterheading% no idea
  \fi}

% copied from mwe
\renewcommand\chapter{\if@openright\cleardoublepage\else\clearpage\fi
   \thispagestyle{plain}%
   \global\@topnum\z@
   \@afterindentfalse
   \secdef\@chapter\@schapter}

% copied from book.cls and modified
\def\@chapter[#1]#2{%
  \ifnum \c@secnumdepth >\m@ne
    \if@mainmatter
      \refstepcounter{chapter}%
      \typeout{\@chapapp\space\thechapter.}%
      \addtocontents{toc}{\string\contentsline {chapter}%
        {\hbox to .65in{Chapter}\protect\numberline{\thechapter}#1}{\thepage}}%
    \else
      \addtocontents{toc}{\string\contentsline {chapter}%
        {\hbox to .65in{Chapter}\protect\numberline{\thechapter}#1}{\thepage}}%
    \fi
  \else
    \addtocontents{toc}{\string\contentsline {chapter}%
      {\hbox to .65in{Chapter}\protect\numberline{\thechapter}#1}{\thepage}}%
  \fi
  \chaptermark{#1}%
  \addtocontents{lof}{\protect\addvspace{10\p@}}%
  \addtocontents{lot}{\protect\addvspace{10\p@}}%
  \if@twocolumn
    \@topnewpage[\@makechapterhead{#2}]%
  \else
    \@makechapterhead{#2}%
    \@afterheading
  \fi}
\makeatother

\begin{document}
\tableofcontents
\chapter{In the beginning}

This space intentionally left blank.

\lab{Eat the apple.}

This space intentionally left blank.
\end{document}


text:
Q: How can I have a Makefile target update dependent on the value of an environment variable? I have a make target that will have different output depending on the value of an environment variable.
How can I:

*

*skip the dependency and not re-make the target if the environment variable has not changed the last run

*make or re-make the target if the environment variable is not set or has changed

I thought I could create or conditionally update a file with the current environment variable value and then use that file as a make dependency. I couldn't find an elegant way to do that with native tools. (sed -i always updated the file's timestamp, maybe awk is possible)

A: How about using a shell script to update a file that holds the variable value?
SHELL = /bin/bash
var_file := var.txt
var_name := NAME

is_var_updated = [[ ! -e $(var_file) ]] || [[ "$$(< $(var_file))" != "$($(var_name))" ]]
update_var_file = echo "$($(var_name))" > $(var_file)

$(shell $(is_var_updated) && $(update_var_file))

output.txt: $(var_file)
    echo "Name is $$NAME" > $@

This works like this.
$ ls
Makefile
$ NAME=foo make
echo "Name is $NAME" > output.txt
$ NAME=foo make
make: `output.txt' is up to date.
$ NAME=bar make
echo "Name is $NAME" > output.txt

A: Make conditionals could be a starting point:
.PHONY: all

FILE := foobar
ifdef ENV_VAR
OLD_ENV_VAR := $(shell [ -f $(FILE) ] && cat $(FILE))
ifeq ($(ENV_VAR),$(OLD_ENV_VAR))
DONTRUN := 1
endif
endif

ifdef DONTRUN
all:
    @echo 'ENV_VAR unmodified'
else
$(shell printenv ENV_VAR > $(FILE))
all:
    @echo 'ENV_VAR undefined or modified'
endif


text:
Q: Append Key into JSON_OBJ_COLUMN - Oracle In Oracle 12c I created one table with json objects.
Imagine the next sample:

id
date
json_obj

1
01-MAY-2021
{   key_1: val1, key_2: val2}

Now I want to update key_2 value, and append key_3: val3 into the same json object related with id 1.
That could be edited? or I must to overwrite?

A: Provided that your DB version is 12R2+, then you can use PARSE() and PUT() for object type JSON_OBJECT_T consecutively, and then apply a standard UPDATE statement such as
DECLARE
  jobj JSON_OBJECT_T;
  jdoc tab.json_obj%TYPE;
BEGIN
  SELECT json_obj
    INTO jdoc
    FROM tab
   WHERE id = 1;

  jobj := JSON_OBJECT_T.PARSE( jdoc );
  jobj.PUT( 'key_2', 'val_22' );
  jobj.PUT( 'key_3', 'val_3' );
  jdoc := jobj.TO_CLOB();

  DBMS_OUTPUT.PUT_LINE( jdoc );

  UPDATE tab
     SET json_obj = jdoc
   WHERE id = 1;
END;
/


text:
Q: How to grant permissions to Webapp Web Analytics Reports in Central Administration My management department asks for access on the Web Analytics reports for the whole web application. I tried giving them the permissions to see Web Analytics, but they are still not able to login into Central Administration. Is there a possibility granting them acces to the reports, without giving them CA Administration rights?

A: freaky,
Making everyone a Farm Administrator on Central Admin is not a good idea, you should ask them to see Site Collection and Site level Web Analytics Data instead of whole Web Application!
However, one way is to put user in Security -> Manage the farm Administrators Group -> [Add user in this group] and now they should see Web Analytics Reports
About Site Collection and Site level Web Analytics Reports:
Out-of-the-box, these reports are visible to Administrators at each level.  For example, site-level reports are available to Site Administrators of those sites.  And there is also a new permission level, "View Web Analytics Data" that will allow users to access these reports without having to give them Administrator privileges.
You can access Web Analytics reports by going to Site Actions -> Site Settings.  Under the Site Actions heading you will see two links, Site Web Analytics Reports and Site Collection Web Analytics Reports.
Source

A: In SharePoint 2010, there is a permission called View Web Analytic Data - View reports on Web site usage. You can create a group having Read + this permission.
EDIT:
Try configuring permissions by following these steps and after it you can create a Web Analytics Web Part (located at the end of the linked article) in a site where they have access to.


text:
Q: Rails form with a subset of has_many :through checkboxes I have a fairly straightforward application for assigning Abilities to Users, using Permissions as a join table. I've included the model definitions below.
However, Abilities also belong to a Client. The form for adding Abilities to a User contains only the Abilities for a specific Client.
As the form only returns checked ability_ids for that client, if I simply use
@user.update(params[:user].permit({:ability_ids => []}))

with form
= simple_form_for(@user, url: user_permissions_path, method: :patch do |f|
  = f.hidden_field :client_id, value: @client.id, name: :client_id
  = f.association :abilities, as: :check_boxes, collection: @client.abilities

Then all permissions for all other client applications are deleted for that user. This is the controller update code I'm using currently, but i'm pretty confident there's a more 'Rails way' to do this.
# permissions_controller#update

# Filter empty elements
update_abilities  = params[:user][:ability_ids].reject { |c| c.empty? }

# Get list of current ability ids
current_abilities = @user.abilities.for_client(@client).pluck(:id).collect{ |i| i.to_s }

abilities_for_deletion = @user.permissions.where(ability_id: current_abilities - update_abilities)
abilities_for_deletion.delete_all unless abilities_for_deletion.empty?

abilities_for_addition = Ability.find(update_abilities - current_abilities)
@user.abilities.push(abilities_for_addition)

class User < ActiveRecord::Base
  has_many :permissions, dependent: :destroy
  has_many :abilities, through: :permissions do
    def for_client(client)
      where('abilities.client_id' => client.id)
    end
  end
end

class Permission < ActiveRecord::Base
  belongs_to :ability
  belongs_to :user
end

class Ability < ActiveRecord::Base
  has_many :permissions, dependent: :destroy
  belongs_to :client
end

I ask because I now need to modify user groups via the same form, which also belong to a specific client, and would require large duplication of this update code.
Thanks.


text:
Q: How to handle conflicting Visual State Setters in separate Visual State Groups? Let's say I've got a RadioButton style defined in a XAML ResourceDictionary (no code-behind):
<Style x:Key="ExampleRadioButtonStyle"
       TargetType="RadioButton">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="RadioButton">
                <Grid x:Name="Root">
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal" />
                            <VisualState x:Name="PointerOver">
                                <VisualState.Setters>
                                    ???
                                </VisualState.Setters>
                            </VisualState>
                        </VisualStateGroup>
                        <VisualStateGroup x:Name="CheckStates">
                            <VisualState x:Name="Checked">
                                <VisualState.Setters>
                                    <Setter Target="Content.Fill" Value="White" />
                                    <Setter Target="Content.Stroke" Value="Blue" />
                                </VisualState.Setters>
                            </VisualState>
                            <VisualState x:Name="Unchecked">
                                <VisualState.Setters>
                                    <Setter Target="Content.Fill" Value="Transparent" />
                                    <Setter Target="Content.Stroke" Value="Black" />
                                </VisualState.Setters>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <Ellipse x:Name="Content"
                             StrokeThickness="5"/>
                </Grid>
        </ControlTemplate>
    </Setter.Value>
</Setter>

Now I want to change the Content.Stroke property when the CommonStates.CurrentState is PointerOver to:

*

*Cyan when the CheckStates.CurrentState is Checked

*Gray when the CheckStates.CurrentState is Unchecked
What is the best way to achieve that?
Please note that this is just a simplified example prepared to present my problem which is much more complex in reality (for example I need to handle all CommonStates) so I look for a decent solution not a simple workaround handling only the mouse over behavior.

A: According to the code you provided, we can't directly get the selected state of the RadioButton from PointerOver.You can follow the native style,create two Ellipse,one for the selected state and the other for the unselected.Use the Check status switch to show or hideEllipse.Then set the stroke in PointerOver.For example:
<Ellipse x:Name="Content" Fill="{StaticResource RadioButtonOuterEllipseFill}" Height="20" StrokeThickness="{ThemeResource RadioButtonBorderThemeThickness}" Stroke="{ThemeResource RadioButtonOuterEllipseStroke}" UseLayoutRounding="False" Width="20"/>
<Ellipse x:Name="CheckedContent" Fill="{ThemeResource RadioButtonOuterEllipseCheckedFill}" Height="20" Opacity="0" StrokeThickness="{ThemeResource RadioButtonBorderThemeThickness}" Stroke="{ThemeResource RadioButtonOuterEllipseCheckedStroke}" UseLayoutRounding="False" Width="20"/>

When the CheckStates.CurrentState is Checked,you can show the CheckedContent and hide Content,the UnChecked the opposite.
<VisualStateGroup x:Name="CheckStates">
    <VisualState x:Name="Checked">
        <VisualState.Setters>
            <Setter Target="Content.Opacity" Value="0"></Setter>
            <Setter Target="CheckedContent.Opacity" Value="1"></Setter>
            <Setter Target="CheckedContent.Fill" Value="White" />
            <Setter Target="CheckedContent.Stroke" Value="Blue" />
        </VisualState.Setters>
    </VisualState>
    ......
</VisualStateGroup>

Then you can set stroke for different states in PointerOver.
<VisualState x:Name="PointerOver">
    <VisualState.Setters>
        <Setter Target="Content.Stroke" Value="Gray"></Setter>
        <Setter Target="CheckedContent.Stroke" Value="Cyan"></Setter>
    </VisualState.Setters>
</VisualState>


text:
Q: Implement webservice for login with social sites I am working with the webservies for ios and android app and need to develop a service for login with social media.
The app need to support login with twitter, facebook, linkedin, and google plus.
As parameters, I am accepting userid from social site and the site from which this id originated and the basic user info like firstname, lastname, and email.
Below is the structure of relevant tables for this

*

*user table
userid |  email | deviceid | firstname | lastname | password
userid being primary and email is unique

*user social media table
userid | site | token
When I get this information from the frontend, I first check if social user id is already there. If social id doesn't match then I check if email exists in db or not. If email is not in the db, then I register the new user.
Now the main issue is that the twitter sdk for android and ios does not return the email and even facebook does not return the email if the user is registered by phone, because of this I am having a problem uniquely identifying the user on my end. I have searched a lot but can't come up with any solution for this.
Please correct me if I am wrong anywhere in my approach and suggest to me how can I handle the email issue.

A: I'd have used 1 table for both types of users instead, like this:
userid | type | email | socialid | deviceid | firstname | lastname | password | token

'type' column would be an enum of possible account types: fb, twitter, google or email
'socialid' would have an id from social network (the id is included in oauth response) for users coming from those and will be null for normal users(registered via email)
'email' would include an email for normal users and be null for social users
Then it's just a matter of SELECT query to understand what type of user you're working with

A: Take a look at http://hybridauth.sourceforge.net/ and implement to suite your architecture or solution.

A: Normally the Facebook API should ship with the users ID. Twitter SDK is a bit tricky. Try to save the userers Twitter-username in your database.


text:
Q: How can I unbind C-tab from jedi:complete? With jedi-mode enabled, the C-tab is bound to jedi:complete.
How can I unbind it so that I can then bind it back to other-window?
I've tried:

*

*(global-set-key (kbd "C-`") 'jedi:complete)

*(global-set-key [C-tab] 'other-window)

*(global-unset-key (kbd "<C-tab>"))

*(defcustom jedi:key-complete (kbd "C-`")
"Keybind for command `jedi:complete'."
:group 'jedi)
None of them is getting me the desired results.

A: You can use:
(define-key jedi-mode-map (kbd "<C-tab>") nil)

None of the commands with global in them will work, since minor mode key bindings
have priority over global key bindings.


text:
Q: Where do my settings go? I am having a tough time trying to figure out where my settings are going.  I am retaining a connection string which I can not find anywhere.  So far I learned that AppName.vshost.exe.config is supposed to be the debug version and AppName.exe.config is supposed to be the release but that is not the case or if it is then they are not going to thier default folders nor the folder I chose.    I do not know if I did something wrong or this is a Microsoft "feature" but if anyone has a clue please fill me in.
I am developing on a Win 7 machine with VS 2015.  My build - Configuration is "Active (Debug)" and I have set the Output path to "C:\Bin" because I have other libraries I am building that are required by this app and its easier to just set all the output paths to the same place.
To try to find the issue I made a new setting, Test:

I also added a textbox to the form and use it like so:
 public Main()
    {
        ...
        textBox1.Text = Settings.Default.Test;
        ...
    }

private void Main_FormClosing(object sender, FormClosingEventArgs e)
    {
        ...
        Settings.Default.Test = textBox1.Text;
        ...
    }

I then compiled and copied the exe and required dlls from C:\Bin to C:\Test.  There isn't any config file in that directory.
The form comes up with a "T" in the text box.  So far so good.  I then change it to "EXE-Test":

I close it and re-open it and my change is there.  But where does it go?  There is no config file created in the folder where I run it from like I would expect.
Both the SQLgem.vshost.exe.config and SQLgem.exe.config files have the original "T" in them in my output folder (C:\Bin).

C:\Code\SQLgem\SQLgem\bin\Release has nothing in it, which is what I expected since I did not build a release.  C:\Code\SQLgem\SQLgem\bin\Debug just has shells, the new setting (actually all my settings) do not appear there.
And it gets even odder.  When I run in debug (visual studio) and change the "T" to debug it persists.  So where does this one go?

So now there are two settings that persist but I can not find anywhere.  Doing a C:> dir SQLgem.exe.config /s does not find any more than the ones I already mentioned.
Where can they be?
Somehow "Hewlett-Packard Company" became the company in the embedded information.  So when I was following the first post and checked both locations I instinctively ignored the folder that was not my company.  Upon furhter investigation I finally found them!

A: Those are user-scope settings, not application-scope, so they won't be persisted back to app.exe.config in the bin directory (which is often C:\Program Files and not writable by the user).
Somewhere under %LOCALAPPDATA% (which is user-writable) you'll find the settings stored in a file named user.config.
The directory this file is in is influenced by your assembly metadata, such as Company Name and Product Name and Version.


text:
Q: @property gets writeable when attribute is of dict type @property defined as int
The following code is taken from Python Docs:
class Parrot(object):
    def __init__(self):
        self._voltage = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

When I run:
parrot = Parrot()
print(parrot.voltage)
parrot.voltage = 100
print(parrot.voltage)

I get the following output (as expected, as no setter is defined)
{0: 100000}
Traceback (most recent call last):
   File "prop.py", line 13, in <module>
     parrot.voltage = 100
 AttributeError: can't set attribute

@property defined as dict
However, if I define self._voltage = {} the property becomes writeable:
class Parrot(object):
    def __init__(self):
        self._voltage = {}
        self._voltage[0] = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

parrot = Parrot()
print(parrot.voltage)
parrot.voltage[0] = 100
print(parrot.voltage)

The output is then:
{0: 100000}
{0: 100}

Same behavior in Python 2.7.9 and Python 3.4.3. Why is the property writeable, even if no setter is explicitly defined in the code? Here it was proposed to subclass dict to get this behavior. However, it seems that this not required.

A: You are not setting the property. You are manipulating a mutable object.
The assignment is not on the property itself, but on a subscription, the [..] part addresses a dictionary key. You could assign the property to a new name and still manipulate that dictionary:
parrot = Parrot()
parrot_voltage = parrot.voltage
parrot_voltage[0] = 100

but you cannot set the property to a new dictionary or a different type of object altogether. This applies to all mutable objects used in a property; lists, sets, instances, etc.


text:
Q: How to create a sequence of bytes() with length 1 I am writing an application in Python 3 that talks to a device over a serial port, using the pyserial module.
When writing to a device, the pyserial module expects the data to be represented as a sequence of bytes.
This works fine if I write the data all at once, but fails if I write the data byte-by-byte, with a delay after each byte. The reason I want to write byte-by-byte is when I have to deal with devices that can only process data at a low rate.
The code I am using is:
def write_timed(self, data):
    """Write data to serial port,
    taking into account inter-character delay and line-delay

    :param data (str): string to write; any escaped characters will be converted
        e.g. \n will be output as a newline (not as characters '\' and 'n')
    """
    # convert raw string to sequence of bytes
    data = bytes(data.encode('latin-1').decode("unicode_escape"), "latin-1")
    logging.info("TX:{}".format(repr(data)))
    # only write to device if we have something to write
    if data:
        if data and self.char_delay_s == 0:
            self.serial.write(data)
        else:
            for d in data:
                self.serial.write(d)
                time.sleep(self.char_delay_s)
        time.sleep(self.line_delay_s)
        # ensure all data has gone out
        self.serial.flush()

The error I get is:
  File "C:\projects\maintenance\protocoltest\protocoltest\device\device.py", line 65, in write_timed
    self.serial.write(d)
  File "C:\projects\newplatform\venv3_pyside2\lib\site-packages\serial\serialwin32.py", line 301, in write
    data = to_bytes(data)
  File "C:\projects\newplatform\venv3_pyside2\lib\site-packages\serial\serialutil.py", line 61, in to_bytes
    for item in seq:
TypeError: 'int' object is not iterable

The reason for the error is that when I execute for d in data:, variable d becomes an int instead of a sequence of bytes with length 1.
If I try to fix that using d = bytes(d) I get a string of zeros, the length of the value of d.
How can I write single bytes to pyserial?
If I set self.char_delay_s to zero, everything works fine, even strings of length 1. If I have a non-zero value, the get the error above.

A: Unfortunately, as you discovered, when you index a bytes object you get an int object. The easiest thing to do is simply cast that int back to bytes:
for d in data:
    d = bytes([d])
    # d is now a bytes object and can be used as such

Alternatively, you can use slices instead of indexing:
for i in range(len(data)):
    d = data[i : i + 1]
    # d is a bytes object because it's a slice of a bytes object


text:
Q: Can't hide actionbar menu item programatically I'm trying to hide an Actionbar menu item if a shared preference is false.
I'm getting the shared preference as I want, but the menu item wont hide.
// Inflate a menu to be displayed in the toolbar
toolbar.inflateMenu(R.menu.activity_main_actionbar);

// Enable disable set start page item
if(!sharedPref.getBoolean("enable_custom_startpage", false)) {
    toolbar.getMenu().findItem(R.id.setasstartpage).setVisible(false);
}

What am i doing wrong??

A: The right place for doing this is onPrepareOptionsMenu. From the docs,

Prepare the Screen's standard options menu to be displayed. This is
  called right before the menu is shown, every time it is shown. You can
  use this method to efficiently enable/disable items or otherwise
  dynamically modify the contents.

So, I would recommend you to override onPrepareOptionsMenu and then check for the Shared Prefs inside it and show menu accordingly. Something like,
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    // Enable disable set start page item
    if(!sharedPref.getBoolean("enable_custom_startpage", false)) {
        toolbar.getMenu().findItem(R.id.setasstartpage).setVisible(false);
    }

    return true;
}

A: try this
mToolbar.getMenu().findItem(id).setEnabled(false);

I hope it will work for you.

A: try this
invalidateOptionsMenu();

I hope it is helpful for you.

A: Get a MenuItem pointing to such item, call setVisible on it to adjust its visibility and then call invalidateOptionsMenu() on your activity so the ActionBar menu is adjusted accordingly.
Update: A MenuItem is not a regular view that's part of your layout. Its something special, completely different. Your code returns null for item and that's causing the crash. What you need instead is to do:
MenuItem item = menu.findItem(R.id.addAction);

A: *

*Start by saving the menu globally in your activity-
Menu menuu;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menuu=menu;
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

*Have different menu.xml for you . one is having noitem and other is
containing the items you want.
menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.afixi.prasenjeetpati.notification_service.MainActivity">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />
</menu>

menu_blank.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.afixi.prasenjeetpati.notification_service.MainActivity">
</menu>

*Now to remove the option menu at any time do this-
menuu.clear();
getMenuInflater().inflate(R.menu.menu_blank, menuu);

and to get back the normal menu-
menuu.clear();
getMenuInflater().inflate(R.menu.menu_main, menuu);


text:
Q: How do you programmatically find a true URL in C# instead of a forwarding link? Another way to ask this question is this: How do you programmatically expand a TinyURL link to its true location?
What I want to do is to find a way to programmatically take the link:
http://www.baidu.com/link?url=mW91GJqjJ4zBBpC8yDF8xDhiqDSn1JZjFWsHhEoSNd85PkV8Xil7qccoOX3rynaE

(the first link in a search for Jessica Alba using baidu.com) and have it return the actual link:
http://baike.baidu.com/view/270790.htm

That is just one example.  What I want to do is not specific to Jessica but for using Baidu.com as part of my group of search engines in my meta search engine project.
Maybe there is a way of using the WebBrowser class but I did not see a member that was the URL.
Maybe there is a way of using WebRequest and WebResponse.

A: Make a request to tinied URL, and parse out the HTTP response Location header.

A: Here you go, it's nice and easy!
var WReq = WebRequest.Create("http://www.baidu.com/link?url=mW91GJqjJ4zBBpC8yDF8xDhiqDSn1JZjFWsHhEoSNd85PkV8Xil7qccoOX3rynaE");
WReq.Method = "HEAD";   // Only download the headers, not the page content
var ActualURL = WReq.GetResponse().ResponseUri.ToString();
MessageBox.Show(ActualURL);

A: string url = "http://www.baidu.com/link?url=mW91GJqjJ4zBBpC8yDF8xDhiqDSn1JZjFWsHhEoSNd85PkV8Xil7qccoOX3rynaE";
var req = (HttpWebRequest)HttpWebRequest.Create(url);
req.AllowAutoRedirect = false; //<--!!!!
var resp = req.GetResponse();
var realUrl = resp.Headers["Location"]; //http://baike.baidu.com/view/270790.htm

PS: The key point here is the req.AllowAutoRedirect = false


text:
Q: Return error response if a body params is not mentionned in the validator I'm using the Laravel Validator to test my incoming request. So to be sure that the request contains an username and an email, I write something like that:
$validator = Validator::make($request->all(), [
    'username'  => 'required',
    'email'     => 'required|email'
]);

if ($validator->fails()) {
    return response()->json('error', 400);
};

But if in my request I have an additionnal params like name, the validator will not consider it as an error and will not fail.
Have you an idea how I can make my validator more strict so that the request body match exactly?

A: Technically it's not a validation fail in the Validator. But you could check if there are extra (unexpected) fields and send a JSON response based on that if you wanted.
Something like this maybe?
$validationRules = [
    'username'  => 'required',
    'email'     => 'required|email'
];

$validator = Validator::make($request->all(), $validationRules);

// Check if there are extra (unexpected) fields and fail in that case
$extraFields = $request->except(array_keys($validationRules));
if (count($extraFields) > 0) {
    return response()->json('error because there are extra fields', 400);
}

if ($validator->fails()) {
    return response()->json('error', 400);
}

return response()->json('ok', 200);

I hope it can help you.

A: Validation rules can be attached only to properties, so I don't think Laravel's Validator is able to do that. But you still can explicitly forbid certain fields by providing a custom closure rule to them, like this:
$denied = function($attr, $value, $fail) {
    $fail("{$attr} is denied.");
};

$validator = Validator::make($request->all(), [
    'username'  => 'required',
    'email'     => 'required|email',
    'name'      => $denied,
    'password'  => $denied
]);

Otherwise you need to implement custom validation logic, probably utilizing the rule array from your validator as a white list.


text:
Q: Reference request for tensor analysis I took a look at other similar questions, such as Tensor Book Recommendation Request but did not get what I am looking for.
What I have:

*

*first course in linear algebra, tensor calculus

*background in engineering sciences

What I am looking for:

*

*Tensor analysis introductory book (Not completely math oriented. It should be readable for someone non-math major.)

*I know basics and properties of tensor. I understand $v'_i=Q_{ji}v_i$ that tensor $Q$ transforms vector $v$ to get $v'$ but I do not understand tensor as linear mapping.

*Trying to understand dual space (dual vector space). I checked few linear algebra books, such as Shilov G. E., but didn't get what I was looking for. (as per question Where to start learning Linear Algebra?). Unfortunately, my linear algebra course did not discuss dual vector spaces.

P.S. I saw questions asking book recommendation getting closed. But 'book recommendation' and 'reference request' are active tags in SE Mathematics, so I don't see any reason why. Secondly, there are already several questions out there on the website.


text:
Q: How are __repr__ and __str__ implemented in print function The way that I understand about __str__ and __repr__ through googling is that __str__is called when printor __str__() function is used and the output is always string. __repr__ is called when repr() or __repr__() function is used and while repr() can only output string, __repr__() could be any valid python expression such as tuple, dictionary, string etc.
So I was creating a two class Person and CircularQueue. In person class, it contains variable name, age and I defined __str__ and __repr__. For CircularQueue class, it is ordinal CQ except it only accepts Person class.
For print(cg.dequeue()) it prints only the name as I expected with __str__. However, when I run print(cg.multi_dequeue(3)), it gives the output of __repr__ and not __str__. I thought that since I used print it would use __str__.

*

*Why print(cg.dequeue()) output using __str__ while print(cg.multi_dequeue(3)) output using __repr__?

*This question is not really connected to the topic but why can't I use return self in __repr__ even if I use cg.multi_dequeue(3).__repr__()? It gives TypeError: __repr__ returned non-string (type Person) error.
class Person:
        name = ""
        age = 0

        def __init__(self, name, age):
            self.name = name
            self.age = age
        def __repr__(self):
            return ("[Person(name: " + self.name + ", age: " + str(self.age) + ")")
            #return self
        def __str__(self):
            return self.name

class CircularQueue:
...
    def enqueue(self, element):
        check = isinstance(element,Person)
        #check if CQ is full
        if self.is_full():
            print("Queue is full!")
            return 0
        #check if input is Person class
        elif check != True:
            print("Element is not a Person class element")
            return 0
        #add element to CQ
        else:
            self.queue[self.rear] = element
            self.rear = (self.rear + 1) % self.M
    def dequeue(self):
        #check if CQ is empty
        if self.is_empty():
            print("Queue is empty")
            return 0
        #return element
        else:
            temp = self.queue[self.front]
            self.queue[self.front] = None
            self.front = (self.front +1) % self.M
            return temp
    def multi_dequeue(self, count):
        temp = []
        for i in  range(count):
            temp.append(self.dequeue())
        return temp

def main():
    cg = CircularQueue(10)
    cg.enqueue(Person("hi",1))
    cg.enqueue(Person("bye",1))
    cg.enqueue(Person("dd",3))
    cg.enqueue(Person("ss",3))
    cg.enqueue(Person("aa",3))
    print(cg.dequeue())
    print(cg.multi_dequeue(3))

main()

output
hi
[[Person(name: bye, age: 1), [Person(name: dd, age: 3), [Person(name: ss, age: 3)]

A: The explanation is not very good. I will try another one.
The difference between __repr__ and __str__ lies in the information value. The standard implementation is __repr__ and returns the class and the hash of the instance, which represents the memory address, as this is used by the interpreter for unique identification. It is the unique representation of an object's instance. However, this is not always helpful for the user. This is where __str__ comes into play.
Inheritance is an illustration of a tree structure. Every time you inherit from a class or type, you add another child node to the tree. The deeper you are in the tree, the more information may be available about the individual nodes.
Within my implementation of a tree you can see that the unique identification is given by the class, the module path and the content. However, the actual content of the node is more interesting for the user. However, this can vary depending on the use or depth within the tree.
Due to the amount of data that is collected in a sequence / iterable, it makes more sense to continuously output the __repr__ variant. In my implementation the __str__ output would make no sense, would change constantly and go beyond the scope if I wanted to output the entire tree. So with __str__ I only return the string of the real data. Remember, there may be a node that appears at a different location in the tree but contains the same content. These appear the same but are different.
Unfortunately I can't give you a better explanation. I hope it's not too weird and complicated.
Think about it.
I believe in you!
from abc import ABC
from typing import List

class BaseNode(ABC):

    def __init__(self) -> None:
        self._children = []
        self._parent = None

    def __len__(self) -> int:
        return len(self._children)

    def __repr__(self):
        # python default implementation of __repr__
        return f'<{self.__class__.__module__}.{self.__class__.__name__}' \
            f' object at {self.__hash__()}>'

    # python default implementation of __str__
    __str__ = __repr__

    def has_children(self) -> bool:
        return len(self) > 0

    def is_leaf(self) -> bool:
        return not self.has_children()

    def is_root(self) -> bool:
        return self._parent is None

    def add(self, child: 'BaseNode') -> 'BaseNode':
        self._children.append(child)
        child._parent = self
        return self

    def depth(self) -> int:
        d,n = 0,self
        while not n.is_root():
            d,n = d+1,n._parent
        return d

    def descendants(self) -> List['Node']:
        arr = []
        if self.is_leaf(): return arr
        else:
            arr.extend(self._children)
            for child in self._children:
                arr.extend(child.descendants())
        return arr

    # abstract
    def remove(self, child: 'BaseNode') -> 'BaseNode':
        self._children.remove(child)
        child._parent = None
        return self

class RootNode(BaseNode):
    pass

class Node(BaseNode):
    def __init__(self, content):
        super().__init__()
        self._content = content

    def __str__(self):
        return self.content

    @property
    def content(self):
        return self._content

def main():
    node = RootNode()
    node_a   = Node('Node 1')
    node_aa  = Node('Node 1.1')
    node_ab  = Node('Node 1.2')
    node_aba = Node('Node 1.2.1')
    node_b   = Node('Node 2')
    node_ba  = Node('Node 2.1')

    node_ab.add(node_aba)
    node_a.add(node_aa)
    node_a.add(node_ab)
    node.add(node_a)
    node_b.add(node_ba)
    node.add(node_b)

    print(node)
    print(str(node))
    print(repr(node))
    print(node.depth())
    print(node.descendants())

    print(node_aba)
    print(str(node_aba))
    print(repr(node_aba))
    print(node_aba.depth())
    print(node_aba.descendants())

if __name__ == '__main__':
    main()
``


text:
Q: Azure Function Can't bind parameter 'messageReceiver' to type 'Microsoft.Azure.ServiceBus.Core.MessageReceiver' Having upgraded to Microsoft.Azure.ServiceBus v5.2.0 MessageReceiver no longer works.
MessageReceiver messageReceiver

Microsoft.Azure.WebJobs.Host: Error indexing method
'BrunelWMSServiceBus'. Microsoft.Azure.WebJobs.Host: Can't bind
parameter 'messageReceiver' to type
'Microsoft.Azure.ServiceBus.Core.MessageReceiver'.

MessageReceiver is still supported according to the doc but it no longer works in the run-time. I've seen references to parameter naming but messageReceiver is apparently ok.
ServiceBusMessageActions messageActions

works but MUST be called messageActions or it will fail to bind too. Just wondering whether to stop using MessageReceiver and use ServiceBusMessageActions instead.

A: It's not added to the specs yet, but obviously IMessageReceiver shouldn't be used any longer as it belongs to Microsoft.Azure.ServiceBus library which is deprecated and not referenced by Microsoft.Azure.WebJobs.Extensions.ServiceBus SDK anymore. So ServiceBusMessageActions messageActions parameter is definitely the way to go now.
https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/servicebus/Microsoft.Azure.WebJobs.Extensions.ServiceBus#message-settlement


text:
Q: SOAPUI - Parse different JSON Response objects to fetch the same child node values using Groovy Scripting I'm automating REST API's using SOAPUI. I've 2 different resources and below are the Response JSON formats.
The root element varies but the status block remains same for both the response jsons. After the Rest API POST call, I've a Groovy script in place to validate the response (if "code" == "00")
Goal: Using Groovy Script, I've to Parse through the JSON and retreive the "code" node value irrespective of the root element.
Response(JSON) Formats:
{
    "resouurce_1_response":
    {
        "status":
        {
            "code": "00"
        }
    }
}

{
    "resource_2_response":
    {
        "status":
        {
            "code": "00"
        }
    }
}

A: One quick way of doing it would be:
def json1 = '{ "resouurce_1_response": { "status": { "code": "00" } } }'
def json2 = '{ "resource_2_response": { "status": { "code": "00" } } }'

import groovy.json.*

def slurper = new JsonSlurper()

assert slurper.parseText(json1).find().value.status.code == '00'
assert slurper.parseText(json2).find().value.status.code == '00'

Of course, if your actual Json is more complex than you show, you might need to do something different (recursively walk the map?)


text:
Q: How can I programmatically insert RTF text into a PowerPoint text frame using C#? Is there any way to programmatically insert RTF-formatted text into a PowerPoint TextFrame?
string myString = <some RTF formatted text>;

MyPlaceholder.TextFrame.TextRange.Text = myString;

This answer gets me close: Is it possible to insert pieces of RTF text into a Word document (.docx) using OpenXml?
But I am having trouble figuring out how to do this in PowerPoint rather than Word.
What I am trying to do is copy text from a RichEditBox in my application onto a PowerPoint slide and maintain font-color, format, etc. I am able to successfully bring the text into PowerPoint. I just can't bring in the formatting (such as font-color) with it.
Thanks.

A: I was finally able to accomplish this by saving from the RichEditBox to a stream using the following line of code and then writing to a file:
tempRichEditBox.Document.SaveToStream(Windows.UI.Text.TextGetOptions.FormatRtf, randAccStream);

I then used this line to import the file into PowerPoint. The font color and formatting are maintained.
var rtfShape = PptSlide.Shapes.AddOLEObject(FileName: rtfFileName);


text:
Q: Automatic Rows & Columns with CSS I have ~170 small, square elements in a div, I'd like them to arrange themselves into however many rows they need to for the width of the div (which will change with the width of the browser).

I know I could do:
#container .sq { float:right; }

with some padding to make them collect on the right and slowly overflow downwards - something like this:
. . . . . . .
. . . . . . .
. . . . . . .
      . . . .

where each dot is an sq element, but I really want something that overflows upwards, so they'd look like this:
      . . . .
. . . . . . .
. . . . . . .
. . . . . . .

or like this if the browser was resized:
    . . . . . . .
. . . . . . . . .
. . . . . . . . .

Does anyone have any idea if this is possible in CSS?

A: The difficulty in implementing that probably vastly outweighs the desire for the result. You may be able to achieve it using JavaScript/jQuery but I'm not sure if it's worth the effort?

A: Is this is what you need?
http://www.sohtanaka.com/web-design/smart-columns-w-css-jquery/

A: In IE8, you can say -ms-writing-mode: rl-bt. Although writing-mode is part of the CSS3 Text Layout work, this value is not included in the draft spec at this time.
On all other browsers you would need some script. For example if each .sq had float: right;, you could add clear: right to every nth element starting from the end of the list. (Where n is the number of squares that you calculate will fit the width.) Or simply float: left; and add a margin-left to the first sq to push it however far to the right it needs to be.


text:
Q: Conditional Format Formula I think I developed a brain lock. I have a conditional format formula comparing 2 cells. I need it to color red if the difference is >3¢ or < -3¢.
Here is what I have tried and so far these do not work:

*

*=(D19-F19)<>3

*=OR(D19-F19<-3,D19-F19>3)

*=abs(D19-F19)<>3
Can someone please tell me what I am doing wrong.

A: The following will evaluate as True if the difference is greater than 3:
=ABS(E17-F17)>3

Example:
Num 1   Num 2   Test
     3      -4  TRUE
     3      -3  TRUE
     3      -2  TRUE
     3      -1  TRUE
     3       0  FALSE
     3       1  FALSE
     3       2  FALSE
     3       3  FALSE
     3       4  FALSE
     3       5  FALSE
     3       6  FALSE
     3       7  TRUE
     3       8  TRUE
     3       9  TRUE

Your first example ( =(D19-F19)<>3 ) only evaluates as False for a difference of exactly 3.
Your second example ( =OR(D19-F19<-3,D19-F19>3) ) should have worked. Maybe you entered your data with the ¢ symbol in the cell? In this case, because the cells contain both numbers and text, you can't use them in formulas. Take out the "¢" so you only have numbers in the cells. Write in a heading above the numbers what the data units are. EG:
Cost_1   Cost_2   Difference
(¢)       (¢)      (¢)
 3         15       12
 0          2        2

Your third example ( =abs(D19-F19)<>3 ) only evaluates as False when the difference is exactly 3 or -3