text:
Q: How to use Reflection in order to avoid value boxing? I am exploring Blazor's QuickGrid source code and found one interesting spot here.
On the 45th line Steve Sanderson left a TODO with a potentially better alternative solution.
I could not resist my curiosity and decided to give it a try and benchmark the solution afterwards. But, unfortunately, my knowledge in Reflection is really poor.
Could anybody help me to understand how the ideas described in the Steve's comment could be achieved?
Thanks
UPD-1: Code snippet of what I have atm
    if( typeof(TProp).GetInterface(nameof(IFormattable)) != null ) {

    Type result = typeof(Func<,>).MakeGenericType(typeof(TGridItem), typeof(TProp));

    _cellTextFunc = item => FormatValue(compiledPropertyExpression);
}

    // TODO: Consider using reflection to avoid having to box every value just to call IFormattable.ToString
    // For example, define a method "string Format<U>(Func<TGridItem, U> property) where U: IFormattable", and
    // then construct the closed type here with U=TProp when we know TProp implements IFormattable

    private string FormatValue<U>( Func<TGridItem, U> property ) where U : IFormattable
    {
        return null;
    }

A: I suspect what Steve meant was to define a method such as:
private string? FormatItem<U>(TGridItem item, Func<TGridItem, U> property) where U: IFormattable
{
    return property(item)?.ToString(Format, null);
}

(I had to add item to make it make sense: perhaps I'm missing something).
We also need to define a spearate version for nullables, since Nullable<T> can't satisfy the constraint IFormattable<T>, even if T does implement IFormattable<T>.
private string? FormatItemNullable<U>(TGridItem item, Func<TGridItem, U?> property) where U : struct, IFormattable
{
    return property(item)?.ToString(Format, null);
}

Then once you know U, you can create a delegate which invokes this method:
var formatItemMethodInfo = typeof(C<TGridItem, TProp>).GetMethod("FormatItem", BindingFlags.NonPublic | BindingFlags.Instance)!;
var formatItemNullableMethodInfo = typeof(C<TGridItem, TProp>).GetMethod("FormatItemNullable", BindingFlags.NonPublic | BindingFlags.Instance)!;

var formatter = (Func<TGridItem, Func<TGridItem, TProp>, string>)Delegate.CreateDelegate(
    typeof(Func<TGridItem, Func<TGridItem, TProp>, string>),
    this,
    nullableUnderlyingTypeOrNull == null
        ? formatItemMethodInfo.MakeGenericMethod(typeof(TProp))
        : formatItemNullableMethodInfo.MakeGenericMethod(nullableUnderlyingTypeOrNull));

And finally use this when constructing _cellTextFunc:
_cellTextFunc = item => formatter(item, compiledPropertyExpression);

This has a little bit of upfront cost (creating the delegate), but invoking it is cheap, and means that you don't have to box item to IFormattable if it's a value type.
See on SharpLab.

If I were to suggest a better solution, since we're already using compiled expressions with Property, I'd extend that and compile the ToString call into the expression. Something like:
var toStringMethod = typeof(IFormattable).GetMethod("ToString")!;

var propVar = Expression.Variable(typeof(TProp), "prop");

// What to call String(...) on. We need to call prop.GetValueOrDefault().ToString(...)
// if prop is a nullable value type
Expression toStringCallTarget = nullableUnderlyingTypeOrNull == null
    ? propVar
    : Expression.Call(
        propVar,
        typeof(TProp).GetMethod("GetValueOrDefault", Type.EmptyTypes)!);

// The ToString(...) call itself
var toStringCall = Expression.Call(
    toStringCallTarget,
    toStringMethod,
    Expression.Property(Expression.Constant(this), "Format"),
    Expression.Constant(null, typeof(IFormatProvider)));

// If prop is nullable (class or nullable struct), then we need to do
// prop == null ? null : prop[.GetValueOrDefault()].ToString(...),
// otherwise just call prop.ToString(...)
Expression conditionalCall = default(TProp) == null
    ? Expression.Condition(
        Expression.Equal(propVar, Expression.Constant(null, typeof(TProp))),
        Expression.Constant(null, typeof(string)),
        toStringCall)
    : toStringCall;

var block = Expression.Block(new[] { propVar },
    Expression.Assign(propVar, Property.Body),
    conditionalCall);

_cellTextFunc = Expression.Lambda<Func<TGridItem, string?>>(block, Property.Parameters[0]).Compile();

See it on SharpLab.

Just for fun, I put together a benchmark of the original approaches, Steve's proposed approach, and mine and MarcGravell's proposed solutions:
namespace MyBenchmarks
{
    [MemoryDiagnoser]
    public class Benchmark
    {
        private readonly GridItem gridItem = new();

        private readonly Func<GridItem, string?> originalClass = new Original<GridItem, FormattableClass>() { Property = x => x.Class, Format = "X" }.Test();
        private readonly Func<GridItem, string?> originalNonNullable = new Original<GridItem, FormattableStruct>() { Property = x => x.NonNullable, Format = "X" }.Test();
        private readonly Func<GridItem, string?> originalNullable = new Original<GridItem, FormattableStruct?>() { Property = x => x.Nullable, Format = "X" }.Test();

        private readonly Func<GridItem, string?> reflectionClass = new ReflectionTest<GridItem, FormattableClass>() { Property = x => x.Class, Format = "X" }.Test();
        private readonly Func<GridItem, string?> reflectionNonNullable = new ReflectionTest<GridItem, FormattableStruct>() { Property = x => x.NonNullable, Format = "X" }.Test();
        private readonly Func<GridItem, string?> reflectionNullable = new ReflectionTest<GridItem, FormattableStruct?>() { Property = x => x.Nullable, Format = "X" }.Test();

        private readonly Func<GridItem, string?> formatterClass = new FormatterTest<GridItem, FormattableClass>() { Property = x => x.Class, Format = "X" }.Test();
        private readonly Func<GridItem, string?> formatterNonNullable = new FormatterTest<GridItem, FormattableStruct>() { Property = x => x.NonNullable, Format = "X" }.Test();
        private readonly Func<GridItem, string?> formatterNullable = new FormatterTest<GridItem, FormattableStruct?>() { Property = x => x.Nullable, Format = "X" }.Test();

        private readonly Func<GridItem, string?> compiledExpressionClass = new CompiledExpressionTest<GridItem, FormattableClass>() { Property = x => x.Class, Format = "X" }.Test();
        private readonly Func<GridItem, string?> compiledExpressionNonNullable = new CompiledExpressionTest<GridItem, FormattableStruct>() { Property = x => x.NonNullable, Format = "X" }.Test();
        private readonly Func<GridItem, string?> compiledExpressionNullable = new CompiledExpressionTest<GridItem, FormattableStruct?>() { Property = x => x.Nullable, Format = "X" }.Test();

        [Benchmark]
        public void OriginalClass() => originalClass(gridItem);

        [Benchmark]
        public void OriginalNonNullable() => originalNonNullable(gridItem);

        [Benchmark]
        public void OriginalNullable() => originalNullable(gridItem);

        [Benchmark]
        public void ReflectionClass() => reflectionClass(gridItem);

        [Benchmark]
        public void ReflectionNonNullable() => reflectionNonNullable(gridItem);

        [Benchmark]
        public void ReflectionNullable() => reflectionNullable(gridItem);

        [Benchmark]
        public void FormatterClass() => formatterClass(gridItem);

        [Benchmark]
        public void FormatterNonNullable() => formatterNonNullable(gridItem);

        [Benchmark]
        public void FormatterNullable() => formatterNullable(gridItem);

        [Benchmark]
        public void CompiledExpressionClass() => compiledExpressionClass(gridItem);

        [Benchmark]
        public void CompiledExpressionNonNullable() => compiledExpressionNonNullable(gridItem);

        [Benchmark]
        public void CompiledExpressionNullable() => compiledExpressionNullable(gridItem);
    }

    class Original<TGridItem, TProp>
    {
        public Expression<Func<TGridItem, TProp>> Property { get; set; } = default!;
        public string? Format { get; set; }

        public Func<TGridItem, string?> Test()
        {
            Func<TGridItem, string?> cellTextFunc;

            var compiledPropertyExpression = Property.Compile();
            if (!string.IsNullOrEmpty(Format))
            {
                // TODO: Consider using reflection to avoid having to box every value just to call IFormattable.ToString
                // For example, define a method "string Format<U>(Func<TGridItem, U> property) where U: IFormattable", and
                // then construct the closed type here with U=TProp when we know TProp implements IFormattable

                // If the type is nullable, we're interested in formatting the underlying type
                var nullableUnderlyingTypeOrNull = Nullable.GetUnderlyingType(typeof(TProp));

                if (!typeof(IFormattable).IsAssignableFrom(nullableUnderlyingTypeOrNull ?? typeof(TProp)))
                {
                    throw new InvalidOperationException($"A '{nameof(Format)}' parameter was supplied, but the type '{typeof(TProp)}' does not implement '{typeof(IFormattable)}'.");
                }

                cellTextFunc = item => ((IFormattable?)compiledPropertyExpression!(item))?.ToString(Format, null);
            }
            else
            {
                cellTextFunc = item => compiledPropertyExpression!(item)?.ToString();
            }

            return cellTextFunc;
        }

        private string? FormatItem<U>(TGridItem item, Func<TGridItem, U> property) where U : IFormattable
        {
            return property(item)?.ToString(Format, null);
        }
    }

    class ReflectionTest<TGridItem, TProp>
    {
        private static readonly MethodInfo formatItemMethodInfo = typeof(ReflectionTest<TGridItem, TProp>).GetMethod("FormatItem", BindingFlags.NonPublic | BindingFlags.Instance)!;
        private static readonly MethodInfo formatItemNullableMethodInfo = typeof(ReflectionTest<TGridItem, TProp>).GetMethod("FormatItemNullable", BindingFlags.NonPublic | BindingFlags.Instance)!;
        public Expression<Func<TGridItem, TProp>> Property { get; set; } = default!;
        public string? Format { get; set; }

        public Func<TGridItem, string?> Test()
        {
            Func<TGridItem, string?> cellTextFunc;

            var compiledPropertyExpression = Property.Compile();
            if (!string.IsNullOrEmpty(Format))
            {
                // If the type is nullable, we're interested in formatting the underlying type
                var nullableUnderlyingTypeOrNull = Nullable.GetUnderlyingType(typeof(TProp));

                if (!typeof(IFormattable).IsAssignableFrom(nullableUnderlyingTypeOrNull ?? typeof(TProp)))
                {
                    throw new InvalidOperationException($"A '{nameof(Format)}' parameter was supplied, but the type '{typeof(TProp)}' does not implement '{typeof(IFormattable)}'.");
                }

                var formatter = (Func<TGridItem, Func<TGridItem, TProp>, string>)Delegate.CreateDelegate(
                    typeof(Func<TGridItem, Func<TGridItem, TProp>, string>),
                    this,
                    nullableUnderlyingTypeOrNull == null
                        ? formatItemMethodInfo.MakeGenericMethod(typeof(TProp))
                        : formatItemNullableMethodInfo.MakeGenericMethod(nullableUnderlyingTypeOrNull));
                cellTextFunc = item => formatter(item, compiledPropertyExpression);
            }
            else
            {
                cellTextFunc = item => compiledPropertyExpression!(item)?.ToString();
            }

            return cellTextFunc;
        }

        private string? FormatItem<U>(TGridItem item, Func<TGridItem, U> property) where U : IFormattable
        {
            return property(item)?.ToString(Format, null);
        }

        private string? FormatItemNullable<U>(TGridItem item, Func<TGridItem, U?> property) where U : struct, IFormattable
        {
            return property(item)?.ToString(Format, null);
        }
    }

    public interface IFormatter<T>
    {
        string Format(T value, string? format, IFormatProvider? formatProvider = null);
    }

    public static class Formatter<T>
    {
        public static IFormatter<T>? Instance { get; }

        static Formatter()
        {
            object? instance = null;
            var underlying = Nullable.GetUnderlyingType(typeof(T));
            if (typeof(IFormattable).IsAssignableFrom(underlying ?? typeof(T)))
            {
                if (typeof(T).IsValueType)
                {
                    if (underlying is null)
                    {
                        instance = Activator.CreateInstance(typeof(SupportedValueTypeFormatter<>).MakeGenericType(typeof(T)));
                    }
                    else
                    {
                        instance = Activator.CreateInstance(typeof(SupportedNullableFormatter<>).MakeGenericType(underlying));
                    }
                }
                else
                {
                    instance = Activator.CreateInstance(typeof(SupportedRefTypeFormatter<>).MakeGenericType(typeof(T)));
                }
            }
            Instance = (IFormatter<T>?)instance;
        }
    }

    internal sealed class SupportedNullableFormatter<T> : IFormatter<T?>
        where T : struct, IFormattable
    {
        public string Format(T? value, string? format, IFormatProvider? formatProvider)
            => value is null ? "" : value.GetValueOrDefault().ToString(format, formatProvider);
    }

    internal sealed class SupportedValueTypeFormatter<T> : IFormatter<T>
        where T : struct, IFormattable
    {
        public string Format(T value, string? format, IFormatProvider? formatProvider)
            => value.ToString(format, formatProvider);
    }
    internal sealed class SupportedRefTypeFormatter<T> : IFormatter<T>
        where T : class, IFormattable
    {
        public string Format(T value, string? format, IFormatProvider? formatProvider)
            => value is null ? "" : value.ToString(format, formatProvider);
    }

    class FormatterTest<TGridItem, TProp>
    {
        public Expression<Func<TGridItem, TProp>> Property { get; set; } = default!;
        public string? Format { get; set; }

        public Func<TGridItem, string?> Test()
        {
            Func<TGridItem, string?> cellTextFunc;

            var compiledPropertyExpression = Property.Compile();
            if (!string.IsNullOrEmpty(Format))
            {
                // If the type is nullable, we're interested in formatting the underlying type
                var nullableUnderlyingTypeOrNull = Nullable.GetUnderlyingType(typeof(TProp));

                if (!typeof(IFormattable).IsAssignableFrom(nullableUnderlyingTypeOrNull ?? typeof(TProp)))
                {
                    throw new InvalidOperationException($"A '{nameof(Format)}' parameter was supplied, but the type '{typeof(TProp)}' does not implement '{typeof(IFormattable)}'.");
                }

                cellTextFunc = item => Formatter<TProp>.Instance!.Format(compiledPropertyExpression!(item), Format, null);
            }
            else
            {
                cellTextFunc = item => compiledPropertyExpression!(item)?.ToString();
            }

            return cellTextFunc;
        }
    }

    class CompiledExpressionTest<TGridItem, TProp>
    {
        private static readonly MethodInfo toStringMethod = typeof(IFormattable).GetMethod("ToString")!;
        public Expression<Func<TGridItem, TProp>> Property { get; set; } = default!;
        public string? Format { get; set; }

        public Func<TGridItem, string?> Test()
        {
            Func<TGridItem, string?> cellTextFunc;

            if (!string.IsNullOrEmpty(Format))
            {
                // If the type is nullable, we're interested in formatting the underlying type
                var nullableUnderlyingTypeOrNull = Nullable.GetUnderlyingType(typeof(TProp));

                if (!typeof(IFormattable).IsAssignableFrom(nullableUnderlyingTypeOrNull ?? typeof(TProp)))
                {
                    throw new InvalidOperationException($"A '{nameof(Format)}' parameter was supplied, but the type '{typeof(TProp)}' does not implement '{typeof(IFormattable)}'.");
                }

                var propVar = Expression.Variable(typeof(TProp), "prop");

                Expression toStringCallTarget = nullableUnderlyingTypeOrNull == null
                    ? propVar
                    : Expression.Call(
                        propVar,
                        typeof(TProp).GetMethod("GetValueOrDefault", Type.EmptyTypes)!);

                var toStringCall = Expression.Call(
                    toStringCallTarget,
                    toStringMethod,
                    Expression.Property(Expression.Constant(this), "Format"),
                    Expression.Constant(null, typeof(IFormatProvider)));

                Expression conditionalCall = default(TProp) == null
                    ? Expression.Condition(
                        Expression.Equal(propVar, Expression.Constant(null, typeof(TProp))),
                        Expression.Constant(null, typeof(string)),
                        toStringCall)
                    : toStringCall;

                var block = Expression.Block(new[] { propVar },
                    Expression.Assign(propVar, Property.Body),
                    conditionalCall);

                cellTextFunc = Expression.Lambda<Func<TGridItem, string?>>(block, Property.Parameters[0]).Compile();
            }
            else
            {
                cellTextFunc = item => Property.Compile()!(item)?.ToString();
            }

            return cellTextFunc;
        }
    }

    public class GridItem
    {
        public FormattableClass Class { get; } = new FormattableClass();
        public FormattableStruct NonNullable => new FormattableStruct();
        public FormattableStruct? Nullable => new FormattableStruct();
    }

    public class FormattableClass : IFormattable
    {
        public string ToString(string? format, IFormatProvider? formatProvider) => "";
    }

    public struct FormattableStruct : IFormattable
    {
        public string ToString(string? format, IFormatProvider? formatProvider) => "";
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            BenchmarkRunner.Run<Benchmark>();
        }
    }
}

With the results:

Method
Mean
Error
StdDev
Gen0
Allocated

OriginalClass
6.111 ns
0.1206 ns
0.1128 ns
-
-

OriginalNonNullable
7.568 ns
0.1793 ns
0.1677 ns
0.0038
24 B

OriginalNullable
54.260 ns
1.0880 ns
1.4893 ns
0.0038
24 B

ReflectionClass
6.750 ns
0.0630 ns
0.0590 ns
-

ReflectionNonNullable
4.710 ns
0.0514 ns
0.0456 ns
-

ReflectionNullable
7.374 ns
0.0819 ns
0.0726 ns
-

FormatterClass
14.054 ns
0.2079 ns
0.1843 ns
-
-

FormatterNonNullable
3.521 ns
0.0907 ns
0.0849 ns
-
-

FormatterNullable
7.156 ns
0.0889 ns
0.0832 ns
-
-

CompiledExpressionClass
2.919 ns
0.0864 ns
0.0888 ns
-
-

CompiledExpressionNonNullable
1.815 ns
0.0405 ns
0.0379 ns
-
-

CompiledExpressionNullable
1.799 ns
0.0577 ns
0.0686 ns
-
-

As you can see, the only solution which boxes is the original code. The reflection-based approach is faster than Marc's solution for classes, and about the same for structs. However, the expression-based approach is significantly faster than anything.
I've no idea where that extra cost in FormatterClass is coming from, but it's repeatable.
I'm deliberately ignoring the cost of constructing the Func<TGridItem, string> in this benchmark: the original code is obviously optimised for the case where Property rarely changes, and the cost of compiling Property is going to dominate anything else most likely.

A: I would go with a generic interface such as IFormatter<T> without a generic constraint, and a few private implementations with the necessary complaint, and use reflection internally to decide which private implementation to use - a simple version for everything except Nullable<T>, and a special-case for that; this is the same approach used by EqualityComparer<T>.Default.
Full example is below, noting that Formatter<T>.Instance will be null if the T doesn't support IFormattable (to allow testing, although this could also be handled separately).
The use of generics in the private implementation means we're using "constrained call", so: no boxing there. The special-casing of Nullable<T> means we can handle that too, with an additional indirection.
The important thing is that we only do the thinking once per type - testing whether the type is nullable, whether it implements IFormattable, etc - and this is then cached via a strategy instance. If we do the thinking every time: boxing would probably be cheaper!
Relevant usage for the sample provided (note you could probably simply with a non-generic static class with generic method so you can just do Formatter.Format(value, format, provider) and use generic inference from value for the rest):
// L50
if (Formatter<TProp>.Instance is null)
{
    throw new InvalidOperationException($"A '{nameof(Format)}' parameter was supplied, but the type '{typeof(TProp)}' does not implement '{typeof(IFormattable)}'.");
}
_cellTextFunc = item => Formatter<TProp>.Instance.Format(compiledPropertyExpression!(item), Format, null);

Console.WriteLine(Formatter<int>.Instance!.Format(123, "G"));
Console.WriteLine(Formatter<int?>.Instance!.Format(123, "G"));
Console.WriteLine(Formatter<int?>.Instance!.Format(null, "G"));
Console.WriteLine(Formatter<NotFormattable?>.Instance is null);

struct NotFormattable { }

public interface IFormatter<T>
{
    string Format(T value, string? format, IFormatProvider? formatProvider = null);
}

public static class Formatter<T>
{
    public static IFormatter<T>? Instance { get; }

    static Formatter()
    {
        object? instance = null;
        var underlying = Nullable.GetUnderlyingType(typeof(T));
        if (typeof(IFormattable).IsAssignableFrom(underlying ?? typeof(T)))
        {
            if (typeof(T).IsValueType)
            {
                if (underlying is null)
                {
                    instance = Activator.CreateInstance(typeof(SupportedValueTypeFormatter<>).MakeGenericType(typeof(T)));
                }
                else
                {
                    instance = Activator.CreateInstance(typeof(SupportedNullableFormatter<>).MakeGenericType(underlying));
                }
            }
            else
            {
                instance = Activator.CreateInstance(typeof(SupportedRefTypeFormatter<>).MakeGenericType(typeof(T)));
            }
        }
        Instance = (IFormatter<T>?)instance;

    }
}
internal sealed class SupportedNullableFormatter<T> : IFormatter<T?>
    where T : struct, IFormattable
{
    public string Format(T? value, string? format, IFormatProvider? formatProvider)
        => value is null ? "" : value.GetValueOrDefault().ToString(format, formatProvider);
}

internal sealed class SupportedValueTypeFormatter<T> : IFormatter<T>
    where T : struct, IFormattable
{
    public string Format(T value, string? format, IFormatProvider? formatProvider)
        => value.ToString(format, formatProvider);
}
internal sealed class SupportedRefTypeFormatter<T> : IFormatter<T>
    where T : class, IFormattable
{
    public string Format(T value, string? format, IFormatProvider? formatProvider)
        => value is null ? "" : value.ToString(format, formatProvider);
}


text:
Q: Order by on EF not working as I had hoped How do I get this to work properly? I want order by duedate desc, type
I currently have:
billSummaryRepository.GetBillSummaries(logIn.CustomerNumber)
    .OrderByDescending(o => o.DueDate)
    .OrderBy(o => o.Type)

This works:
BillSummaries = billSummaryRepository.GetBillSummaries(logIn.CustomerNumber)
    .OrderBy(o => o.Type)
    .OrderByDescending(o => o.DueDate)

but how dangerous is that? Will it work?

A: BillSummaries = billSummaryRepository
    .GetBillSummaries(logIn.CustomerNumber)
    .OrderByDescending(o => o.DueDate)
    .ThenBy(o => o.Type);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get a full stacktrace with ControllerAdvice in Spring Boot? I use a @ControllerAdvice for my REST service. However I can not get a full stacktrace and define where an exception occured.
My ControllerAdvice:
@ControllerAdvice
public class RestResponseEntityExceptionHandler
        extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = {Exception.class})
    protected ResponseEntity<Object> handleException(
            Exception ex, WebRequest request) {
        String bodyOfResponse = "Internal error";

        System.out.println(ex.toString());

        return handleExceptionInternal(ex, bodyOfResponse,
                new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);

    }
}

If an Exception occurs I receive only:

WARN 72490 --- [nio-5054-exec-2]
  .m.m.a.ExceptionHandlerExceptionResolver : Resolved
  [java.lang.NullPointerException]

How I can get a full stacktrace?

A: You can replace System.out.println(ex.toString()); with ex.printStackTrace(); to get where the exception occured and cause of it.
If you are using log, then use log.info("{}", ex)


text:
Q: Angular ng-model can't get value can you help to get the ng-model data
<input type="text" class="form-control" ng-model = "DateSchedule" required>
<button type="submit" ng-click="saveReservation()" class="btn btn-primary pull-right"><i class="glyphicon glyphicon-plus"></i> Schedule</button>

in the script i already place the controller and app
alert($scope.DateSchedule);

it return me undefined
thanks


text:
Q: Сортировка. Нарушается порядок Есть массив из пар элементов (Priority:Sec)

Я сортирую его, используя quicksort, по приоритетам:

Далее я прогоняю полученный сортированный массив снова в quicksort, но уже по SEC, планируя получить
(10:10)(100:10)(250:10)(200:11)(250:20)(100:21)(50:30)(50:31)

А получаю:

Код:
// Быстрая сортика
    void quicksort(struct ProcessManager * PRMR, int first, int last, bool SEC){
        struct SimpleProcess count;
        int mid;
        int f=first, l=last;

        if (PRMR->RealCount < 2) return;

        if (SEC) mid=PRMR->Process[(f+l) / 2].SecurityLevel;
            else mid=PRMR->Process[(f+l) / 2].Priority;

        do {
            if (SEC){
                while (PRMR->Process[f].SecurityLevel<mid) f++;
                while (PRMR->Process[l].SecurityLevel>mid) l--;
            } else {
                while (PRMR->Process[f].Priority<mid) f++;
                while (PRMR->Process[l].Priority>mid) l--;
            }
            if (f<=l) //перестановка элементов
            {
            count=PRMR->Process[f];
            PRMR->Process[f]=PRMR->Process[l];
            PRMR->Process[l]=count;
            f++;
            l--;
            }
        } while (f<l);

        if (first<l) quicksort(PRMR, first, l, SEC);
        if (f<last)  quicksort(PRMR, f, last, SEC);
    }

    // Сортировка диспетчера задач
    bool sort_procman(struct ProcessManager * PRMR){

        // Сортировка процесс менеджера
        if (PRMR->Sorted) return true;
        if (PRMR->RealCount <= 1) {PRMR->Sorted = true; return true;}

        // Сортировка по приоритету
        quicksort(PRMR, 0, PRMR->RealCount-1, false);

        // Сортировка по уровню безопасности
        quicksort(PRMR, 0, PRMR->RealCount-1, true);

        // Обновляем инфо
        PRMR->Sorted = true;
        return true;

    }

Вопрос: Почему так получается и как получить желаемое?
P.S. Сорри, что картинками - программа выполняется под MS-DOS

A: Нужна только одна сортировка с правильной функцией сравнения, в которой должно в первую очередь сравниваться главное поле, а при его равенстве - вторичное (и т.д., если полей много).
В указанном примере главным полем будет второе, но  это можно переключать.
Примерно так работают сортировки элементов в проводнике Windows в табличном режиме показа - при выборе колонки "по типу" файлы будут группироваться по расширению, а в каждой группе  упорядочиваться по имени. При выборе колонки "по имени" - наоборот.


text:
Q: Limit RNN legal output for each time step I'm trying to make an RNN predict moves for a card game. In each time step, only certain actions are legal (i.e. some moves cannot be made in certain situations).
So at any given point through the game, one out of 12 moves is the correct one. Each move is labeled as an int in range 0 through 11. In most situations, only a subset of these are actually legal moves. So say I try to train the model, and it predicts e.g. move 4 in a situation, however only moves 2, 3 and 9 are legal at this time. After this move has been made, a different subset is allowed for the next time step. How do I make it predict from only a subset of the moves?
I haven't come so far as to coding the model yet, but I intend to use Keras/TensorFlow LSTM in Python to do this.
I would be happy if you could point me in a good direction here!

A: You can add a mask as an argument of calling your model.
But the simpliest way is to get prediction as probabilities of all moves and then just ignore those which are not permitted.


text:
Q: Android - determine number of fingers touching How do you determine the number of fingers are touching the screen at the same time?

A: You can get through your MotionEvent of in onTouchEvent(MotionEvent event)
int pointerCount = event.getPointerCount();

MotionEvent.getPointerCount() returns the number of active pointers


text:
Q: Excel Application.Input full address I am trying to write a macro in Excel where I could format sheets dynamically. 1 macro, without a hardcoded sheet's name.
I don't know how to extract the entire value of the Application.Selection if the macro points to another sheet (and I need to do it on another sheet)
Sub GetRangeToModify()

    Dim RangeOfA1, RangeOfA2 As range

    Set RangeOfA1 = Application.Selection
    Set RangeOfA2 = Application.InputBox("Select the loaded CSV's sheet' A1 field", "Select A1 cell", RangeOfA1, Type:=8)
    MsgBox RangeOfA2.Address
End Sub

With this snippet you can get the location of the cell, but the sheet's name is not visible ( e.g. $K$16; not Sheet1!$K$16)

The plan is: get the full string from the selection (e.g: Sheet2!$L$19), activate another sheet with the extracted sheet's name, and do stuff there (insert new columns etc.)
Is there a way to do it properly?

A: Try:
Dim RangeOfA1 as Range, RangeOfA2 As range 'must assign explicit data type for each declaration; otherwise, data type is Variant by default.

Dim strWS as String 'worksheet name

Set RangeOfA1 = Application.Selection
Set RangeOfA2 = Application.InputBox("Select the loaded CSV's sheet' A1 field", "Select A1 cell", RangeOfA1, Type:=8)
 strWS = RangeOfA2.Worksheet.Name
 MsgBox "'" & strWS & "'!" & RangeOfA2.Address


text:
Q: Erro ao executar .jar no Windows PowerShell com Maven Boa tarde à todos.
Estou tentando executar esta ferramenta (CPA - https://github.com/CityPulse/cpa). Através do link disponibilizado, realizo o download das classes.
Após isso, executo o Maven, que gera um .jar. O arquivo de configuração (pom.xml) utilizado no Maven é este: https://github.com/CityPulse/cpa/blob/master/pom.xml
Após instalar o Maven, ele gera a pasta "target" com o .jar citado acima. Ao tentar executar este .jar, inicia-se o problema.
Em todas minhas tentativas, tenho recebido o seguinte erro:
"Erro: Não foi possível localizar nem carregar a classe principal com.ericsson.research.iot.citypulse.CityPulseInterface"

Este é o comando que tenho executado:
.\java -jar C:\Users\Vinicius\Documents\GitHub\cpa\apache-maven-3.3.9\bin\target\cpa-1.0-SNAPSHOT-jar-with-dependencies.jar

O arquivo MANIFEST.MF está assim:
Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven
Built-By: Vinicius
Build-Jdk: 1.8.0_73
Main-Class: com.ericsson.research.iot.citypulse.CityPulseInterface

Meu diretório das classes e o local onde está o .jar:
JAR: C:\Users\Vinicius\Documents\GitHub\cpa\apache-maven-3.3.9\bin\target

Classe: C:\Users\Vinicius\Documents\GitHub\cpa\apache-maven-3.3.9\bin\target\src\main\java\com\ericsson\research\iot\citypulse

Fiz várias alterações no nível de diretório, colocando o .jar inclusive no mesmo das classes (dentro do package), porém o erro prosseguiu.
Obs: JAVA_HOME e PATH já estão configuradas. Utilizo Windows 10.
Podem me ajudar?

A: Abre o seu jar com winrar ou com algum descompilador de código tipo jd-gui
e certifique que a classe esteja no jar gerado. Caso não esteja você está com alguma configuração do maven errada.


text:
Q: Configure webflux oauth2 client with keycloak I'm trying to secure my microservice's endpoint using webflux oauth2 client and I use keycloak as an authorization & resource server.
Api receives Bearer JWT token and it should send the token to keycloak to check whether user has access to this resource.
I could configure this scenario using keycloak adapter but I cannot find how to do it with webflux oauth2 client.
application.yml
spring:
 security:
    oauth2:
      client:
        provider:
          keycloak:
            token-uri: KEYCLOAK_TOKEN_URL
        registration:
          keycloak:
            provider: keycloak
            client-id: client-id
            client-secret: xxx
            authorization-grant-type: client_credentials
            scope: openid

configuration class:
@EnableWebFluxSecurity
public class SecurityContextWebFlux {
    @Bean
    public ReactiveOAuth2AuthorizedClientManager authorizedClientManager(
            ReactiveClientRegistrationRepository clientRegistrationRepository,
            ReactiveOAuth2AuthorizedClientService authorizedClientService) {

        ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider =
                ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
                        .clientCredentials()
                        .build();

        AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager =
                new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
                        clientRegistrationRepository, authorizedClientService);
        authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

        return authorizedClientManager;
    }

    @Bean
    public WebClient webClient(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
        ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
        return WebClient.builder().filter(oauth).build();
    }

    @Bean
    public SecurityWebFilterChain configure(ServerHttpSecurity http) {
        return http.cors().and()
                .httpBasic().disable()
                .authorizeExchange()
                .anyExchange()
                .authenticated()
                .and()
                .oauth2Client()
                .and()
                .build();
    }
}

Here are logs showing following message:
Request 'GET /v1/products' doesn't match 'POST /logout
more:
2022-02-16T18:08:23.169Z [trace_id= span_id= trace_sampled=] - DEBUG http-nio-8181-exec-2 athPatternParserServerWebExchangeMatcher : Request 'GET /v1/products' doesn't match 'null /oauth2/authorization/{registrationId}'
2022-02-16T18:08:23.205Z [trace_id= span_id= trace_sampled=] - DEBUG parallel-1 o.s.s.w.s.u.m.OrServerWebExchangeMatcher : Trying to match using PathMatcherServerWebExchangeMatcher{pattern='/logout', method=POST}
2022-02-16T18:08:23.205Z [trace_id= span_id= trace_sampled=] - DEBUG parallel-1 athPatternParserServerWebExchangeMatcher : Request 'GET /v1/products' doesn't match 'POST /logout'
2022-02-16T18:08:23.205Z [trace_id= span_id= trace_sampled=] - DEBUG parallel-1 o.s.s.w.s.u.m.OrServerWebExchangeMatcher : No matches found

Can someone explain how I can configure webflux oauth2 client with keycloak?


text:
Q: Any ways to add custom/debug message to details of failed test method of python/django unittest.TestCase? I am using unittest.TestCase to write test cases for my django app (which is essentially the same unittest.TestCase from python). Whenever a test method fails, I get the explanation of it in the format below. Is there a way that I can add custom/debug messages to the output of failed test method?
======================================================================
FAIL: test_bad_votes (polls.tests.views.PollsViewsTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/colinh/Development/tutorials/guide-to-testing-in-django/polls/tests/views.py", line 66, in test_bad_votes
    self.assertEqual(resp.context['form']['choice'].errors, [u'This field is required.'])
AssertionError: [] != [u'This field is required.']

A: In general, you want to inherit from django's unittest class TestCase, which you can get by importing from django.test. That said, you can pass a msg argument to whatever you're trying to evaluate, containing the failure message.
Here's an example from Humanize:
class HumanizeTests(TestCase):

    def humanize_tester(self, test_list, result_list, method):
        # Using max below ensures we go through both lists
        # However, if the lists are not equal length, this raises an exception
        for test_content, result in zip(test_list, result_list):
            t = Template('{%% load humanize %%}{{ test_content|%s }}' % method)
            rendered = t.render(Context(locals())).strip()
            self.assertEqual(rendered, escape(result),
                         msg="%s test failed, produced '%s', should've produced '%s'" %     (method, rendered, result))

Obviously, yours doesn't need to look like the above, but you can see the msg argument in action.


text:
Q: UITableViewCells invisible Requirement :
I have a list of UITableviewCell loaded from a nib that I'm presenting on UITableview. The first time I open the UIViewController all cells are shown correctly and work as expected.
Issue :
If I navigate back to the parent and then open the UIViewController again the UITableviewCell are 'invisible'. I say invisible because with a breakpoint in cellForRowAt I can see that the table view does load all cells and the cells are valid.
Code :
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 13
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 40
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = (project?.sliderData.sliders[indexPath.row].view)! as UITableViewCell
    print(cell.contentView.subviews.count)
    if let left = cell.viewWithTag(2) as? UILabel {
        left.text = "left"
    }
    if let middle = cell.viewWithTag(3) as? UILabel {
        middle.text = "middle"
    }
    if let right = cell.viewWithTag(4) as? UILabel {
        right.text = "right"
    }
    return cell
}

Screen Shot Image

Expected observation :
I was thinking that maybe the subviews of the cells get released because I don't have any bindings to them in IB. To test this I'm printing the count of subviews and writing some text to the subview labels. And everything seems to go fine, the cells are loaded and the labels are there but the cells just don't show up.
But then, if I scroll the TableView up and down a little to get some cells updated those cells do appear at the top and bottom of the view as shown in the pic.

A: You need to call dequeueReusableCell(withIdentifier: "cell") inside your code then will show your table cell. It will reuse cell for your all numbers of row data content.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! UITableViewCell
   return cell
}

More Details : How to create uitableview with multiple sections in iOS Swift.

A: Did not find reason why the tableView behaves the way it does so I solved the issue by dequeueing default cells. The views provided by the slider objects are added as subviews to the dequeued cells. Now the subviews can of course be any UIViews.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "sliderCell")
    if cell == nil {
        cell = UITableViewCell.init(style: .default, reuseIdentifier: "sliderCell")
    }
    cell?.addSubview((project?.sliderData.sliders[indexPath.row].view)!)
    return cell!
}


text:
Q: Google Chrome Remote Debugging - Loading Page I have been reading through Google Chrome Remote Debugging documentation (http://code.google.com/chrome/devtools/docs/remote-debugging.html), but I still don't understand how do I open a new web page in Google Chrome. I am using Python and after launching Google Chrome with --remote-debugging-port, I can only communicate with /json on the localhost (I am writing a custom debugger for internal testing).
I have tried to build a JSON object by reading this http://code.google.com/chrome/devtools/docs/protocol/page.html and send it to /json, but no results.
Any help would be appreciated!
EDIT: I found out how to send the commands - connecting through Web Sockets to the webSocketDebuggerUrl returned when doing a query to /json (you can use websocket for python) and then simply sending the parameters (json format) as defined.

A: *

*you can ask your further questions in https://groups.google.com/forum/#!forum/google/chrome-developer-tools if you like. (I just got your question about DevTools with help of Google Alert's rss feed);

*you can sniff the messages between DevTools and Chrome (Open DevTools in detached mode, open DevTools for DevTools, open console in the second instance and write window.dumpInspectorProtocolMessages = 1)


text:
Q: Splitting comma separated values to multiple columns I am trying to split a comma separated column to multiple columns using SQL such that each separated value is under its own column on Snowflake
This is a sample of my table
"2015-01-01","00:52:44",161144,"3.1.0","x86_64","mingw32","Formula","1.1-2","US",1

This is what I have tried:
SELECT * FROM "TUTORIAL"."PUBLIC"."CRAN_LOGS" STRING_SPLIT('date','time','size','r_version','r_arch','r_os','package','version','country','ip_id',';')

This is giving me the error message:

SQL compilation error: syntax error line 1 at position 59 unexpected
''date''. syntax error line 1 at position 149 unexpected ')'.

A: You are looking for split_part
SPLIT_PART(<string>, <delimiter>, <partNumber>)

Just be careful with column names though. Some of them could be reserved keywords in SQL and might throw an error
with your_table as
(select 'date,time,size,r_version,r_arch,r_os,package,version,country,ip_id' as col)

select split_part(col,',',1) as date,
       split_part(col,',',2) as time,
       split_part(col,',',3) as size,
       split_part(col,',',4) as r_version,
       split_part(col,',',5) as r_arch,
       split_part(col,',',6) as r_os,
       split_part(col,',',7) as package,
       split_part(col,',',8) as version,
       split_part(col,',',9) as country,
       split_part(col,',',10) as ip_id
from your_table;


text:
Q: Random color for uiview In my xcode i have a uiview which is dynamic
UIView *gaping=[[UIView alloc] initWithFrame:CGRectMake(15, 0, 172, 39)];
    gaping.backgroundColor= [UIColor redColor];

I need the background color to be dynamically change.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UIView *gaping=[[UIView alloc] initWithFrame:CGRectMake(15, 0, 172, 39)];
    gaping.backgroundColor= [UIColor redColor];

    UITableViewCell *TableCell = [[UITableViewCell alloc] init];
    NSMutableDictionary *RRTYRT = [DATAARRAY objectAtIndex:indexPath.row];

    UILabel *LabelOne = [[UILabel alloc] initWithFrame:CGRectMake(45, 0, 100, 30)];
    LabelOne.textColor = [UIColor whiteColor];
    LabelOne.backgroundColor = [UIColor clearColor];
    LabelOne.text = [RRTYRT objectForKey:@"themename"];
    [gaping addSubview:LabelOne];

    [gaping.layer setCornerRadius:5.8f];

    [TableCell.contentView addSubview:gaping];
    return TableCell;

}

The below mentioned code is the table view within which i have this view and for each cell of the tableview i need to change the color of this UiView. I know its a bit confusing to understand so please if anyone can help me it would be aooritiable .
Thanks

A: Here is a random color from Tapku library
- (UIColor*) randomColor{
    int r = arc4random() % 255;
    int g = arc4random() % 255;
    int b = arc4random() % 255;
    return [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1];
}

And to use it:
LabelOne.backgroundColor = [self randomColor];

But you should consider read some articles about developing in objective-c, and the proper uses of UITableView with reusing cells

A: UIColor *color;
float randomRed = arc4random() % 255;
float randomGreen = arc4random() % 255;
float randomBlue = arc4random() % 255;

 gaping.backgroundColor= [UIColor colorWithRed:randomRed green:randomGreen blue:randomBlue alpha:1.0];

A: Try to use like this and make your color what you want:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UIView *gaping=[[UIView alloc] initWithFrame:CGRectMake(15, 0, 172, 39)];

    CGFloat redLevel    = rand() / (float) RAND_MAX;
    CGFloat greenLevel  = rand() / (float) RAND_MAX;
    CGFloat blueLevel   = rand() / (float) RAND_MAX;

    gaping.backgroundColor = [UIColor colorWithRed: redLevel
                                                green: greenLevel
                                                 blue: blueLevel
                                                alpha: 1.0];

    UITableViewCell *TableCell = [[UITableViewCell alloc] init];
    NSMutableDictionary *RRTYRT = [DATAARRAY objectAtIndex:indexPath.row];

    UILabel *LabelOne = [[UILabel alloc] initWithFrame:CGRectMake(45, 0, 100, 30)];
    LabelOne.textColor = [UIColor whiteColor];
    LabelOne.backgroundColor = [UIColor clearColor];
    LabelOne.text = [RRTYRT objectForKey:@"themename"];
    [gaping addSubview:LabelOne];

    [gaping.layer setCornerRadius:5.8f];

    [TableCell.contentView addSubview:gaping];
    return TableCell;

}

A: This is a nice way to get random background color similar to clear app effect:
-(UIColor*)bcgColorForIndexPath:(NSIndexPath*) indexPath
{
    NSUInteger rowCount = [YOURARRAY count] - 1; //it's your array which gives you all rows for data source
    float value = ((float)indexPath.row / (float)rowCount) * 0.5; // You can change this value depends on your needs
    return [UIColor colorWithRed: 1.0 green:value blue: 0.0 alpha:1.0]; // You can make different color dynamic, for example red, it's deepends on your requirements
}

And you call it like that:
gaping.backgroundColor = [self bcgColorForIndexPath:indexPath];

A: try this
int lowerBound = 1;
int upperBound = 255;
int red = lowerBound + arc4random() % (upperBound - lowerBound);
int green = lowerBound + arc4random() % (upperBound - lowerBound);
int blue = lowerBound + arc4random() % (upperBound - lowerBound);
[gaping setBackgroundColor:[UIColor colorWithRed:red green:green blue:blue alpha:1.0]];

A: Any changes to the background color of a cell into cellForRowAtIndexPath are ignored. Instead change cell color in:
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.backgroundColor = [self bcgColorForIndexPath:indexPath];
}

...using Greg's bcgColorForIndexPath method.

A: Just instantiate some UIColor to  an array of colors:
NSMutableArray *myColors = [[NSMutableArray alloc] initWithObjects:[UIColor redColor], [UIColor blackColor], [UIColor pinkColor], [UIColor yellowColor] , nil];

And then set your UIView backgroundColor as follow:
gaping.backgroundColor= [myColors objectAtIndex:indexPath.row];

if it solves your purpose, let me know.
Feel free ask further.


text:
Q: React Native can't build app - IOS I initialized a new project with react-native cli, opened it and tried to build it in IOS. it's the first time I ever tried doing it. first project ever.
and every time i try to build the project, it wouldn't install on the ios simulator, the build is failed and i get this error -
Installing build/Build/Products/Debug-iphonesimulator/Albums.app
An error was encountered processing the command (domain=MIInstallerErrorDomain, code=4):
Failed to chmod /Users/Eilon/Library/Developer/CoreSimulator/Devices/1E826A2C-E2AF-4C6C-84CE-6C52E6A0262D/data/Library/Caches/com.apple.containermanagerd/Bundle/Application/A2B54114-E373-4209-82F1-748BCC9899BB/Albums.app/Albums : No such file or directory
Launching org.reactjs.native.example.Albums

and it just stuck.
I tried reinstall Xcode few times and nothing helps.
any idea what the problem could be?

A: Well After more than 2 days of struggling this. the problem was the folder structure. one of the folders had spaces in it's name, after removing the spaces everything worked fine.


text:
Q: Can not add new key value to object inside foreach loop using Node.js I am trying to add one new key/value pair into object inside forEach loop using Node.js but as per my code its not working. I am explaining my code below.
user.StoreDetails.forEach(ele => {
    let findValue = resArr.find((item) => {return item.StoreCode === ele.StoreCode});
    ele.StoreName = findValue.StoreName;
    console.log('ele', ele);
})

Here I need to add new key/value pair i.e-StoreName but after finishing loop that key/value is appending to that particular object.


text:
Q: $DISPLAY dependent gtk themes I have a computer at home that I log into remotely. The "monitor" for it is a TV, so I want gtk applications to use a large font and icon theme, which I managed to do by editing the ~/.gtkrc-2.0 file and some other similar stuff. What I want to be able to do is have a separate theme for when I'm logging in remotely. The best way to explain is that I would like my gtk theme choice to be dependent on the X display that the application is started on. For example, if I start something on :0.0 then that is the TV and I want large fonts, but if I start it on localhost:10.0 I want to use a regular size font, because it will get rendered on my laptop screen.
The elegant solution would be to have some sort of IF statement in the .gtkrc-2.0 file that checks the $DISPLAY variable and behaves accordingly. The problem is I can't find any documentation on control structures in .gktrc files, or if it's even possible to do that.
[Edit]
Additionally, is there any way to do this in GTK+ 3 without having to install gnome?

A: You can achieve this by running an XSETTINGS daemon, e.g. xsettingsd (or Xfce xfsettingsd or GNOME gsd-xsettings) locally on both machines. It will affect all clients of the X display it's running on, overriding gtkrc.
If the program uses GTK+ 2, you can point $GTK2_RC_FILES to a colon-separated list of alternative gtkrc's. (There is no direct alternative for GTK+ 3 settings.ini; it uses Xsettings as the primary mechanism.)
Note: This method will likely stop working in GTK 4, which prefers reading internal GSettings.

A: AFAIK it is not possible to make do any scripting for gtkrc. You can copy both configurations to somewhere where you can restore them from .xinitrc, .xsession or other X startup file. The only problem is that you can't use both :0.0 and :10.0 running in parallel with different themes. You should either run only one X at time or make different user with different home directory for your TV setup for instance. You can even use the same UID/GID for both users and will have access to all files.


text:
Q: A question about gerunds If someone say "non-radiating objects"...
Does he mean : objects that do not have emission of radiation ?
If yes, why do we not say "non-radiator objects" ? What is the difference?

A: Not all words that end in ing are gerunds. And in the phrase non-radiating objects, radiating is not a gerund.
So your question is based on a misunderstanding. (But yes a non-radiating object would be an object that does not emit radiation.)
A gerund is a verb form that functions as a noun. In your example radiating functions as an adjective, modifying objects; it's known as a participial adjective.
Whether a verb form is a gerund or a participial adjective depends on how it is used. For example, in the following sentences words ending in ing are used as gerunds:

His asking her to marry him came as a great surprise.
  They loved swimming in the sea.
  The quality of her singing impressed the audience.

But the ing words in the following expressions are functioning as adjectives, not gerunds:

A boiling kettle
  A leaking tap
  A sprinting athlete
  An aching muscle

Although we often combine two nouns (whether as a single word, hyphenated or in sequence), so that the first functions as an adjective (toothbrush, shoe-lace, coffee mug) the combination radiator object is not in common use.
https://www.englishclub.com/grammar/nouns-adjective.htm
https://www.englishclub.com/grammar/nouns-compound.htm
https://www.thoughtco.com/what-is-a-participial-adjective-1691486


text:
Q: Unable to get OpenSearch dashboard by running OpenSearch docker compose I am a windows user. I installed Windows Subsystem for Linux [wsl2] and then installed docker using it. Then I tried to get started with OpenSearch so I followed the documentation in the given link
https://opensearch.org/downloads.html and run docker-compose up, In the shell, I am getting an error message like

opensearch-dashboards  | {"type":"log","@timestamp":"2022-01-18T16:31:18Z","tags":["error","opensearch","data"],"pid":1,"message":"[ConnectionError]: getaddrinfo EAI_AGAIN opensearch-node1 opensearch-node1:9200"}

In the port http://localhost:5601/ I am getting messages like

OpenSearch Dashboards server is not ready yet

I also changed resources preference for memory to 5GB in docker-desktop but it still doesn't work. Can somebody help me with this?

A: After 5 days having issues with opensearch I've found something working fine for me:

*

*Set docker memory to 4GB

*And docker vm.max_map_count = 262144

Then I use previous versions of opensearch because the latest does not seems stable:

*

*opensearchproject/opensearch:1.2.3

*opensearchproject/opensearch-dashboards:1.1.0

*opensearchproject/logstash-oss-with-opensearch-output-plugin:7.16.2

Here is my docker-compose.yml file:
version: '3'
services:
  opensearch-node1A:
    image: opensearchproject/opensearch:1.2.3
    container_name: opensearch-node1A
    environment:
      - cluster.name=opensearch-cluster
      - node.name=opensearch-node1A
      - discovery.seed_hosts=opensearch-node1A,opensearch-node2A
      - cluster.initial_master_nodes=opensearch-node1A,opensearch-node2A
      - bootstrap.memory_lock=true # along with the memlock settings below, disables swapping
      - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m" # minimum and maximum Java heap size, recommend setting both to 50% of system RAM
    ulimits:
      memlock:
        soft: -1
        hard: -1
      nofile:
        soft: 65536 # maximum number of open files for the OpenSearch user, set to at least 65536 on modern systems
        hard: 65536
    volumes:
      - opensearch-data1:/usr/share/opensearch/data
    ports:
      - 9200:9200
      - 9600:9600 # required for Performance Analyzer
    networks:
      - opensearch-net
  opensearch-node2A:
    image: opensearchproject/opensearch:1.2.3
    container_name: opensearch-node2A
    environment:
      - cluster.name=opensearch-cluster
      - node.name=opensearch-node2A
      - discovery.seed_hosts=opensearch-node1A,opensearch-node2A
      - cluster.initial_master_nodes=opensearch-node1A,opensearch-node2A
      - bootstrap.memory_lock=true
      - "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m"
    ulimits:
      memlock:
        soft: -1
        hard: -1
      nofile:
        soft: 65536
        hard: 65536
    volumes:
      - opensearch-data2:/usr/share/opensearch/data
    networks:
      - opensearch-net
  opensearch-dashboardsA:
    image: opensearchproject/opensearch-dashboards:1.1.0
    container_name: opensearch-dashboardsA
    ports:
      - 5601:5601
    expose:
      - "5601"
    environment:
      OPENSEARCH_HOSTS: '["https://opensearch-node1A:9200","https://opensearch-node2A:9200"]'
    networks:
      - opensearch-net
  logstash-with-plugin:
    image: opensearchproject/logstash-oss-with-opensearch-output-plugin:7.16.2
    container_name: logstash-with-plugin
    networks:
      - opensearch-net

volumes:
  opensearch-data1:
  opensearch-data2:

networks:
  opensearch-net:

A: I had the same issue with my Opensearch-dashboards instance installed on VM without Docker usage. The problem was caused by wrong setting for connection to search engine in the opensearch-dashboards.yml file. I mixed up https and http protocols here (there was mismatch between settings of opensearch and opensearch-dashboards):
opensearch.hosts: [https://localhost:9200]

A: I had the same error message when opening "http://localhost:5601/" while testing opensearch and opensearch dasboard locally using Docker in Windows 10:

*

*OpenSearch Dashboards server is not ready yet

*opensearch-dashboards |
{"type":"log","@timestamp":"2022-02-10T12:29:35Z","tags":["error","opensearch","data"],"pid":1,"message":"[ConnectionError]:
getaddrinfo EAI_AGAIN opensearch-node1 opensearch-node1:9200"}

But when looking into the log I also found this other error:

*

*opensearch-node1 | [1]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]

The 3 part solution working for me was:
Part 1
On each opensearch nodes update the file:
/usr/share/opensearch/config/opensearch.yml

And add line:
plugins.security.disabled: true

Before the security plugins:
cks. "Single-node" mode disables them again.
#discovery.type: single-node

plugins.security.disabled: true

######## Start OpenSearch Security Demo Configuration ########
# WARNING: revise all the lines below before you go into production
plugins.security.ssl.transport.pemcert_filepath: esnode.pem

I found the information on opensearch official documentation
Part 2
Setting allocated memory for docker desktop to 4GB into .wslconfig more information here:
opendistrocommunity discussion
stackoverflow aloocate memory
Make sure your allocated memory is well set up (you have to restart docker desktop) with this command: docker info and check the line "Total Memory" it should be set to 4GB (approximately, in my case it has be set to 3.84GiB)
Part 3
And also increase vm.max_map_count:

*

*open powershell

*wsl -d docker-desktop

*echo "vm.max_map_count = 262144" > /etc/sysctl.d/99-docker-desktop.conf

The info was founded here on github discussion


text:
Q: How to run Microsoft command line compilers from PowerShell Windows 7, PowerShell 2, Visual Studio 2015, I'm trying to run the command line C# compiler from PowerShell (not the embedded PowerShell within Visual Studio, but a regular, full-blown command window).
In the normal course of events, before using the command line compilers you need to run C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat but that doesn't work here because the environment variables will be set within cmd.exe and then discarded when control returns to PowerShell.
https://github.com/nightroman/PowerShelf supplies Invoke-Environment.ps1 that sounds like it might be the solution, but Invoke-Environment "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" does nothing, no effect whatsoever.
Am I using Invoke-Environment the wrong way, or is there something else I should be doing?

A: i've made a simple cmdlet to set the current PowerShell instance to a "developer environment" that i just leave on my $profile, it uses 2 modules from ms, one is to find where visual studio is installed, and the other comes with vs 2019 and up, it is used to power the "vs PowerShell" thing on start menu.
here's it:
function Enter-VsDevEnv {
    [CmdletBinding()]
    param(
        [Parameter()]
        [switch]$Prerelease,
        [Parameter()]
        [string]$architecture = "x64"
    )

    $ErrorActionPreference = 'Stop'

    if ($null -eq (Get-InstalledModule -name 'VSSetup' -ErrorAction SilentlyContinue)) {
        Install-Module -Name 'VSSetup' -Scope CurrentUser -SkipPublisherCheck -Force
    }
    Import-Module -Name 'VSSetup'

    Write-Verbose 'Searching for VC++ instances'
    $vsinfo = `
        Get-VSSetupInstance  -All -Prerelease:$Prerelease `
    | Select-VSSetupInstance `
        -Latest -Product * `
        -Require 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64'

    $vspath = $vsinfo.InstallationPath

    switch ($env:PROCESSOR_ARCHITECTURE) {
        "amd64" { $hostarch = "x64" }
        "x86" { $hostarch = "x86" }
        "arm64" { $hostarch = "arm64" }
        default { throw "Unknown architecture: $switch" }
    }

    $devShellModule = "$vspath\Common7\Tools\Microsoft.VisualStudio.DevShell.dll"

    Import-Module -Global -Name $devShellModule

    Write-Verbose 'Setting up environment variables'
    Enter-VsDevShell -VsInstanceId $vsinfo.InstanceId  -SkipAutomaticLocation `
        -devCmdArguments "-arch=$architecture -host_arch=$hostarch"

    Set-Item -Force -path "Env:\Platform" -Value $architecture

    remove-Module Microsoft.VisualStudio.DevShell, VSSetup
}

i leave my profile on gh so, there this function wil always be up-to-date


text:
Q: Loop Through Table and then Transpose Copy VBA Macro I am trying to have copy a row, copy and paste transpose, then go down a row and loop until the row is empty in value. Here is my Code:

Sub Loop

Dim rng As Range
Set rng = Range("B2:D2")

Dim paste As Range
Set paste = Range("F:F")

Do Until IsEmpty(ActiveCell)

Commits.Select
Selection.Copy
upl.Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= \_

False, Transpose:=True

Commits.Activate
ActiveCell.Offset(rowoffset:=1).Activate

Loop

End Sub

The code creates an infinite loop and I am unsure how to fix it. Here is the final product I want it to look like


text:
Q: Python how to get labels of a generated adjacency matrix from networkx graph? If i've an networkx graph from a python dataframe and i've generated the adjacency matrix from it.
So basically, how to get labels of that adjacency matrix ?

A: Assuming you refer to nodes' labels, networkx only keeps the the indices when extracting a graph's adjacency matrix. Networkx represents each node as an index, and you can add more attributes if you wish. All node's attributes except for the index are kept in a dictionary. When generating graph's adjacency matrix only the indices are kept, so if you only wish to keep a single string per node, consider indexing nodes by that string when generating your graph.

A: If the adjacency matrix is generated without passing the nodeList, then you can call G.nodes to obtain the default NodeList, which should correspond to the rows of the adjacency matrix.


text:
Q: Jenkins using docker as an agent I am not able to integrate Docker with Jenkins completely. I setup Docker at Cloud Node settings in the Jenkins portal. How can I use some image that contains Node, Ruby, etc? Must those images contain a JDK?

A: There is a great post with a detailed explanation of how to deal with this here. In the post, they state that every Docker image (even if you require building a Node or Ruby project) requires a JDK. Seems the JDK requirement comes from the Docker plugin.


text:
Q: Will JSP Modification remain after Tomcat restart? A war file is deployed in Tomcat 6 on Solaris 10. antiResourceLocking is not set to true. A change is to be made to a JSP in the application folder(exploded from the war file). No restart is made.
If Tomcat is restarted inadvertently, will the JSP change made earlier still be around or would it overwritten from the war?

A: It will stay the same. The war is only exploded once.
Of course you can delete the war file to be on the safe side, it's not needed any more.


text:
Q: JavaFx CSS - Slider Track Trying to style Slider using CSS. In IntelliJ ide I notice the line is underlined & gives an error (as shown below).
I referred to Link1 Link2 Link3 get some understanding of Linear Gradient, but still unable to understand what is causing the error.
Hope issue faced is clear, await inputs.
Error:
Mismatched parameters ([[from <point> to <point> | to <side-or-corner>] ,]?
[[repeat | reflect] ,]? <color-stop> [, <color-stop>]+) less... (Ctrl+F1)

Inspection info: This inspection detects unknown functions and illegal function parameters.

IDE:

A: I found this link where instead of using the derive the code is specified as:
linear-gradient(to right, #2D819D 20%, #969696 20%);

I have adopted the above approach & this eliminates the error. Hope this is the right approach


text:
Q: How can I find all resources that can access an S3 bucket I have an S3 bucket, and I want to know which AWS resources have permission to access it (security audit). There is nothing in the bucket policy itself - permissions are defined using IAM policies on the resources.
I have a LOT of different components on this project. Is there a way to find all the resources that have permissions for this bucket? Or do I have to check the IAM policies on every single resource in the account?


text:
Q: Exporting data into Excel with multiple spreadsheets Has anyone successfully transferred data into Excel with multiple spreadsheets?
I'm stuck with it. I'm using Visual Basic 2010.

A: Yes, using EPPlus. It's as simple as:
Dim ws = package.Workbook.Worksheets.Add("Name")

Thanks Tim :)

A: You can use this method to export data to excel file:
Public Shared Function ExportDataTableToDataFile(ByVal srcDataTable As DataTable, ByVal dbTbName As String, _
                                               ByVal dbFilePath As String, ByVal dbFileType As String, _
                                               Optional ByVal schemaTable As DataTable = Nothing) As Boolean

        Dim expConnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbFilePath

        Select Case dbFileType
            Case ".dbf"
                If dbTbName.Length > 8 Then
                    dbTbName = dbTbName.Remove(8)
                End If

                expConnStr &= ";Extended Properties=dBase IV"
            Case ".xls"
                expConnStr &= dbTbName & ".xls;Extended Properties=""Excel 8.0;HDR=YES;IMEX=0"""
            Case ".mdb"
                expConnStr &= dbTbName & ".mdb;User Id=admin;Password="
            Case ".csv"
                expConnStr &= ";Extended Properties=""text;HDR=Yes;FMT=Delimited(,)"""
                dbTbName &= ".csv"
            Case ".mpp"
                expConnStr = "Provider=Microsoft.Project.OLEDB.10.0;Project Name=" & dbFilePath & dbTbName & ".mpp"
            Case Else
                Return False
        End Select

        Dim res As Boolean = True
        Dim createCmdStr As String = "CREATE TABLE [" & dbTbName & "] ("
        Dim insertCmdStr As String = "INSERT INTO [" & dbTbName & "] ("
        Dim insertParams As String = " VALUES ("
        Dim paramPrefix As String = "@p_"
        Dim oleDbCon As New OleDbConnection(expConnStr)
        Dim oleDbDa As New OleDbDataAdapter
        Dim createCmd As New OleDbCommand
        Dim insertCmd As New OleDbCommand
        Dim param As OleDbParameter
        Dim oleDbColTp As OleDbType

        Try
            If String.IsNullOrEmpty(dbTbName) Or String.IsNullOrEmpty(dbFilePath) Or srcDataTable Is Nothing Then
                res = False
                Return res
            End If

            If Not System.IO.Directory.Exists(dbFilePath) Then
                System.IO.Directory.CreateDirectory(dbFilePath)
            End If

            If System.IO.File.Exists(dbFilePath & dbTbName & dbFileType) Then
                System.IO.File.Delete(dbFilePath & dbTbName & dbFileType)
            End If

            If dbFileType = ".mdb" Then
                Dim ADOXCatalog As New ADOX.Catalog

                Try
                    ADOXCatalog.Create(expConnStr)
                Catch ex As System.Runtime.InteropServices.COMException
                Catch ex As Exception
                    MessageBox.Show(ex.Source & ": " & ex.Message.ToString, "Chyba!")
                    Return False
                Finally
                    ADOXCatalog = Nothing
                End Try
            End If

            For Each col As DataColumn In srcDataTable.Columns
                If col.DataType Is GetType(DateTime) Then
                    oleDbColTp = OleDbType.VarWChar
                Else
                    If schemaTable IsNot Nothing Then
                        oleDbColTp = schemaTable.Rows(srcDataTable.Columns.IndexOf(col))(11)
                    Else
                        oleDbColTp = GetOleDbType(col.DataType)
                    End If
                End If

                createCmdStr &= "[" & col.ColumnName & "] " & GetSqlDbType(col.DataType).ToString

                If col.DataType Is GetType(String) Then 'OleDb dovoluje max dlzku 255 pre VarChar
                    If col.MaxLength > 255 Then
                        col.MaxLength = 255
                    End If

                    createCmdStr &= " (" & col.MaxLength & ")"
                End If

                'createCmdStr &= IIf(col.AllowDBNull, "", " NOT NULL")
                insertCmdStr &= "[" & col.ColumnName & "]"
                insertParams &= "?"

                param = insertCmd.Parameters.Add(paramPrefix & col.ColumnName, oleDbColTp, col.MaxLength, col.ColumnName)
                param.SourceVersion = DataRowVersion.Current

                If Array.IndexOf(srcDataTable.PrimaryKey, col) >= 0 Then
                    createCmdStr &= " PRIMARY KEY"
                ElseIf col.Unique Then
                    createCmdStr &= " UNIQUE"
                End If

                If srcDataTable.Columns.IndexOf(col) < srcDataTable.Columns.Count - 1 Then
                    createCmdStr &= ", "
                    insertCmdStr &= ", "
                    insertParams &= ", "
                Else
                    createCmdStr &= ")"
                    insertCmdStr &= ")"
                    insertParams &= ")"
                End If
            Next

            insertCmdStr &= insertParams
            createCmd.Connection = oleDbCon
            createCmd.CommandText = createCmdStr
            insertCmd.Connection = oleDbCon
            insertCmd.CommandText = insertCmdStr
            oleDbDa.InsertCommand = insertCmd

            For Each drow As DataRow In srcDataTable.Rows
                drow.AcceptChanges()
                drow.SetAdded()
            Next

            If oleDbCon.State <> ConnectionState.Closed Then
                oleDbCon.Close()
            End If

            oleDbCon.Open()
            'createCmd.ExecuteNonQuery()
            oleDbDa.Update(srcDataTable)
        Catch ex As Exception
            res = False
            MessageBox.Show(ex.Message.ToString, "Chyba!")
        Finally
            oleDbCon.Close()
        End Try

        Return res

    End Function


text:
Q: nub not compiling when checking a list for duplicates Working on a sudoku inspired assignment and I need to implement a function that checks if a Block Cell has no repeated elements in it (to check if its a valid solution to the puzzle).
okBlock :: Block Cell -> Bool
okBlock b = okList $ filter (/= Nothing) b
 where
  okList :: [a]-> Bool
  okList list
   | (length list) == (length (nub list)) = True
   | otherwise                            = False

*

*Block a = [a]

*Cell = [Maybe Int]
Haskell complains saying No instance for (Eq a) arising from a use of "==" Possible fix: add (Eq a) to the context of the type signature for okList...
Adding Eq a to the type signature does not help. I have tried the function in the terminal and it works fine for for lists, and for lists of lists (i.e the type I am feeding it in the function).
What am I missing here?

A: Well you can only filter out duplicates, if there is a way to check whether two values are duplicates. If we look at the type signature for nub, we see:
nub :: Eq a => [a] -> [a]

So that means that in order to filter out duplicates in a list of as, we need a to be an instance of the Eq class. We can thus simply forward the type constraint further in the signatures of the functions:
okBlock :: Block Cell -> Bool
okBlock b = okList $ filter (/= Nothing) b
 where
  okList :: Eq => [a] -> Bool
  okList list
   | (length list) == (length (nub list)) = True
   | otherwise                            = False
We do not need to specify that Cell is an instance of Eq because:

*

*Int is an instance of Eq;

*if a is an instance of Eq, so is Maybe a, so Maybe Int is an instance of Eq; and

*if a is an instance of Eq, so is [a], so [Maybe Int] is an instance of Eq.

That being said we can do some syntactical improvements of the code:

*

*there is no need to work with guards if you simply return the result of the guard True and False, and

*you can use an eta reduction and omit the b in okBlock.

*you don't need parentheses around function application (unless to feed to result straight to another, non-infix function).

This gives us:
okBlock :: Block Cell -> Bool
okBlock = okList . filter (/= Nothing)
  where
    okList :: Eq => [a] -> Bool
    okList list = length list == length (nub list)

A final note is that usually you do not have to specify a type signature. In that case Haskell will aim to dervice the most generic type signature. So you can write:
okBlock = okList . filter (/= Nothing)
  where
    okList list = length list == length (nub list)

Now okBlock will have type:
Prelude Data.List> :t okBlock
okBlock :: Eq a => [Maybe a] -> Bool

A: Three points that are too big to make in a comment.
nub is horribly slow
nub takes O(n^2) time to process a list of length n. Unless you know the list is very short, this is the wrong function to use to remove duplicates from a list. Adding a bit more information about what sort of thing you're working with allows more efficient nubbing. The simplest, and probably most general, approach that isn't absolutely wretched is to use an Ord constraint:
import qualified Data.Set as S

nubOrd :: Ord a => [a] -> [a]
nubOrd = go S.empty where
  go _seen [] = []
  go seen (a : as)
    | a `S.member` seen = go seen as
    | otherwise = go (S.insert a seen) as

length is wasteful
Suppose I write
sameLength :: [a] -> [b] -> Bool
sameLength xs ys = length xs == length ys

(which uses the approach you did). Now imagine I calculate
sameLength [1..16] [1..2^100]

How long will that take? Calculating length [1..16] will take nanoseconds. Calculating length [1..2^100] will probably take billions of years using current hardware. Whoops. What's the right way? Pattern match!
sameLength [] [] = True
sameLength (_ : xs) (_ : ys) = sameLength xs ys
sameLength _ _ = False

Nubbing isn't the right solution to this problem
Suppose I ask noDuplicates (1 : [1,2..]). Obviously, there's a duplicate, right at the beginning. But if I use sameLength and nub to check, I will never get an answer. It will keep building the nubbed list and comparing it to the original list until the seen becomes so large it exhausts your computer's memory. How can you fix that? By directly calculating what you need:
noDuplicates = go S.empty where
  go _seen [] = True
  go seen (x : xs)
    | x `S.member` seen = False
    | otherwise = go (S.insert x seen) xs

Now the program will conclude that there's a duplicate the moment it sees the second 1.


text:
Q: Use of Multi Threading for printing Odd and Even Numbers I'm pretty new to threads and just trying to get a grip on the basics.So, I tried the following code to print odd and even numbers one after the other.
But I'm getting a null pointer.
public class P {
public static void main(String[] args) throws InterruptedException {

     Print print = new Print(false);
     Even e =new Even();
     Odd o = new Odd();
     e.start();
     o.start();
}

}
class Even extends Thread
{
    Print print;
public void run()
{
  try {
    print.printeven();

} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

}
class Odd extends Thread
{
    Print print;
public void run()
{
  try {
    print.printodd();

} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

}
class Print {
public  boolean flag=false;

Print(boolean flag){

    this.flag=flag;
}

synchronized void printodd() throws InterruptedException
   {

    for(int i=1;i<10;i=i+2)
        if(!flag)
        {
        System.out.println(i);
        notifyAll();
        flag=true;
        }
        else
        {
            wait();
        }
   }

synchronized void printeven() throws InterruptedException
   {

    for(int i=2;i<=10;i=i+2)
        if(flag)
        {
        System.out.println(i);
        notifyAll();
        flag=false;
        }
        else
        {
            wait();
        }
   }

}
If someone could explain in detail what I'm doing wrong here and give a basic idea how to go about debugging this.

A: You have not instantiated Print instance in both ODD and EVEN classes.
Do this for both Even and Odd constructors.
public Odd(Print print)
{
  this.print = print;
}

When instantiating do like this.
 Print print = new Print(false);
 Even e =new Even(print);
 Odd o = new Odd(print);

A: See You are doing Nothing with
Print print = new Print(false);  // this statement
in main() method.
pass the "print" object to Odd and Even class Constructor.
You are getting Null pointer Because you are not initialising print Object Odd and Even class.


text:
Q: $Avg aggregation in Mongodb I'm trying to get the average of a field called Score that is inside an array of objects.
This is the sentence with which I tried to get it
db.classroom.aggregate([{$group : { _id : "$_id", puntaje : { $avg : "${userScore.score}" }}}])

The collection called Classroom is the following
{
        "_id" : ObjectId("56a0b43541c1375cd4e90b85"),
        "name" : "Desarrollo de Software",
        "comment" : "Salon destinado al Desarollo de Software",
        "code" : [
                {
                        "code" : "ABCDEF123456",
                        "user" : [
                                DBRef("user", 201309)
                        ]
                }
        ],
        "post" : [
                {
                        "post" : "Me gusta el salon :)",
                        "date" : ISODate("-292275055-05-16T16:47:03.192Z"),
                        "user" : DBRef("user", 201309)
                }
        ],
        "userScore" : [
                {
                        "score" : 4.5,
                        "user" : DBRef("user", 201309)
                }
        ]
}

Why the avg is always null ?


text:
Q: Word for: sideways descent down a steep slope? When descending a steep slope composed of dirt, gravel or slippery stone, one may at some point transition from a forward walk to a slower, more careful sideways one, using (say) the outside edge of the left foot and and inside edge of the right foot to dig into the ground and provide better purchase while descending.
Is there a word for this mode of locomotion, or one which could be considered to best describe it?
Usage ex:
"He _____ down the slope, picking his way around crags and boulders."

A: I think it is possible to use "sidle down" The Free Dictionary

sidle 1. to move sideways or obliquely.

And from snippet views in Google Books:

Being There: The Parables of Jesus in a Different Voice O'Malley, William J. · 2016. He hauled the mule's reins over her head and sidled down the rockfall through the bushes.

The Forgetting Tide Mike Hoinville · 2015 ... with a kind of side stepping motion as if he had skis on, he sidled down the very steep slope

People of the Bear Mother T. D. Austin · 2012 Then to my horror, as he sidled down the sloping boulder, the Grandfather slipped on a muddy patch of clay,

(NB The approved way of descending loose ground, e.g. scree, is to go down forwards - this lessens the chances of falling and of broken ankles.)

A: In skiing, the term is:

Side-slipping

I imagine it could be used in other circumstances.
The analogous term for ascending a ski slope is:

Side-stepping

which actually better describes a pedestrian ascent.

A: I think you are looking for a verb, but a noun for paths that go sideways down a steep slope in mountainous terrain is switch-back:
From: Merriam-Webster definition:
A zigzag road, trail, or section of railroad tracks for climbing a steep hill


text:
Q: Strong induction and mistake what is the fault in this reasoning by  strong induction
For all  $ A $ and $ B $ of $ M_p (K) $ and
all integer $n$ we have: $ A ^ n B = B $
The proof :
Denote  $\forall n\in \mathbb N,\quad P (n) $ :  $ A ^ n B = B $

*

*The property is true at rank $ n = 0 $ because $ A ^ 0
 B = I_n B = B $

*Let $ n $ be a natural integer, suppose $ P (n) $
true up to rank $ n $.
$ A ^ {n + 1} B = A A ^ n B = AB $ (hypothesis at rank
$ n $) and $ A B = B $ (assumption at rank $ 1 $)
we thus obtain $ A ^ {n + 1} B = B $
and $ P (n + 1) $ is true

A: In the inductive step you're only allowed to use previous steps. $P(1)$ is not a previous step for $P(1).$
The inductive step requires that $P(1)$ is already true, which is valid for $P(n)$ for all $n \geq2,$
but since you only have $P(0)$ as a base case you needed an inductive step that is valid for all $n \geq 1.$


text:
Q: Why does inflating a view in getView() cause an exception? I am trying to inflate a new view in the getView() method in one of my app's fragments. To do this, I create an LayoutInflater, and then inflate convertView:
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.inflater_my_search, parent);
    }

    return convertView;
}

However, when I do this, I get this exception:

android.view.InflateException: Binary XML file line #101: addView(View, LayoutParams) is not supported in AdapterView

What is causing this problem?

A: Use inflater.inflate(R.layout.inflater_my_search, parent, false);
The 2 param method is trying to attach the view to the parent, throwing the Exception

A: convertView = inflater.inflate(R.layout.inflater_my_search, parent); // here
 your trying to add the view in parent make sure you remove all views and then  add.

instead of that use simple techniques like
1. convertView = inflater.inflate(R.layout.inflater_my_search, parent, false);//
here your inflating view but not adding the parent.(false flag)

2 convertView = inflater.inflate(R.layout.inflater_my_search, null)//
here your not supplying any parent.


text:
Q: Decomposition of $\mathbb{C}[G]$ / Orthogonality relations I am currently working on Jean-Pierre Serre's "Linear representations" german translation in chapter 6 and I do not understand the last part of the proof of the following theorem.
a) Let $\rho_i : G \longrightarrow GL(V_i)$ for $i = 1,...,n$ be distinct irreducible representations of the group G. The map $\rho: \mathbb{C}[G] \longrightarrow \prod_{i}^{n} End(V_i)$, defined by the $\rho_i$, is surjective.
Proof:
Suppose the Image of $\rho$ is a proper subspace of  $\prod_{i}^{n} End(V_i)$. Then there exists a non zero linear form $\phi : \prod_{i}^{n} End(V_i) \longrightarrow \mathbb{C}$ that vanishes on the Image of $\rho$, i.e. $\phi (\sum_{i}^{n} \rho_i(s)) = 0 $ for all $s \in G$.
This will give us a relation of the form $\sum_{k} \lambda_k m_k(s) = 0$ for all $s \in G$. Here, the $m_k(s)$ are the coefficients in the Matrix of the representation $\rho_i(s)$.
So far the proof makes sense to me, but I do not understand the following part at all.
We want to show that all $\lambda_k$ are zero, because then we have found our contradiction to the non zeroness of $\phi$. Serre only writes:
Due to the orthogonality relations of the coefficients we can conclude that $\lambda_k = 0$ for all $k$.
The orthogonality relations from chapter 2.2 in the english version are meant here, but I just cannot see how I have to apply them to get that all $\lambda_k = 0$.
I have found another thread to the same theorem, but the proof is different at the end and I hope someone can help me with my problem.
Help would be highly appreciated.

A: Pick an $i \in \{1, \dots, n\}$. We multiply both sides of the equation $\sum_{k} \lambda_k m_k(s)= 0$ by $\bar m_i(s)$, and we take a sum over all $s \in G$, giving
$$ \sum_k \left( \lambda_k \sum_{s \in G}  m_k(s) \bar m_i(s) \right)= 0$$
But by orthogonality, $$\sum_{s \in G}  m_k(s) \bar m_i(s) = \begin{cases} |G| & {\rm  if \ } k = i \\ 0 &{\rm  if \ } k \neq i \end{cases}$$ So
$$ \sum_k \left(\lambda_k \sum_{s \in G}  m_k(s) \bar m_i(s) \right) = \lambda_i |G|.$$
Thus we have shown that $\lambda_i|G| = 0$, i.e. $\lambda_i = 0$. Since the choice of $i$ was arbitrary, this completes the proof.


text:
Q: Eval inside an ASP.net repeater doesn't work inside another control I have a Reapter control with a custom server side control inside of it. When I place the code:
<%# Eval("DateAdded") %>

inside the item template of the repeater it works fine, but when I place it inside the custom server control inside the repeater, it doesn't work.
Is it possible to do something like Parent.Eval() or Container.Eval() to get back to the context of the Reapeter rather than the custom control?

A: It should work. Can you supply more context/code for the server control?
Also, are you using single quotes to set properties on a control dynamically using eval? Double quotes should throw an error, not just be ignored.
MyProperty='<%# Eval("DateAdded") %>'

A: The repeater is databound, the control that you are placing this eval statement in isn't.  You'll need to pass the value to the control using a property.
For Example:
<uc1:MyControl MyProperty='<%# Eval("DateAdded") %>' />

You can now access the MyProperty property inside your control to access this value.


text:
Q: Play audio & video files in user account using Easy Digital Downloads WordPress plugin I use  Easy Digital Downloads plugin to sell downloadable files.
Now I want to play audio and video files (that user buy it) in user account,
I can print downloads history with this shortcode: [download_history] but this just show download history not play,
next I changed history-downloads.php file like this:

    <a href="<?php echo esc_url( $download_url ); ?>" class="edd_download_file_link">
<?php echo edd_get_file_name( $file ); ?>

play online audio
    <audio controls>
       <source src="<?php echo esc_url( $download_url ); ?>" type="audio/ogg">
       your browser dosn't support play file!
    </audio>

but I want to play Both video and audio, how can I separate video and audio type download files?
is there a way to access download category and use it like this?
<?php if($file_category_id==$video_category_id){
    echo '
play online video
        <video width="400" controls>
            <source src="'. esc_url( $download_url ) .'" type="video/mp4">
            Your browser does not support video.
        </video>';
}
else if($file_category_id==$audio_category_id){
    echo '
play online audio
        <audio controls>
            <source src="'. esc_url( $download_url ) .'" type="audio/ogg">
            your browser does not support audio!
        </audio>';
} ?>

A: You can store content type of downloadable files and use it when used short code [download_history]. For example you can use ACF plugin and set custom type on your product.


text:
Q: How to prompt user to insert an excel file then create the dataframe in pandas for further analysis Good day! I would like to know how to prompt user to insert an excel file (from any location - either in window desktop or folder) then create the dataframe in pandas for further analysis. Not really find the solution here with the complete steps. Below is what I been try, but just seem not really link together the flow:
First step:-
def load_data():

  print ("Please insert your data!")

  filename = input(prompt) ## Not really sure here how to link to the ('???.xlsx') ##

  load_data()

Second step:-
import pandas as pd

df = pd.read_excel('???.xlsx')

For your information too, the final .ipynb will save as .py and use Pyinstaller to create a simple window program. Thank you for your help!

A: import pandas as pd

from prompt_toolkit import prompt

filename = prompt('Enter your file name: ')

df = pd.read_excel(/YOUR_DIRECTORY_PATH/%s' % filename + '.xlsx')


text:
Q: Node.js Password Encryption Same As In Asp.Net I have created a wesite in asp.net and use ms-sql database to save the records. Now want to convert it in node.js application. And want to use same sql database. In asp.net application I have encrypt the password for registered user. Below is code.
   public static string CreateHash(string unHashed)
    {
        System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
        byte[] data = System.Text.Encoding.ASCII.GetBytes(unHashed);
        data = x.ComputeHash(data);
        return System.Text.Encoding.ASCII.GetString(data);
    }

    public static bool MatchHash(string HashData, string HashUser)
    {
        HashUser = CreateHash(HashUser);
        if (HashUser == HashData)
            return true;
        else
            return false;

    }

Now problem is that how I use same encryption in node.js. So when node application is ready old user can also make login. It only possible if node app also use same encryption that I have use in asp.net.
For node I have created all environment and use mssql module for database communication. Please help me fix that. Thanks!!

A: First of all MD5 shall no longer be used if you are serious about security.
Based on your comment and code, I fear there is a 'data loss' in the initial ASP.net code.
Let us have a look at CreateHash function again, I've added comments:
   public static string CreateHash(string unHashed)
    {
        System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();

        // Convert unHashed string to bytes using ASCII coding
        byte[] data = System.Text.Encoding.ASCII.GetBytes(unHashed);

        // Compute MD5 hash from bytes
        data = x.ComputeHash(data);

        // Decode MD5 resulting bytes as ASCII
        return System.Text.Encoding.ASCII.GetString(data);
    }

The last line confuses me, it is decoding bytes received from MD5 function as if they were ASCII, but that is incorrect assumption. And the resulting encoded string as you gave in comment contains lots of "?'s".
Next node.js code will do similar except encode the string using hex rather than ascii:
var crypto = require('crypto')

function createHash(data)  {
    return crypto.createHash('md5').update(data, 'ascii').digest('hex')
}

To emulate "bytes to ascii" you could try .digest('binary') instead of hex. If it does not give what you expect, then you have to make a separate 'conversion' step from hex to ascii. (I am not experienced enough to give you elegant solution to the later one)


text:
Q: Time dependency in the Hamiltonian in Schwartz's book on Quantum Field Theory On page 258 of his book on Quantum Field Theory and the Standard Model (in the comment between formulas 14.25 and 14.26) , Schwartz writes:

"We will also write $\hat{H} (t) = \int d^3 x \hat{\mathscr{H}}$, with the $t$ dependence of $\hat{H}(t)$ coming from how the field operators change with time in the full interacting theory".

My problem is that while I do understand that the full interacting operators have a very complex dependency over time, I don't think the Hamiltonian should. After all even in the most complex theories, if time doesn't appear explicitly, $\hat{H}$ is a constant of motion, which means that it should remain the same at all times. I don't see why there should be a time dependency. Maybe Schwartz was just trying to stress how the operators that make up the Hamiltonian are time dependent?

A: I think you are correct. The Hamiltonian in the Heisenberg picture is (essentially by definition) time independent, since it obviously commutes with itself.
I think that wether $\hat H$ is or is not time-independent seems to be irrelevant for the derivation of the path integral. Look at (14.27), where he uses
$$
\langle \Pi_j | \hat{\mathcal H}(\vec x,t(?)) |\Phi_j \rangle = \langle \Pi_j | \left ( \frac{1}{2} \Pi_j(\vec x)^2 + \mathcal V(\Phi_j(\vec x)) \right) |\Phi_j \rangle
$$
The RHS does clearly not depend on time, since $\Phi_j$ and $\Pi_j$ are time-independent classical fields.
In the path integral formalism one reinterprets $\Phi_j(\vec x) \equiv \Phi(t_j,\vec x)$ (and similarly for $\Pi$), where now $\Phi(t,\vec x)$  is the time dependent classical field. Similarly one can see
$$
\mathcal H(\vec x, t) \equiv \frac{1}{2} \Pi(\vec x, t)^2 + \mathcal V(\Phi(\vec x, t))
$$
as time-dependent. Note that the $\Phi_j$ and $\Pi_j$ can be anything, they are integrated over in the functional integral. In particular their "time-evolution" must not be the classical time-evolution given by the Poisson bracket with the Hamiltonian, so $\mathcal H(\vec x, t)$ as defined above is somehow truly time-dependent. This is probably what Schwartz had in mind.
I may be wrong on this and I am happy to be corrected.


text:
Q: PHP: 3 time periods with different pricing It's all about booking...
I've got 3 time periods:

Period 3 from 01.01.2014 to 29.04.2014 - Price 3 (per day)
Period 2 from 30.04.2014 to 14.06.2014 - Price 2 (per day)
Period 1 from 15.06.2014 to 21.09.2014 - Price 1 (per day)
Period 4 from 22.09.2014 to 29.04.2015 - Price 3 (per day)

I've already made a php calculation that calculates the booked days and pricing for each period. But I can't figure it out how to calculate between two periods.

For example:
Somebody books from 26.01.2014 to 25.04.2014 = 89 days * Price 1
But it gets really hard when somebody books from period 3 to period 1 for... I tried to separate the calculations:
   if ($check_in >= '2013-04-30' && $check_out <= '2014-09-21')
     {
    //Days and price calcs here
    // contains Period 2 and Period 1
     }

But it doesn't work well...
Do you have any ideas how to make the whole calculation to work perfectly?
I missed something really important.
Here is the structure:
Period 1
if($numberDays == 1)
{
$price = $price1_period1
}

if($numberDays >= 2 && $numberDays <= 3)
{

$price = $price2_period1 * $numberDays;
}

if($numberDays >= 4 && $numberDays <= 6)
{
$price = $price3_period1 * $numberDays;
}

if($numberDays >= 7 && $numberDays <= 14)
{
$price = $price4_period1 * $numberDays;
}

if($numberDays >= 15 && $numberDays <= 29)
{

$price = $price5_period1 * $numberDays;
}

if($numberDays >= 30)
{
$price = $price6_period1 * $numberDays;
}

It's the same for the other periods. Ex.: for period 2 the price for 6 days is $price3_period2.

A: You could generate a price for each day. Then loop from start date to end date and sum the dayprice to get the total price:
<?php
$oneDay = 24*3600;

$configs = array(
    array(
        'startTime' => strtotime('2014-01-01'),
        'endTime' => strtotime('2014-04-29'),
        'price' => 10
    ),
    array(
        'startTime' => strtotime('2014-04-30'),
        'endTime' => strtotime('2014-06-14'),
        'price' => 20
    ),
    array(
        'startTime' => strtotime('2014-06-15'),
        'endTime' => strtotime('2014-09-21'),
        'price' => 30
    ),
    array(
        'startTime' => strtotime('2014-09-22'),
        'endTime' => strtotime('2015-04-29'),
        'price' => 40
    ),
);

$prices = array();
foreach ($configs as $config)
{
    $time1 = $config['startTime'];
    $time2 = $config['endTime'];
    $price = $config['price'];

    while ($time1 <= $time2)
    {
        $prices[date('Y-m-d', $time1)] = $price;
        $time1 += $oneDay;
    }
}

/**
 * @param $checkIn in format YYYY-mm-dd
 * @param $checkOut in format YYYY-mm-dd
 */
function getTotalPrice($checkIn, $checkOut, $prices)
{
    $time1 = strtotime($checkIn);
    $time2 = strtotime($checkOut);

    $price = 0;
    while ($time1 <= $time2)
    {
        $time1 += 24 * 3600;
        $price += $prices[date('Y-m-d', $time1)];
    }

    return $price;
}

echo getTotalPrice('2014-01-04', '2014-01-09', $prices);

A: First things first, I assume $check_in and $check_out are strings that you get from some form, then you are comparing them with another string, any of them are dates.
What you can do is convert both $check_in and $check_out to Datetime and then do the comparison, example:
// Check In Date
$check_in_date = new Datetime($check_in);
$date_compare_in = new Datetime('2013-04-30');

$diff_in = $check_in_date->diff($date_compare_in);

// Check Out Date
$check_out_date = new Datetime($check_out);
$date_compare_out = new Datetime('2014-09-21');

$diff_out = $check_out_date->diff($date_compare_out);

Now $diff_in is a DateInterval object that you can check for the quantity of days, example, if the hours are greater than 0, the $check_in was later than the compare date, if is less than 0 the $check_in was before.
if($diff_in->h >= 0 and $diff_out->h <= 0){
// We are within this date range.
}

a DateInterval Object has the following structure:
DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 0
    [h] => 0
    [i] => 0
    [s] => 0
    [invert] => 0
    [days] => 0
)