text:
Q: Adding arrows to a Gantt chart? (To-the-point question at the end of the post)
I am using the following snippet to draw Gantt diagrams, taken from this source:
% GanttHeader setups some parameters for the rest of the diagram
% #1 Width of the diagram
% #2 Width of the space reserved for task numbers
% #3 Width of the space reserved for task names
% #4 Number of months in the diagram
% In addition to these parameters, the layout of the diagram is influenced
% by keys defined below, such as y, which changes the vertical scale
\def\GanttHeader#1#2#3#4{%
 \pgfmathparse{(#1-#2-#3)/#4}
 \tikzset{y=7mm, task number/.style={left, font=\bfseries},
     task description/.style={text width=#3,  right, draw=none,
           font=\sffamily, xshift=#2,
           minimum height=2em},
     gantt bar/.style={draw=black, fill=blue!30},
     help lines/.style={draw=black!30, dashed},
     x=\pgfmathresult pt
     }
  \def\totalmonths{#4}
  \node (Header) [task description] at (0,0) {\textbf{\large Tasks}};
  \begin{scope}[shift=($(Header.south east)$)]
    \foreach \x in {1,...,#4}
      \node[above] at (\x,0) {\footnotesize\x};
 \end{scope}
}

% This macro adds a task to the diagram
% #1 Number of the task
% #2 Task's name
% #3 Starting date of the task (month's number, can be non-integer)
% #4 Task's duration in months (can be non-integer)
\def\Task#1#2#3#4{%
\node[task number] at ($(Header.west) + (0, -#1)$) {#1};
\node[task description] at (0,-#1) {#2};
\begin{scope}[shift=($(Header.south east)$)]
  \draw (0,-#1) rectangle +(\totalmonths, 1);
  \foreach \x in {1,...,\totalmonths}
    \draw[help lines] (\x,-#1) -- +(0,1);
  \filldraw[gantt bar] ($(#3, -#1+0.2)$) rectangle +(#4,0.6);
\end{scope}
}

And the result is excellent, I would like to stick with this method rather than using pgfgantt or other packages with which I haven't had it so easy to create a Gantt diagram, here's an exaple of a generated diagram with that snippet in the preamble:
\begin{figure}
\begin{tikzpicture}
  \GanttHeader{textheight}{2ex}{7cm}{7}
  \Task{1}{First task}{0.5}{2.5}
  \Task{2}{Second task}{1.5}{2}
  \Task{3}{Another one}{3}{1}
  \Task{4}{Another one}{4}{1}
  \Task{5}{Yet another one}{5}{2}
\end{tikzpicture}
\caption{My figure's caption.}
\label{fig:gantt}
\end{figure}

The only thing I need is to add an arrow that shows predecessors for some tasks. Let's say an arrow going from the end of task 1, to the beginning of task 4. I have tried to set identifiers for the nodes defined in the \Task definition but I am quite a noob with Tikz.
Sample Gantt from the previously cited source :

How can I add arrows from the end of one rectangle to the start of another? Preferably stair-like arrows (only horizontal and vertical lines). Otherwise, a way to declare \nodes inside the Task definition in the desired places would help a lot!
Fully working example including needed packages:
\documentclass[10pt,a4paper]{article}
\usepackage[latin1]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}

\usepackage{geometry}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{graphicx}

% GanttHeader setups some parameters for the rest of the diagram
% #1 Width of the diagram
% #2 Width of the space reserved for task numbers
% #3 Width of the space reserved for task names
% #4 Number of months in the diagram
% In addition to these parameters, the layout of the diagram is influenced
% by keys defined below, such as y, which changes the vertical scale
\def\GanttHeader#1#2#3#4{%
 \pgfmathparse{(#1-#2-#3)/#4}
 \tikzset{y=7mm, task number/.style={left, font=\bfseries},
     task description/.style={text width=#3,  right, draw=none,
           font=\sffamily, xshift=#2,
           minimum height=2em},
     gantt bar/.style={draw=black, fill=blue!30},
     help lines/.style={draw=black!30, dashed},
     x=\pgfmathresult pt
     }
  \def\totalmonths{#4}
  \node (Header) [task description] at (0,0) {\textbf{\large Tasks}};
  \begin{scope}[shift=($(Header.south east)$)]
    \foreach \x in {1,...,#4}
      \node[above] at (\x,0) {\footnotesize\x};
 \end{scope}
}

% This macro adds a task to the diagram
% #1 Number of the task
% #2 Task's name
% #3 Starting date of the task (month's number, can be non-integer)
% #4 Task's duration in months (can be non-integer)
\def\Task#1#2#3#4{%
\node[task number] at ($(Header.west) + (0, -#1)$) {#1};
\node[task description] at (0,-#1) {#2};
\begin{scope}[shift=($(Header.south east)$)]
  \draw (0,-#1) rectangle +(\totalmonths, 1);
  \foreach \x in {1,...,\totalmonths}
    \draw[help lines] (\x,-#1) -- +(0,1);
  \filldraw[gantt bar] ($(#3, -#1+0.2)$) rectangle +(#4,0.6);
\end{scope}
}

\begin{document}
    \begin{figure}
    \begin{tikzpicture}
      \GanttHeader{\textwidth}{2ex}{4cm}{7}
      \Task{1}{First task}{0.5}{2.5}
      \Task{2}{Second task}{1.5}{2}
      \Task{3}{Another one}{3}{1}
      \Task{4}{Another one}{4}{1}
      \Task{5}{Yet another one}{5}{2}
    \end{tikzpicture}
    \caption{My figure's caption.}
    \label{fig:gantt}
    \end{figure}
\end{document}

A: If you modify \Task to the following you get named coordinates at the ends of each rectangle, called 1a,1b,2a etc. Na is at the left edge, Nb at the right edge.
\def\Task#1#2#3#4{%
\node[task number] at ($(Header.west) + (0, -#1)$) {#1};
\node[task description] at (0,-#1) {#2};
\begin{scope}[shift=($(Header.south east)$)]
  \draw (0,-#1) rectangle +(\totalmonths, 1);
  \foreach \x in {1,...,\totalmonths}
    \draw[help lines] (\x,-#1) -- +(0,1);
  \filldraw[gantt bar] ($(#3, -#1+0.2)$) rectangle +(#4,0.6);
  \coordinate (#1a) at (#3,-#1+0.5); % coordinate at left end of box
  \coordinate (#1b) at (#3+#4,-#1+0.5);  % coordinate at right end of box
\end{scope}
}

The two last lines in the scope are new.
I started by thinking only of the case where the boxes overlap, in which case the following macro lets you draw arrows easily.
\newcommand\arrowwhereboxesoverlap[3][]{%
  % #1: arrow style
  % #2: number of first task
  % #3: number of second task
  \path (#2b) ++(0.2,-0.5) coordinate (tmpa);
  \path (#3a) ++(-0.2,0) coordinate (tmpb);
  \draw [#1] (#2b) -| (tmpa) -| (tmpb) -- (#3a);
  }

Use e.g.
\startendarrow[thick,red,->]{1}{2}

to draw an arrow from the first to second box.
For the case where there is no overlap, such as from 2 to 4, the drawing is simpler (less corners), so you can do something like
\draw [blue,dashed,very thick,->] (2b) -- ++ (0.2,0) |- (4a);

This can of course also be wrapped in a macro, if desired.
Complete example:
\documentclass[10pt,a4paper]{article}
\usepackage[latin1]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}

\usepackage{geometry}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{graphicx}

% GanttHeader setups some parameters for the rest of the diagram
% #1 Width of the diagram
% #2 Width of the space reserved for task numbers
% #3 Width of the space reserved for task names
% #4 Number of months in the diagram
% In addition to these parameters, the layout of the diagram is influenced
% by keys defined below, such as y, which changes the vertical scale
\def\GanttHeader#1#2#3#4{%
 \pgfmathparse{(#1-#2-#3)/#4}
 \tikzset{y=7mm, task number/.style={left, font=\bfseries},
     task description/.style={text width=#3,  right, draw=none,
           font=\sffamily, xshift=#2,
           minimum height=2em},
     gantt bar/.style={draw=black, fill=blue!30},
     help lines/.style={draw=black!30, dashed},
     x=\pgfmathresult pt
     }
  \def\totalmonths{#4}
  \node (Header) [task description] at (0,0) {\textbf{\large Tasks}};
  \begin{scope}[shift=($(Header.south east)$)]
    \foreach \x in {1,...,#4}
      \node[above] at (\x,0) {\footnotesize\x};
 \end{scope}
}

% This macro adds a task to the diagram
% #1 Number of the task
% #2 Task's name
% #3 Starting date of the task (month's number, can be non-integer)
% #4 Task's duration in months (can be non-integer)
\def\Task#1#2#3#4{%
\node[task number] at ($(Header.west) + (0, -#1)$) {#1};
\node[task description] at (0,-#1) {#2};
\begin{scope}[shift=($(Header.south east)$)]
  \draw (0,-#1) rectangle +(\totalmonths, 1);
  \foreach \x in {1,...,\totalmonths}
    \draw[help lines] (\x,-#1) -- +(0,1);
  \filldraw[gantt bar] ($(#3, -#1+0.2)$) rectangle +(#4,0.6);
  \coordinate (#1a) at (#3,-#1+0.5);
  \coordinate (#1b) at (#3+#4,-#1+0.5);
\end{scope}
}

\newcommand\arrowwhereboxesoverlap[3][]{%
  % #1: arrow style
  % #2: number of first task
  % #3: number of second task
  \path (#2b) ++(0.2,-0.5) coordinate (tmpa);
  \path (#3a) ++(-0.2,0) coordinate (tmpb);
  \draw [#1] (#2b) -| (tmpa) -| (tmpb) -- (#3a);
  }

\begin{document}
    \begin{figure}
    \begin{tikzpicture}
      \GanttHeader{\textwidth}{2ex}{4cm}{7}
      \Task{1}{First task}{0.5}{2.5}
      \Task{2}{Second task}{1.5}{2}
      \Task{3}{Another one}{3}{1}
      \Task{4}{Another one}{4}{1}
      \Task{5}{Yet another one}{5}{2}

      \arrowwhereboxesoverlap[thick,red,->]{1}{2}
      \draw [blue,dashed,very thick,->] (2b) -- ++ (0.2,0) |- (4a);
\end{tikzpicture}
    \caption{My figure's caption.}
    \label{fig:gantt}
    \end{figure}
\end{document}

A: How do you feel about this? I'm using the pgfgantt package for the Gantt diagrams and pdflscape to get the landscape mode
\documentclass{report}

\usepackage{pgfgantt}
\usepackage{pdflscape}

\definecolor{barblue}{RGB}{153,204,254} %up to 255

\begin{document}
\pagestyle{empty}
\begin{landscape}
    \begin{figure}
    \centering
        \begin{ganttchart}[%Specs
            y unit title=0.4cm,
            y unit chart=0.5cm,
            canvas/.style={fill=none, draw=black, line width=.75pt},
            vgrid,
            title label anchor/.style={below=-1.6ex},
            title left shift=.05,
            title right shift=-.05,
            title height=1,
            title/.style={fill=none},
            title label font=\bfseries,
            bar/.style={fill=barblue},
            incomplete/.style={fill=white},
            progress label text={},
            bar height=0.7,
            group right shift=0,
            group top shift=.6,
            group height=.3,
            group peaks height=.2]{1}{36}

            %labels
            \gantttitle{2014}{36}\\
            \gantttitle{Jan}{3}
            \gantttitle{Feb}{3}
            \gantttitle{Mar}{3}
            \gantttitle{Apr}{3}
            \gantttitle{May}{3}
            \gantttitle{Jun}{3}
            \gantttitle{Jul}{3}
            \gantttitle{Aug}{3}
            \gantttitle{Set}{3}
            \gantttitle{Oct}{3}
            \gantttitle{Nov}{3}
            \gantttitle{Dec}{3}\\

            % Parameter Selection
            \ganttgroup{Group 1}{2}{18}\\ %elem0
            \ganttbar[progress=0]{Bar}{2}{18}\\
            \ganttmilestone{Mileston}{18}\\\\

            % Testing equipment
            \ganttgroup{Group 2}{2}{18}\\ %elem0
            \ganttbar[progress=0]{Bar}{2}{18}\\
            \ganttmilestone{Milestone}{18}\\\\

            % Testing
            \ganttgroup{Group 3}{19}{35}\\
            \ganttbar[progress=0]{Bar}{19}{35}\\
            \ganttbar[progress=0]{Bar}{19}{35}\\
            \ganttmilestone{Milestone}{27}\\
            \ganttmilestone{Milestone}{35}\\

            % Algorithm Development
            \ganttgroup{Group 4}{28}{35}\\
            \ganttbar[progress=0]{Bar}{28}{35} \\

            %relations
            \ganttlink{elem2}{elem6}
            \ganttlink{elem5}{elem6}
            \ganttlink{elem9}{elem11}

        \end{ganttchart}
    \caption{Gantt diagram for the first year (2014)}
    \label{fig:Gantt2014}
    \end{figure}
\end{landscape}

\end{document}


text:
Q: When to use ChangeNotifier? In the flutter sample explaining how to use the Provider package, there are two models, Catalog and Model.
For the Catalog model, ChangeNotifier is not used, but for the Cart model it's used.
Cart model
Catalog model
Why is ChangeNotifier used for the Cart model and not Catalog model?
My thinking is that the Cart model depends on changes outside (in the catalog model).
The catalog model is hard-coded and hence no need to notify anyone of changes.
Is my thinking correct?
PS: this is my first app and I'm a complete noob when it comes to state management.

A: Yes you are correct.
The ChangeNotifier as the name suggests stands for notifying the changes. As you can see the function notifyListners() called at catalog and add functions are used to notify the listeners subscribed to the notifier using Consumer widget or using Consumer.of(). So as to when to use ChangeNotifiers ? You can use then whenever there are state changes in a model dependant upon some other view deep in the tree that you cannot get to them directly.

So from this widget tree you can clearly see that MyCatalog and MyCart are totally different from each other in the UI but are dependant logically. i.e. you need to notify the cart widget whenever user changes the MyListItem.
One possible solution for this scenario is that using global variables (sort of) or a variable that is at top of MyCatalog and MyCart in the tree. So that when MyCatalog changes the state the ChangeNotifier at the top of tree would know of the change and notify the MyCart that is listening to the changes.
ChangeNotifiers are used in such scenario where we need to lift the state up as the documentation says here or you could use it when you need the values deep in the tree that you cannot directly give. In case of react we call it props drilling. Giving the state to the child widgets in the tree.
We could acheive this without using providers if I am not wrong. Making MyApp a statefull widget and passing the state to MyCatalog and MyCart widget. so that the renders would know to get the state from. But what if you added another widget that depends on the state deep in the tree. Would you pass the state down ? or Would you use the Provider ? all depends upon you and your application.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как сделать обновление страницы после нажатия кнопки удаления товара с корзины? Есть копка удаления, через onclick происходит удаление
<button type="button" class="lii" name="del" onclick="window.location.href='/cart?id='+<?php echo $value->id ?>"> удалить</button>

Сделал скрипт на обновление страницы
<script type="text/javascript">
$(".lii").click(function func(){
    location.reload();
    return true;
});
setTimeout(func, 1000);

Ну и нифига не работает. Наверно из-за onclick. Что посоветуете ? Просто при удалении товар висит пока не удалю 2-рой товар или не перегружу страницу. Удаление товара с корзины jQuery и Ajax я еще не умею.

A: Если правильно тебя понял.
Измени свой код на вот такой
Убираешь онклик, а создаешь дата атрибут (какой хочешь, в данном случае id)
<button type="button" class="lii" name="del" data-id="<?=$value->id;?>">удалить</button>

А скрипт меняешь вот на такой. На элемент с классом .lii навешивается отслеживание события click, после чего происходит аякс запрос на твою страничку /cart c GET / id
 $('.lii').on('click',function(){
        $.ajax({
           url:'/cart',
           data:{id:$(this).data('id')},
           success:function(){
              location.reload();
           }
        });
    });

После выполнения аякса - страница перезагрузится


text:
Q: Unnesting sf dataframe with list-column containing lubridate intervals I start with an sf dataframe, called polygon_history, with the following columns:
polygon_id,valid_period,geometry

where valid_period is an interval between two dates created using lubridate package.
I subdivided valid_period into smaller intervals and combine them in a list by obtaining the intersection of the valid_period with a list of date ranges (sectionized_periods) that I am interested in analyzing separately, with the code below:
sectionized_periods
[1] 2021-09-01 UTC--2021-09-07 UTC 2021-09-07 UTC--2021-10-10 UTC 2021-10-10 UTC--2021-10-24 UTC 2021-10-24 UTC--2021-11-30 UTC

polygon_history %>%
  rowwise %>%
  mutate(period_section = list(c(lubridate::intersect(valid_period,sectionized_periods))))

Now my table has the following columns:
polygon_id, valid_period, period_sections, geometry

where period_sections is a list-column; and every row is a list of [lubridate] intervals.
Example row in period_sections:
polygon_history$period_section[1]
[[1]]
[1] 2021-09-01 UTC--2021-09-07 UTC 2021-09-07 UTC--2021-10-10 UTC 2021-10-10 UTC--2021-10-24 UTC 2021-10-24 UTC--2021-11-30 UTC

I am trying to unnest this table based on the period_section list-column in order to have a row for each element of the list (each interval), however when I run the code below, I only get numeric values in period_section instead of the intervals. I believe this numeric value represents the duration of the interval, but I need to have the interval instead.
polygon_history <- polygon_history %>%
+     rowwise %>%
+     mutate(PERIOD_SECTION = list(c(lubridate::intersect(VALID_PERIOD,sectionized_periods)))) %>%
+     unnest(PERIOD_SECTION) %>%
+     sf::st_sf()

polygon_history$PERIOD_SECTION
An object of class "vctrs:::common_class_fallback"
 [1]  518400 2851200 1209600 3196800  518400 2851200 1209600 3196800  518400 2851200 1209600 3196800  518400 2851200 1209600 3196800  518400 2851200
[19] 1209600

Appreciate any insights on how to solve this. Thanks!

A: I was able to do what I needed using unchop.
 polygon_history <- polygon_history %>%
    +     rowwise %>%
    +     mutate(PERIOD_SECTION = list(c(lubridate::intersect(VALID_PERIOD,sectionized_periods)))) %>%
    +     unchop(PERIOD_SECTION) %>%
    +     sf::st_sf()


text:
Q: How to Generate Monthly and Yearly Recuring Invoice in Laravel I am doing an invoice application in Laravel. In my application, users can create recurring profiles. Those profiles are automatically generated invoices for monthly or yearly based on invoice date. I want to know how to do this task, can anybody give suggestions?
What I Do: When a user creates a recurring profile, I save the next recurring date in recurring profile table. Every time I generate an invoice based on next recurring date. In this process I have following problem, user deactivate the profile and again activate after 2 months, the invoice cannot generated.

A: Open kernal.php file in app->console folder
protected function schedule(Schedule $schedule)
    {
        $schedule->call(function () {
           //code
        })->monthly();

        $schedule->call(function () {
           //code
        })->yearly();

        //this following code will execute the task on last day of every month
        $schedule->call(function () {
           //code
        })->when(function () {
                return \Carbon\Carbon::now()->endOfMonth()->isToday();
                });
    }

In the schedule method, write your code inside anonymous function and use monthly() and yearly() function to trigger the method every month and year automatically.
More information here https://laravel.com/docs/5.4/scheduling#schedule-frequency-options


text:
Q: When to use MessageChannel HTML5 feature? When we need to use messageChannel? I usually know websocket protocol used when there is need full duplex and low latency.. etc.  Also Websocket used during client server communication.  Can  I use MessageChannel instead of web-socket? My client are using chrome so less worried about other browsers.  Does it satisfy full duplex and low latency requirement?
Need to know messagechannel support low latency and full duplex feature


text:
Q: Trouble Repopulating WijGrid Using Custom Filter I'm having some trouble updating a wijgrid using a json result returned from an ajax call.  The wijgrid does not seem to redraw.  Here is the relevent javascript/jQuery:
$(function () {
    var datasource = new wijdatasource({
        data: [{"Id":1,"Name":"Sidney","Type":"Engineer"},{"Id":4,"Name":"Mavis","Type":"Student"},{"Id":5,"Name":"Betty","Type":"Student"},{"Id":80,"Name":"Taylor","Type":"Student"},{"Id":92,"Name":"Graham","Type":"Student"},{"Id":94,"Name":"Belle","Type":"Student"},{"Id":100,"Name":"Terrence","Type":"Student"},{"Id":106,"Name":"William","Type":"Student"},{"Id":108,"Name":"Synthia","Type":"Student"},{"Id":109,"Name":"Lucious","Type":"Customer"},{"Id":116,"Name":"Leonard","Type":"Student"},{"Id":119,"Name":"Katy","Type":"Student"},{"Id":122,"Name":"Sarah","Type":"Student"},{"Id":127,"Name":"Amy","Type":"Student"},{"Id":178,"Name":"Carl","Type":"Student"}],
        reader: new wijarrayreader([
            { name: 'Id', mapping: 'Id' },
            { name: 'Name', mapping: 'Name' },
            { name: 'Type', mapping: 'Type' }
        ])
    });

    $('#ClientTable').wijgrid({
        allowSorting: true,
        allowPaging: true,
        pageSize: 10,
        data: datasource,
        columns: [
            { visible: false },
            {
                cellFormatter: function (args) {
                    var wg = $.wijmo.wijgrid,
                    row = args.row;

                    if ((row.type & wg.rowType.data) && (row.state === wg.renderState.rendering)) {
                        args.$container.append($('' + row.data.Name + ''));
                        return true;
                    }
                }
            },
            {}
        ]
    });

    $('#pageSize').bind('change', function (e) {
        $('#ClientTable').wijgrid('option', 'pageSize', parseInt($(e.target).val()));
    });

    $('#filterBy').keyup(function (e) {
        var filter = $('#filterBy').val();
        if (typeof filter == 'string' && filter.length > 1) {
            $.ajax({
                url: '/Home/MemberAsyncResults',
                async: true,
                traditional: true,
                type: 'GET',
                data:
                {
                    filter: filter
                },
                success: function (response) {
                    //                            datasource.data = response;
                    //                            datasource.read();
                    datasource.load(response, false);
                    $('#ClientTable').wijgrid('ensureControl', true);
                    $('#ClientTable').wijgrid('doRefresh');
                },
                error: function (e) {
                    var breakOnThisLine = 1;
                }
            });
        }
    });
});

Also, here is the relevent html:
Page Size
<select id="pageSize">
    <option>10</option>
    <option>25</option>
    <option>50</option>
    <option>100</option>
</select>
Filter By
<input type="text" id="filterBy" />

When a breakpoint is set inside of the success method of the ajax call, the correct data is returned from the server.  However, the code for repopulating the datasource of the wijgrid control, or for rerendering the control must not be right...
On a related note, I wasn't really sure what the name or the mapping properties of the wijarrayreader are for.  I think the wijarrayreader is set up correctly, but I only made an educated guess based on some examples.
Many thanks in advance!

A: Try setting ensureControl option of wijgrid in the loaded event of wijdatasource, or set it when initializing wijgrid :
$('#ClientTable').wijgrid({
    allowSorting: true,
    allowPaging: true,
    pageSize: 10,
    ensureControl : true
});

As an alternative, instead of using the $ajax call, I would suggest you to use wijhttpproxy widget which is helpful in these scenarios. Please refer to the following link for more info : http://wijmo.com/wiki/index.php/Datasource#proxy
Please take a look at the code below :
$(document).ready(function () {

        var superPanelRefreshed = false;
        var proxy = new wijhttpproxy({
            url: "http://ws.geonames.org/searchJSON",
            dataType: "jsonp",
            data: {
                featureClass: "P",
                style: "full",
                maxRows: 12,
                name_startsWith: 'ab'
            },
            key: 'geonames'
        });
        var myReader = new wijarrayreader([{
            name: 'label',
            mapping: function (item) {
                return item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName
            }
        }, {
            name: 'value',
            mapping: 'name'
        }, {
            name: 'selected',
            defaultValue: false
        }]);

        var input = $('#testinput');

        datasource = new wijdatasource({
            reader: myReader,
            proxy: proxy,
            loading: function () {

            },
            loaded: function (data) {

            }
        });

        $("#grid").wijgrid({
            data: datasource,
            ensureControl: true
        });

        datasource.load();
    });

    function loadRemoteData() {
        datasource.proxy.options.data.name_startsWith = $('#testinput').val();
        datasource.load();
    }


text:
Q: Swift Core Data many-to-many doesn't save I have a many-to-many relationship for buddy-conversation. I try to save a conversation for a buddy like this:
let conversations = buddy.valueForKeyPath("conversations") as? NSMutableSet
            conversations?.addObject(newConversation)
CoreData.sharedInstance.saveContext()

My log tells me, the buddy has a conversation, but the next time i I run the App, the buddy doesn't have a conversation an it creates a new one.
I tried this
@NSManaged func addConversationObject(conversation: Conversation)

but I get an error every time

A: I'm interpreting this as being based on two different entities, buddies and conversations, where a buddy can be in multiple conversations and each conversation can have multiple buddies participating.  If so, if the conversation is a new one, you'd create the record for it and link the buddy through whatever property you've defined to link them (let's say a buddy could be participatingIn a conversation).  then, to create the conversation and link the buddy (say buddy1) you'd use:
guard let newConversation = NSEntityDescription.insertNewObject(forEntityName: "Conversation", into: context) as? Conversation else
{...damage control for the CoreData failure...}

buddy1.participatingIn = newConversation

At that point, you'd also want to set whatever other values you have in the Conversation record.  On the other hand, if you're adding buddy1 to an existing conversation, you'd have or retrieve that conversation (say as conversation1) and link buddy1 in with:
buddy1.participatingIn = conversation1

I hope that fits your design / helps.


text:
Q: ASP.net Website works fine when published but returns HTTP error 503 when debugging with VS I've been using VS 2012 for a while now and haven't had many issues with publishing or debugging my site.
But just today I tried publishing my site to a new port on a local server and after that whenever I tried debugging my site using "Local ISS Web Server" or "Visual studio development server" My page would return:
Firefox:
Unable to connect

Firefox can't establish a connection to the server at localhost:59617.

The site could be temporarily unavailable or too busy. Try again in a few moments.
If you are unable to load any pages, check your computer's network connection.
If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the Web.

Chromium:
This page isn't working

localhost is currently unable to handle this request.
HTTP ERROR 503

The strange thing is that I can still publish the site to our server or even locally and have it work. It only doesn't work when debugging. I've tried restarting my computer and trying different ports but haven't had any luck.
I even tried modifying my host file like this guy did: http://www.grumpydev.com/2009/03/12/strange-problem-unable-to-connect-to-the-aspnet-webserver-on-localhost/comment-page-1/#comment-73
but still had no luck.
Any suggestions?

A: Of course I find the answer right after I post the question:
https://stackoverflow.com/a/6661177/5428728
I had to go to the root of my project folder and delete the app_offline.htm file.


text:
Q: How to fetch the row number of a Google Spread Sheet via Google Apps Script? I have a google script I am using and I was wanting to insert the current row I am working with into a value which will be re added into a formula I set back in the spreadsheet. I want to do this in case someone resubmits the same data, so they are emailed the changes. At the moment this script is just a proof of concept for me, so I can then go on and code the entire process.
The problem I am having with the script is with the value currentRow. It seems to get the value of the first pass and then does not change it, which is problematic when you have more than one entry to process.
I use the value currentRow in the variable RESEND_EMAIL, so it can generate a formula which looks to see if the two columns are alike (I am going to use the date time stamp and copy it in just the first time to column D (also known as var resend[4]).
This way I can set the script to run automatically and check if this column is set as "Yes", in which case it will send and email again and then change the a value (shown here as email address - but I will use the timestamp instead) so that the formula RESEND_EMAIL changes resend back to "No".
How do I always ger the correct row Number in the value currentRow?
// This constant is written in column C for rows for which an email
// has been sent successfully.
var EMAIL_SENT = "EMAIL_SENT";

function sendEmails2() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 2;   // Number of rows to process
  // Fetch the range of cells A2:B3
  var dataRange = sheet.getRange(startRow, 1, numRows, 6)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var emailAddress = row[0];  // First column
    var message = row[1];       // Second column
    var emailSent = row[2];     // Third column
    var resend = row[4];
    var extension = row [5];
    var currentRow = sheet.getActiveRange().getRow();
    var RESEND_EMAIL = "=IF(A"+ currentRow +"=D" + currentRow +",\"No\",\"Yes\")";

    if (emailSent != EMAIL_SENT) {  // Prevents sending duplicates
      var subject = "Sending emails from a Spreadsheet";
      MailApp.sendEmail(emailAddress, subject, message);
      sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
      sheet.getRange(startRow + i, 5).setFormula(RESEND_EMAIL);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
    if (resend == "Yes") {  // Prevents sending duplicates
      var subject = "Sending emails from a Spreadsheet";
      message = message + " " + extension;
      MailApp.sendEmail(emailAddress, subject, message);
      sheet.getRange(startRow + i, 4).setValue(emailAddress);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }

  }
}

A: As shown in your code i variable value becomes the current row.
...
var currentRow = startRow + i;
...


text:
Q: Kendo MVC Fluent filterable option how can I exclude particular coloumns from beeing filterable in the kendo grid?
.Navigatable()
          .Scrollable(a => a.Height("auto"))
          .Filterable(f => { f.Mode(GridFilterMode.Row);
                               f.Extra(false);

          })

I do not find anythign for the server side (fluent).

A: ..okay I just figured it out by myself in the meantime:
columns.Bound(p => p.value).Filterable(**true/false**);

is what I was looking for.
But now I am stuck at another point: My custom filter options do not work.
I got just same result as default:
.Filterable(f =>  f.Mode(GridFilterMode.Row)
                            .Extra(false)
                            .Operators(operators => operators
                                .ForDate(date => date.Clear()
                                    .IsGreaterThanOrEqualTo("Ab")
                                    .IsLessThanOrEqualTo("Bis")
                                )
                                .ForString(str => str.Clear()
                                    .Contains("Beinhaltet")
                                )
                             )
         )

Any idea on that?


text:
Q: Google maps not rendering properly within an iframe in ie8 because of hidden div I am building a widget and using a iframe to insert some Google maps code into a page and I am encountering a problems in ie8 which are not happening in any other browsers (ff, safari, chrome ie9).
Here are the issues:
The map is not rendering correctly when going to the page from a iframe - it seems to shift to the left.  This does not happen if you go to the page directly (rather than from a iframe).
I've seen this Google Maps does not render correctly in IE8 within iframe nyromodal layer but I'm not really sure how to do this.
My iframe which calls the page is:

                  <iframe frameBorder="0" style="Background-color: Transparent;" allowtransparency="True" width=" 790" height=" 486" scrolling="no" src="http://localhost:7310/widgets/googlemaps/<%= Model.Product.ManufacturersPartNo%>">

Here is my code in full:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Maps.Master" Inherits="System.Web.Mvc.ViewPage<WidgetView>" %>

<%@ Import Namespace="WidgetData" %>
<asp:Content ID="Content3" ContentPlaceHolderID="TitleContent" runat="server">
    <%= Html.WidgetTitle(Model) %>
</asp:Content>
<asp:Content ID="WidgetStyle" ContentPlaceHolderID="StyleContent" runat="server">
    <%= Html.WidgetStyle(Model) %>
    <%= Html.WidgetScripts(Model) %>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>

</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

                            Please enter your Postcode
                            <input id="enterPostCode" type="text" />

                            Distance from your location
                            <select id="distanceMiles" name="distanceMiles">
                                <option value=""></option>
                                <option value="5">5 miles</option>
                                <option value="10">10 miles</option>
                                <option value="15">15 miles</option>
                                <option value="20">20 miles</option>
                            </select>
                            <input id="enterMiles" type="hidden" />

        <%--    --%>

        <%--  <%= Html.GoogleMapsScriptsReturnPostcodeData(Model)%>--%>

</asp:Content>

I am using MVC3.
Any help will be much appreciated I've been on this all day and no idea where to go with it.

A: After a few frustrating days I've found out what the problem is:
As my iFrame was loading in a hidden div the map was resizing to fit the hidden div and therefore getting confused.
Thedre is quite a bit of documentation on google maps not working properley in hidden divs and how to overcome it.
The way that I went for was not to load the src of the iframe untill the click event which showed the div which was hidden was clicked and this fixed it.
Please see the code below:
 $('.divDealerLocatorStep').hide();
  $('.thisDealerTab').click(function (e) {
                $('.divFirstStep').hide();
                $('.divWheretobuyStep').hide();
                $('.divUpgradeOptionStep').hide();
                $('.divDealerLocatorStep').show();
                //here i need to put something which will resize gmap - instead i am just loading the iframe on click and not before
                var iframe = $("#mapLoad");
                iframe.attr("src", "http://localhost:7310/widgets/googlemaps/<%= Model.Product.ManufacturersPartNo%>");
            });

I then converted ny maps to v3 adn decided not to use a iframe but still had a hidden div  so to overcome the same problem I had to add the following:
at the bottom of teh google maps code underneath:
google.maps.event.addDomListener(window, 'load', initialize);

I put this:
google.maps.event.trigger(map, 'resize');

and in the jquery which unhid the hidden dive:
 $(".divDealerLocatorStep").css("display", "block");
                initialize();

and the css:
.divDealerLocatorStep {
            display: none;
        }

Hope this helps others


text:
Q: scipy package import error I have installed scipy on Mac. It imports perfectly fine, but is missing some libraries.
When I try loading diags it throws error:
from scipy.sparse import diags
Traceback (most recent call last):
File "<stdin>", line 1, in <module> ImportError: cannot import name diags

The scipy version that I have is 0.10.1. How can I upgrade this?

A: You can upgrade scipy using pip:
pip install scipy --upgrade


text:
Q: Converting .tex to .docx file with a certain document class using pandoc Extreme TeX and **LaTeX* newcomer, I am trying to convert a .tex to a .docx (Word) document.
I am using the pandoc command line utility and got so far as converting the document, i.e., by doing something like pandoc tex-file.tex -s -o word-file.docx. That worked, but didn't seem to recognize the document class, which is a file in the same directory with a name like class.cls.
When I (clumsily) tried something like pandoc tex-file.tex -s -o --variable documentclass='class-cls' word-file.docx, an error was returned: openFile: does not exist (No such file or directory).
Can you point me in the right direction for converting a .tex to a .docx file with a certain document class using pandoc (or, if recommended, another tool)?


text:
Q: Why dont parent classes are not automatically destruct in php? I am trying to dig some PHP OOP features.
Here is my sample codes
<?php

abstract class Animal{
    public $name;

    public function __construct($name)
    {
        $this->name = $name;
        echo 'animal instruct'  . "\n";
    }
    public function eat(){
        return $this->name . ' is eating food.'  . "\n";
    }

    public function __destruct()
    {
        echo "animal destruct"  . "\n";
    }
}

class Dog extends Animal{
    public $name;
    public function __construct($name)
    {
        parent::__construct($name);
    }

    public function bark(){
        return $this->name . ' is barking.'  . "\n";
    }

    public function __destruct()
    {
        echo "dog destruct"  . "\n";
        parent::__destruct();

    }
}

class Cat extends Animal{
    public $name;
    public function __construct($name)
    {
        parent::__construct($name);
    }

    public function meow(){
        return $this->name . ' is meowing.'  . "\n";
    }

    public function __destruct()
    {
        parent::__destruct();
        echo "cat destruct" . "\n";
    }
}

$bobby = new Dog('Bobby');
echo $bobby->bark();
echo $bobby->eat();

$cat = new Cat("cat");
echo $cat->meow();
echo $cat->eat();
?>

When I run the code , the output is as follow
animal instruct
Bobby is barking.
Bobby is eating food.
animal instruct
cat is meowing.
cat is eating food.
animal destruct
cat destruct
dog destruct
animal destruct

When I remove this code from child classes

parent::__destruct();

the parent class is not automatically destruct itself.
What I want to know is Do we need to destruct parent class in every child classes for some free memory space or PHP will do it itself?

A: There are a few things to unpick here:

*

*Once an object in PHP has no more references to it, the memory it uses will be freed. If it has the last reference to some other object, that object will also be freed, and so on. This is automatic, and largely invisible; you don't need to write any code in your class to make it happen, nor can you stop it happening, other than by keeping a reference to the object somewhere. (If there are circular references, they may not be freed immediately, but PHP will periodically check and free those as well.)

*When the object is freed, PHP will run a method called __destruct, if it exists. This method isn't responsible for freeing the object, it's just happening as an effect of PHP deciding to do so. It gives you a chance to do extra cleanup or checks as well as what PHP does automatically.

*When you inherit from a class, that inheritance is part of the definition of the object; creating an instance of the sub-class doesn't actually create two objects. So in your example, $bobby is an instance of Dog, and the memory that needs to be freed is the memory taken by that instance; there is no extra instance of Animal "inside" it.

*When you define any method in both a parent class and a sub-class, the definition in the sub-class hides the one in the parent class. If you add a definition of eat() in class Dog, it will be called instead of the definition in Animal. The same is true with "magic" methods like __destruct: when $bobby is freed, the engine will call $bobby->__destruct(), and find the definition in class Dog instead of the one in class Animal. By calling parent::__destruct() inside the definition of Dog, you are explicitly asking to run the "hidden" definition.

So the answer to your final question:

Do we need to destruct parent class in every child classes for some free memory space or PHP will do it itself?

Is No. PHP will free the memory space of the object regardless of how you define the object; and there is no separate "parent memory" to free. It will additionally run the __destruct method on that object if one exists; that method will be resolved using the normal rules: look on sub-class first, else parent, and so on.

A: From the manual:

The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

So it says, the parent destructor won't be called automatically, as same is for the parent constructor.
If your parent class needs to do deconstruct work, you have to call it expliticly.
Short answer
The destructor will only be called on instances.


text:
Q: successful fetch of api but no response I am fetching a url using fetch in react redux application which looks like:
fetch(url, {
            mode: 'no-cors',
            method: method || null,
            headers: headers || null,
            body: form || null,
            }).then(function(response) {
                console.log(response.status)
                console.log("response");
                console.log(response);
            }).then(function(data){
                console.log(data)
                console.log(data)
            })

Strange this is happening. When I call the url it is called and the response is 200. When I see in the console for response I am getting proper response from the url but response.status is giving me 0 and my response looks weird like:
body: null
 ok: false and so on...
I don't know what is wrong in here because my api is called and even I am getting response but I am unable to catch the response.
Is it I have to wait for api to complete and process further? Like waiting for fetch if yes then how can I do it?

A: There is no HTTP status code 0. What you see is a 0 returned by the library that you are using. You will have to check the documentation for that.

A: Try sending mode: 'cors'
in no-cors mode you will gat an opaque response


text:
Q: Count the duplicate values on multiple array and sort it to highest I have a target where I have this DUPLICATE checker with COUNT for multiple arrays. As we can see. Any suggestions on how I make this work? Thank you and have a nice day.
DATA:

id
value

1
[5,6,8,4,2]

2
[2,3,4,1,8]

3
[9,3,2,1,10]

Normal result:

number
count

1
2

2
3

3
2

4
2

5
1

6
1

7
0

8
2

9
1

10
1

This is my target result with sorting (Highest count):

number
count

2
3

1
2

3
2

4
2

8
2

5
1

6
1

10
1

9
1


text:
Q: Provider not found when injecting in Angular unit tests? I have a service that receives a class in its constructor. I've mocked the injected service and added it as a provider both in the test module and overridden in the test component, but I'm still getting NullInjectorError: No provider for UserService!
Here's the test - please rest assured that I've imported everything that I need:
describe('DataConsentComponent', () => {
  let component: DataConsentComponent;
  let fixture: ComponentFixture<DataConsentComponent>;

  class UserMock extends User {

    constructor () {
      super();
    }
  }

  class UserServiceMock {

    constructor () {

    }
  }

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [DataConsentComponent],
      providers: [
        { provide: 'UserService', useClass: UserServiceMock },
        { provide: 'User', useClass: UserMock }
      ]
    });

    TestBed.overrideComponent(
      DataConsentComponent,
      {
        set: {
          providers: [
            { provide: 'UserService', useClass: UserServiceMock },
            { provide: 'User', useClass: UserMock }
          ]
        }
      });

    fixture = TestBed.createComponent(DataConsentComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  }));

  it('should create', inject([UserService], () => {
    expect(component).toBeTruthy();
  }));
});

And the class being tested:
import { Component, OnInit } from '@angular/core';
import { UserService } from '@team/user.service';
import { User } from '@team/user.model';
import { GDPR_IS_ACTIVE } from '../../config/constants';

@Component({
  selector: 'app-data-consent',
  template: ''
})

export class DataConsentComponent {

  public User: User;

  constructor(private UserService: UserService){
    this.UserService.UserSource$.subscribe(
      (User: ETMUser) => {
        this.User = User;
    });
  }

  getGDPRIsActive(): boolean {
    return GDPR_IS_ACTIVE() || false;
  }

  getIfUserIsClient() {
    return this.UserService.getUserIsClient();
  }

  getIfUserIsEmployee() {
    return this.UserService.getUserIsEmployee();
  }

  showCandidateGDPRInformation (candidate) {
    return true;
  }

  getNavigateLinkLabel(candidate):any {
    return 'View';
  }

  shouldShowNavigate(candidate) {
    return true;
  }

  isSelectable(candidate) {
    return true;
  }

}

If there's a better way to get that service in, I'm more than willing to refactor.

A: Removing the single quotes around the service names in the providers array in your unit test should do the trick.
You want the TestBed to provide them as classes/objects, not strings, or tokens.


text:
Q: Why can't I attach to docker container of mariadb? Why can't I attach to docker container of mariadb?
$ docker run --name mariadbtest -e MYSQL_ROOT_PASSWORD=mypass -d mariadb/server:10.1
<SKIPPED>
78cadba14946919a3d62e1c616e39e76508107d24c6c1b93da534d3a3eb09e2d

$ docker attach 78cadba14946
<HANG>

How to see parameters of this container?

Also I can't ssh to the container
$ docker inspect -f "{{ .NetworkSettings.IPAddress }}" mariadbtest
172.17.0.2

$ ssh 172.17.0.2
<HANG>

A: docker attach <container> attaches your terminal stream to the container stdout/stderr. If the container sends nothing to these streams - you will see nothing after attaching to it. Try executing some statement in the database and see if anything appears.
As for ssh, normally containers do not have ssh in it. Use docker exec -it <container> sh instead.


text:
Q: Missing type map configuration or unsupported mapping after auto code generation on the client I have a simple class:
[DataContract]
public class ClaimView
{
    [DataMember]
    public string Type { get; set; }

    [DataMember]
    public string Value { get; set; }

    [DataMember]
    public string ValueType { get; set; }
}

I receive this class on the client side by wcf server references and try to map it to System.Security.Claims.Claim like that:
    Mapper.CreateMap<ClaimView, Claim>()
      .ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.Type))
      .ForMember(dest => dest.Value, opt => opt.MapFrom(src=> src.Value))
      .ForMember(dest => dest.ValueType, opt => opt.MapFrom(src => src.ValueType))
      .ForMember(dest => dest.Issuer, opt => opt.Ignore())
      .ForMember(dest => dest.OriginalIssuer, opt => opt.Ignore())
      .ForMember(dest => dest.Properties, opt => opt.Ignore())
      .ForMember(dest => dest.Subject, opt => opt.Ignore());

After I've got the error from autommaper he can't to convert it. What's missing or wrong?

A: Because Claim doesn't have a default constructor, you need to tell Automapper which constructor to use, e.g.:
  Mapper.CreateMap<ClaimView, Claim>()

        .ConstructUsing(cv => new Claim(cv.Type, cv.Value, cv.ValueType))

        .ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.Type))
        .ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.Value))
        .ForMember(dest => dest.ValueType, opt => opt.MapFrom(src => src.ValueType))
        .ForMember(dest => dest.Issuer, opt => opt.Ignore())
        .ForMember(dest => dest.OriginalIssuer, opt => opt.Ignore())
        .ForMember(dest => dest.Properties, opt => opt.Ignore())
        .ForMember(dest => dest.Subject, opt => opt.Ignore());

Then this test will pass:
public void Test()
{
     ClaimIdentityView civ = new ClaimIdentityView
     {
         ClaimViewList = new List<ClaimView>
                             {
                                 new ClaimView
                                 {
                                      Type = "type",
                                      Value = "val",
                                      ValueType = "string"
                                  }
                             }
     };

     var claims = civ.ClaimViewList.Select(Mapper.Map<ClaimView, Claim>).ToList();

     Assert.AreEqual(1, claims.Count);

     Assert.AreEqual("type", claims.Single().Type);
     Assert.AreEqual("val", claims.Single().Value);
     Assert.AreEqual("string", claims.Single().ValueType);
}


text:
Q: Angular Decimal pipe to display significant digits How to use the Angular Decimal pipe to display the most 5 significant digits from a number as follows:
123.456789 => 123.45
12.3456789 => 12.345
0.12345678 => 0.12345
0.00123456 => 0.00123
1234567.89 => 1234567

Some extreme cases
12         => 012.00

A: It should be as follows,
  <h1>{{ amount |  number:'3.2-2'}} </h1>

'3.2-2' means:

*

*A minimum of 3 digit will be shown before decimal point

*It will show at least 2 digits after decimal point

*But not more than 2 digits
DEMO


text:
Q: Positivity of a Sine transform of a positive function Consider a function $f(t)$ with $f(t>0)>0$ and $f(-t)=-f(t)$. Can I make any statement about the positivity of the Sine transform
$$\hat{f}(\omega) = \int_{0}^{\infty} \sin(\omega t) f(t) \mathrm{d}t$$
of such a function? I guess that $\hat{f}(\omega>0)>0$, but I am not sure why.
Edit: Apparently, my guess was wrong. However, I would still be interested, if there exist additional conditions for $f(t)$, which lead to $\hat{f}(\omega>0)>0$. So far, I have only found the condition $f''(t)>0$ for all $t>0$, which has been proven in E. Tuck, Bull. Austral. Math Soc. Vol. 74 (2006), p. 133.
Background: In statistical physics, there emerge kernels $f(t)$ with the above-mentioned properties. Conservation of energy implies that $\hat{f}(\omega>0)>0$ must hold true.

A: No. Consider for instance $f(t)=t\,|t|\,e^{-|t|}$. Then
$$
\hat f(\omega)=\int_0^\infty t^2e^{-t}\sin(\omega\,t)\,dt=\frac{2\,\omega\left(3-\omega^2\right)}{\left(\omega^2+1\right)^3}
$$
is $<0$ for $\omega>\sqrt 3$.


text:
Q: getting a "cannot find method" error in google script I have built the code below and when I run it I keep getting an error message of
"cannot find method copyTo(sheet)"
It is coming on the line when I try to copy to the target sheets.  All the copyTo lines give the same error: source_sheet1.copyTo(target_sheet1);
Edit:  I have changed the code but still get the same error:
function UpdateCore() {

  //Set Target (Core sheets to use)
  var FindThisCore = "Compliance Spreadsheet Template- Sandton";
  var fileCore = DriveApp.searchFiles('title contains "' + FindThisCore+ '" and mimeType = "application/vnd.google-apps.spreadsheet"')
  while (fileCore.hasNext()) {
    var fileCoreMonth = fileCore.next();
    var target = SpreadsheetApp.openById(fileCoreMonth.getId());
    var getmonthsheet = target.getSheetByName("Run me")
    var range = getmonthsheet.getRange(2,2);
    var NewMonth = range.getValue();}

  //Set compliance file to use
  var FindThisMonth = "Compliance Spreadsheet Sandton " + NewMonth

  //Set the Source values (Monthly Values)
  var fileThisMonth = DriveApp.searchFiles('title contains "' + FindThisMonth + '" and mimeType = "application/vnd.google-apps.spreadsheet"')
  while (fileThisMonth.hasNext()) {
     var fileMonth = fileThisMonth.next();
     var source = SpreadsheetApp.openById(fileMonth.getId());}

  CopyToSheet(source,target,"Guiding", "Guiding");
  CopyToSheet(source,target,"Learning", "Learning");
  CopyToSheet(source,target,"Bookkeeping", "Bookkeeping");
  CopyToSheet(source,target,"Fees", "Fees");
}

Which calls
function CopyToSheet (SourceFile, TargetFile, SourceSheet, TargetSheet){

  var SourceSheetFile = SpreadsheetApp.openById(SourceFile.getId());
  var TargetSheetFile = SpreadsheetApp.openById(TargetFile.getId());
  var sourcetoread = SourceSheetFile.getSheetByName(SourceSheet);
  var targettowrite = TargetSheetFile.getSheetByName(TargetSheet);

  sourcetoread.copyTo(targettowrite);
}

I have checked that it is connecting to the correct sheets by having it clear the sheets in the target and source- but the copyTo is still not working.

A: I tried to simplify your code by this function:
function test(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetundefined = ss.getSheetByName("badName");
  var sheetdefined = ss.getSheetByName("existingName");
  sheetdefined.copyTo(sheetdefined);
}

This way the error "cannot find method copyTo..." is triggered.
If you try to use "copyTo" on a undefined object, it will throw the error message "cannot invoke method copyTo of null".
So I guess this simply means, you should check beforehands if your sheets are defined and your target and source are not the same object, maybe this way.
if(sheet != undefined && targetSheet != undefined &&
   sheet.getSheetId != targetSheet.getSheetId){
  sheet.copyTo(targetSheet);
}

A: I found the error:  I was using the copyto method addressing the target sheet, I changed it to on the file and it works perfectly.  The change was very simple, in the function above I changed
sourcetoread.copyTo(targettowrite);

to
sourcetoread.copyTo(TargetSheetFile);

Since I wanted it to overwrite the existing sheet of that name.  I changed the overall function to delete the existing sheet, copy in the new name and then rename it to the original name (rather than the "Copy to..." name automatically assigned).  the full new function looks like this
function CopyToSheet (SourceFile, TargetFile, SourceSheet, TargetSheet){

  var SourceSheetFile = SpreadsheetApp.openById(SourceFile.getId());
  var TargetSheetFile = SpreadsheetApp.openById(TargetFile.getId());
  var sourcetoread = SourceSheetFile.getSheetByName(SourceSheet);
  var targettowrite = TargetSheetFile.getSheetByName(TargetSheet);
  TargetSheetFile.deleteSheet(targettowrite);

  sourcetoread.copyTo(TargetSheetFile);
  var RenameSheet = "Copy of " + TargetSheet;
  var RenameThis = TargetSheetFile.getSheetByName(RenameSheet);
  RenameThis.setName(SourceSheet)

}


text:
Q: Finding a weighting function I have this equation: $$(1+x)y''-xy'-y = 2x.$$
I have to bring this equation to the self-adjoint form. I have already solved this step with using integration factor method and I obtained,
\begin{equation}
[(x+1)e^{-x}y']'-e^{-x}y = 2x(x+1)e^{-x}
\end{equation}
but my problem is that from here I don't know how can i find the $p(x),\rho(x)$ and $q(x)$ from the self-adjoint form so that i can then solve the differential equation using Lagrange? so all i need is to know how can i extract them from the self-adjoint equation found.
Thanks in advance.


text:
Q: Computable images of differences of r.e. sets Suppose f is a computable function from a recursively enumerable set U to the natural numbers and that L,K are r.e. subsets of U. Is f(L-K) a difference of r.e. subsets? The motivation comes from
Primes occurring as orders of elements of a finitely presented group
A positive answer would mean that the theorem proposed in HW's nice answer is 100% correct. Otherwise the $\epsilon$-clarification in my answer is actually needed.

A: Is f injective?  If so, yes.  If not, no.  In the second case, you could achieve any $\Sigma^0_2$ set.


text:
Q: Find out how many characters in a string can fit in one row I have to split a string into an array based on how many characters can fit on each line. Each object in an array needs to be only one line of text. I am able to calculate the number of lines within the string but I can't figure out how to find out max number of characters on one line.
func lineCount(forText text: String) -> Int {
        let font = UIFont.systemFont(ofSize: 24.0)
        let width: Int = Int(self.tableView.frame.size.width)
        let rect: CGRect = text.boundingRect(with: CGSize(width: CGFloat(width), height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)
        return Int(ceil(rect.size.height / font.lineHeight))
    }

A: Swift 5 Update to the answer which worked for me.

*

*Added lineBreakMode
extension String {
    func splittingLinesThatFitIn(width: CGFloat, font: UIFont) -> [String] {

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineBreakMode = .byWordWrapping

        // set up styled text for the container
        let storage = NSTextStorage(string: self, attributes: [
            NSAttributedString.Key.font: font,
            NSAttributedString.Key.paragraphStyle: paragraphStyle
        ])

        // add a layout manage for the storage
        let layout = NSLayoutManager()
        storage.addLayoutManager(layout)

        // Set up the size of the container
        // width is what we care about, height is maximum
        let container = NSTextContainer(size: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude))

        // add the container to the layout
        layout.addTextContainer(container)

        var lines = [String]()

        // generate the layout and add each line to the array
        layout.enumerateLineFragments(forGlyphRange: NSMakeRange(0, storage.length)) { _, _, _, range, _ in
            lines.append(storage.attributedSubstring(from: range).string)
        }

        debugPrint(lines)

        return lines
    }
}

A: You can't get a set number of characters in a row with every font since some fonts have characters with variable widths. What you can do is try to break the string up into line-sized chunks:
extension String {
  func split(width: CGFloat, font: UIFont) -> [String] {
    guard !self.isEmpty else { return [String]() }

    var lines = [String]()

    // set up range of the split
    var splitStart = self.startIndex
    var splitEnd = self.startIndex

    repeat {
      // advance the end range for the split
      splitEnd = self.index(after: splitStart)

      // initial split to test
      var line = String(characters[splitStart..<splitEnd])

      // while we're before the end test the rendered width
      while splitEnd < self.endIndex &&
        line.size(attributes: [NSFontAttributeName: font]).width < width {
          // add one more character
          splitEnd = self.index(after: splitEnd)
          line = String(characters[splitStart..<splitEnd])
      }

      // add split to array and set up next split
      lines.append(line)
      splitStart = splitEnd
    } while splitEnd < self.endIndex // don't go past the end of the string

    // add remainder of string to array
    lines.append(String(characters[splitStart..<self.endIndex]))
    return lines
  }
}

This can be optimized a bit by pre-calculating the width of the entire string, dividing by the number of rows, starting with the average width for each line and then try more or less characters until it fits. However, that does make the code much more complex.
If you want to make sure that words don't get split up then you could save the position of the start of each word and when you reach the end of a line make the split end before the word, taking the word to the next split. Of course you would want to also account for words that are too long to split, hyphenating words, and so on.
Another way to do it, since you need more advanced layout, would be to use NSLayoutManager and NSTextContainer:
let text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Non est ista, inquam, Piso, magna dissensio. Minime vero istorum quidem, inquit. Graecum enim hunc versum nostis omnes-: Suavis laborum est praeteritorum memoria. Negat enim summo bono afferre incrementum diem. Quasi ego id curem, quid ille aiat aut neget. Semper enim ex eo, quod maximas partes continet latissimeque funditur, tota res appellatur. Duo Reges: constructio interrete."

let font = UIFont.systemFont(ofSize: 24.0)

// set up styled text for the container
let storage = NSTextStorage(string: text, attributes: [NSFontAttributeName: font])

// add a layout manage for the storage
let layout = NSLayoutManager()
storage.addLayoutManager(layout)

// Set up the size of the container
// width is what we care about, height is maximum
let width:CGFloat = 500
let container = NSTextContainer(size: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude))

// add the container to the layout
layout.addTextContainer(container)

var lines = [String]()

// generate the layout and add each line to the array
layout.enumerateLineFragments(forGlyphRange: NSMakeRange(0, storage.length)) {
  lines.append(storage.attributedSubstring(from: $0.3).string)
}

lines.forEach { print($0) }

Result:
Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Non est ista, inquam, Piso,
magna dissensio. Minime vero istorum
quidem, inquit. Graecum enim hunc versum
nostis omnes-: Suavis laborum est
praeteritorum memoria. Negat enim summo
bono afferre incrementum diem. Quasi ego id
curem, quid ille aiat aut neget. Semper enim
ex eo, quod maximas partes continet
latissimeque funditur, tota res appellatur. Duo
Reges: constructio interrete.

You can also provide hyphenation and other behaviors through the NSLayoutManager, if you like.

A: i'm not sure if this is the most efficient way but I got it to work with this:
func getLinesArrayOfString(forText text: String) ->NSArray {
        let font = UIFont.systemFont(ofSize: 24.0)
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.tableView.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
        label.numberOfLines = 0
        label.text = text as String
        label.font = font
        label.sizeToFit()
        var linesArray: [Any] = []

        let rect: CGRect = label.frame

        let attStr = NSMutableAttributedString(string: text)
        attStr.addAttribute((NSAttributedStringKey(rawValue: kCTFontAttributeName as String)), value: font, range: NSRange(location: 0, length: attStr.length))
        let frameSetter: CTFramesetter = CTFramesetterCreateWithAttributedString(attStr)
        let path: CGMutablePath = CGMutablePath()
        path.addRect(CGRect(x: 0, y: 0, width: rect.size.width, height: 100000), transform: .identity)
        let frame: CTFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
        let lines = CTFrameGetLines(frame) as? [Any]

        for line: Any in lines! {
            let lineRef = line
            let lineRange: CFRange = CTLineGetStringRange(lineRef as! CTLine)
            let range = NSRange(location: lineRange.location, length: lineRange.length)
            let lineString: String = (text as NSString).substring(with: range)

            CFAttributedStringSetAttribute(attStr, lineRange, kCTKernAttributeName, font)
            CFAttributedStringSetAttribute(attStr, lineRange, kCTKernAttributeName, font)
            linesArray.append(lineString)
        }
        return linesArray as NSArray
    }


text:
Q: UINavigationController interactivePopGestureRecognizer working abnormal in iOS7 In iOS7, we have a new "swipe left to right" gesture, this is a very useful feature, but now I have a problem with it.
I use this code to custom the back button in UINavigationBar.
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
but this will disables the "swipe left to right" gesture, so I use the follow code to keep the gesture enabled.
self.navigationController.interactivePopGestureRecognizer.delegate = self
And then, I found that the gesture is working abnormal, if current ViewController has a tableView, when the tableView is scrolling, the gesture won't be triggered. Now the gesture can't be triggered easily, is there some way to fix it?

A: Setting the interactivePopGestureRecognizer.delegate to self is only the first step. The second step is to implement
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return !(otherGestureRecognizer is UIPanGestureRecognizer)
}

The test against the pan gesture recognizer is needed to block vertical scrolling of a scroll or table view while the interactive pop is in progress.

A: Add in Class Controller "UIGestureRecognizerDelegate"
in viewDidAppear add
override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    self.navigationController?.interactivePopGestureRecognizer.delegate =  self
}

=)

A: This code can wroks well for me.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return [gestureRecognizer isKindOfClass:UIScreenEdgePanGestureRecognizer.class];
}


text:
Q: Difference between strcmp of string.h and my own implementation of strcmp The first printf gives output as -1, whereas the second printf gives output as -115.
#include<stdio.h>
#include<string.h>
int mystrcmp(char*s, char*t){
    for(;*s==*t;s++,t++){
        if(*s=='\0'){
            return 0;
        }
    }
    return (*s-*t);
}
int main()
{
    char *y,*x="this";
    y="thiss";
    printf("%d\n\n",strcmp(x,y));
    printf("%d",mystrcmp(x,y));
    return 0;
}

I understand, that in my implementation, the code is calculating 0(ASCII of Null) - 's'(ASCII value 115).
Can anyone please help me as to how I may exactly duplicate the working of strcmp function that is in string.h

A: The implementation of the "real" strcmp on your platform is most likely close to this code:
int strcmp(const char *s, const char *t) {
    for(; *s == *t; s++, t++) {
        if (*s == '\0') {           // are we at the end ?
            return 0;               // yes
        }
    }
    return (*s-*t) > 0 ? 1 : -1;   // return either +1 or -1
}

BTW: it should be int strcmp(const char *s, const char *t) instead of int strcmp(char *s, char *t)

A: The exact values returned from strcmp in the unequal cases aren't defined explicitly.  In your particular case, any negative value is considered valid.  From the man page:

The strcmp() and strncmp() functions return an integer less than,
  equal to, or greater than zero if s1 (or the first n bytes thereof) is
  found, respectively, to be less than, to match, or be greater than s2.

So the only guarantee is that if the first argument is "less than" the second then the result is negative, and if the first is "greater than" the second then the result is positive.  Different implementations may return different values for the same strings.
As an example, if I compile and run your code on my machine with optimization set at -O0, I get back -115 from strcmp.  If I change the optimization to -O1, it returns -1 instead.  So not only can the result change from one machine to the next, but it can even vary on the same machine with different compiler settings.

A:
The manuel page said that strcmp() function compares the two
  strings s1 and s2. It returns an integer less than, equal to, or
  greater than zero if s1 is found, respectively, to be less than, to
  match, or be greater than s2.
  Your can try this code :

    int ft_strcmp(const char *s1, const char *s2)
{
    while ((unsigned char)*s1 || (unsigned char)*s2)
    {
        if ((unsigned char)*s1 != (unsigned char)*s2)
            return ((unsigned char)*s1 - (unsigned char)*s2);
        s1++;
        s2++;
    }
    return (0);
}


text:
Q: Scope Issue Javascript (self, this) //Code starts
var self = this;
var a=10;

function myFunc(){
    this.a = 4;
    var a = 5;
    console.log("this.a -> " + this.a);   //Output: this.a -> 4
    console.log("self.a -> " + self.a);   //Output: self.a -> undefined
    console.log("a -> " + a);    //Output: a -> 5
}
myFunc();

//Code ends
Can someone please explain the Output of the above console.log                 statements. Thank You.

A:     console.log("this.a -> " + this.a);   //Output: this.a -> 4

The this keyword refers to the object the function belongs to, or the window object if the function belongs to no object. That said you created a varaible a on top and updated that inside the function. Thus 4
    console.log("self.a -> " + self.a);   //Output: self.a -> undefined

No. self referring to window and window have variable a. It should print 4. Check again.
    console.log("a -> " + a);    //Output: a -> 5

That a= 5 shadowed your global variable a declared outside function. You accessed the more specific variable. Local variable have more specific.

A: In Javascript, every scope level has a this. When you save this in the var self outside of any function (top level), it gets the window object. So the first this (stored in self) is different from the one in the function. No property "a" was defined on the top level, so self.a is undefined.
Now there is a difference between a variable (var) and a propery (obj.prop). The first one will be resolved from scopes (if a is not defined in the current scope, it will search if it is defined in higher scopes, until it finds window where "global vars" are, and comes undefined if still not found). The second one will search the property through the prototype chain.

A: I tried the code, self.a also is coming as 4, which is fine.


text:
Q: How do I remove an orphaned Exchange 2010 server from the organization? We properly uninstalled Exchange 2010 from a server but it is still appearing within the Exchange Management Console of the other Exchange 2010 server.  How can we remove this server from the Exchange organization?

A: You'll want to get your ADSIEDIT out...  Beware - you can break things - badly if you aren't careful.  Have a look at the ADSIEdit portions of this...
Got this from http://forums.msexchange.org/m_1800532154/mpage_1/key_/tm.htm#1800532154
You will have to open ADSIEDIT.MSC from one of your Domain Controllers and then navigate to the Server Name.

Path would be
Configuration -> Services -> Microsoft Exchange -> { Name of Your Organization } ->     Administrative Group -> Exchange Administrative Group -> Servers -> { Your Server Name }

Then remove the Server and again try installing again.

It's really not as scary as it sounds...  Just be careful, you probably wanna back up your system state (AD) before you do this.


text:
Q: NTFS Compression on multiple folders I have been tasked with compressing certain folders on a network drive. The drive is formatted NTFS on a Windows Server 2008 R2 machine. The folders to be backed up are all called "Backup", and are several levels deep into the directory structure. I would like an automated way to set each of these folders to use NTFS compression.
Also, on some folders that I have set as compressed, it seems like new files added to them do not become compressed. Is this normal behavior, or how can I ensure that all files within each of these folders does get compressed?

A: Following Ramhound's advice, I did the following:
$results = Get-ChildItem . backup -r | ? {$_.PSIsContainer}
foreach ($object in $results)
{
   $name = $object.FullName + "\*.*"
   compact /c /f $name
}

Okay, it almost did the trick. It compresses every file in every backup directory under the current one, but it does not mark the directories as compressed, so it does not seem to compress new files as they are put in.


text:
Q: Preserve order of outputs of commands executed in parallel by xargs When I run a command with xargs -n 1 -P 0 for parallel execution, the output is all jumbled. Is there a way to do parallel execution, but make sure that the entire output of the first execution is written to stdout before the output of the second execution starts, the entire output of the second execution is written to stdout before the output of the third execution starts, etc.?
For example, when wanting to hash many files containing a lot of data, it can be done like this:
printf "%s\0" * | xargs -r0 -n 1 -P 0 sha256sum

I tested this on a small amount of data (9 GB) and it was done in 5.7 seconds. Hashing the same data using
sha256sum *

took 34.1 seconds. I often need to hash large amounts of data (which can take hours), so processing this in parallel can get things done a lot faster.
The problem here is that the order of the output lines is wrong. In this case, it can be fixed by simply sorting the lines by the second column. But it's not always this easy. For example, this would already break while sticking to the hashing example from above but wanting to hash numbered files in order:
printf "%s\0" {1..10000} | xargs -r0 -n 1 -P 0 sha256sum

This requires more advanced sorting. If we leave hashing example altogether, things get more complicated still.
In the comments, I was asked whether I merely want to prevent interleaving of output. This is not the case. I want order to be preserved.

A: You can do it with GNU Parallel (--keep-order):
printf "%s\0" {1..10000} | parallel --keep-order -r0 -n 1 -P 0 sha256sum


text:
Q: JSF: AJAX Testing best practices We have a JSF 2.0 project with heavy use of AJAX (provided by OpenFaces tag library). Our project is very cool and does many useful things, and we love it. However there is one thing about it that frustrates us - our project doesn't have integration tests. At all. It has selenium tests of course, but they cover the project only from user's perspective. What I'd love to have are some integration tests which would deal with AJAX-related logic. But I'm not sure how to achieve this... Things that are capturing my mind are JSFUnit and HTTPUnit, but I wonder if there is something better for AJAX-based JSF project. Does anyone have any concerns about this?
Thanks!

A: You could try FireUnit or FireBugTest. I haven't tried either of these but they might work. I have always wished for a feature like this too.

A: have you tried Watir
http://wiki.openqa.org/display/WTR/Simple+Ajax+examples
It also has a firefox variant. FireWatir
--Kiran.Kumar


text:
Q: Background Image not Rendering Correctly on iPhone4 I have a background image created by my designer in Photoshop. I convert it to png-24, and have two files, one for retina display at 640 x 920, and one for normal display at 320 x 460 (and which I name correctly with @2x).
When I implement it on the iPhone 4, it doesn't render correctly (the color is much darker), however, when I put it on the iPhone5 it works fine. The size of the file is 608 KB. Anyone know what could be going wrong and how I can fix this?

A: I wouldn't say that the size is a problem. Beeing a background image means it doesn't change over the life time of the app.
Regarding the file size - you could play with the "Save for Web" option in Photoshop and watch for artifacts while you change the format/quality. PNG is great for images with transparency and according to Apple it is the optimal image format for the iPhone.
The color inconsistency between devices might be due to differences in display quality. You could try to fix it programmatically, but make sure to test it on a few devices. As for a easy workaround, in interface builder add a new view over you background image and set the transparency and color to your liking. Then set the view to hidden. Then, depending on the device (iPhone5, iPhone4) set your color view to visible
[view setHidden:NO];
However I can't imagine that iPhone displays differ that much, so be careful if you really want to fix it programmatically.

A: I've really tried a lot to solve this problem and have used a DTS ticket on it. In the end, the reason for this is the iPhone5 displays colors better and there was nothing I could do to fix it.


text:
Q: How to select the count of total active listings week by week? I want to get the count from a table of active apartment listings week by week. The table looks like this (except much longer):
id      created_at          delisted_at
2318867 2014-11-12 18:57:44 Null
2329665 2014-11-14 4:36:32  Null
1431098 2014-07-25 5:45:03  Null
1930123 2014-09-28 10:10:46 2014-09-28 10:10:45
2490774 2014-12-05 0:08:47  Null

To get an active listings for a single week, you have to check that created_at <= end_of_week and delisted_at > end_of_week.
The results table would like like a longer version of:
Week        Number of Active Listings
5/1/2016    3024
5/8/2016    11234
5/15/2016   11234

I would also like to produce another results table month by month as opposed to week by week.
How do I write a query to achieve this behavior?

A: Here is an example for month.  First generate a list of months using generate_series().  The rest is just joins and aggregations:
select g.mon_start, g.mon_end, count(a.id) as numActives
from (select g.mon_start, g.mon_start + interval '1 month' as mon_end
      from generate_series('2016-01-01'::timestamp, '2016-06-01'::timestamp, interval '1 month'
                          ) g(mon_start)
     ) g left join
     actives a
     on a.created_at < g.mon_end and
        (a.delisted_at >= mon_end or a.delisted_at is null)
group by g.mon_start, g.mon_end
order by g.mon_start, g.mon_end;

A similar idea works for weeks as well.


text:
Q: Add a condition to the if statement in my code? is there a way to add at the end of the formula of mc_callAsia an else 0??
for j in range (1,10):
  for k in range (len(K)) :
    mc_callAsia = np.asarray([(i-K[k]) for i in dictimoyennes["moyenneAsia" + str (j)] if (i-K[k])>0])
    payoffAsia = (1/(1+r[k])**T)*sum(mc_callAsia)/10000
    payoffsAsia = np.append(payoffsAsia, [payoffAsia])

The goal would be to keep all the values so either it's positive or 0. I've tried to do it like this
for j in range (1 ,10):
  for k in range (len(K)) :
    for i in range (1, 10000):
        payoffss= max(dictimoyennes["moyenneAsia" + str (j)][i] - K[k],0)
        payoffssAsia = np.append(payoffssAsia, [payoffss])

but it loops forever...
Thank you in advance

A: Yes, you can use if-else in for loop in one line.
# Simple structure
[ x if x%2 else x*100 for x in range(1, 10) ]

# It returns a list. So in you case it would be...
mc_callAsia = [np.asarray([(i-K[k]) if (i-K[k])>0]) else 0 for i in dictimoyennes["moyenneAsia" + str (j)]]


text:
Q: Java project does not compile after switching from Maven to Gradle with "cannot find symbol" errors I had a Maven project, which I then switched to Gradle. I am now attempting to compile the Gradle project, but it isn't compiling, even if it was building and compiling successfully when I used Maven.
I ran gradle init to convert my project to Gradle and it stopped compiling and gave me the "cannot find symbol" errors. It seems as though Gradle cannot find many classes, including the Main class.
I have effectively read through the post: What does a "Cannot find symbol" or "Cannot resolve symbol" error mean? and I was unable to fix my issue. I know it's a compilation error, but I don't know what's causing it. I didn't change the code when I switched from Maven to Gradle, only the build files.
Here is an example of one of the errors:
        Main instance = Main.getInstance();
                            ^
  symbol:   method getInstance()
  location: class Main

Note: the build is a multi-project build. It has several subprojects. Here is the mother build.gradle file:
plugins {
    id "java"
    id "com.github.johnrengelman.shadow" version "7.1.2"
    id "war"
}

group "net.pixlies"
version "1.0-SNAPSHOT"

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

subprojects {
    compileJava.options.encoding = "UTF-8"

    apply plugin: "java"
    apply plugin: "war"
    apply plugin: "com.github.johnrengelman.shadow"

    compileJava {
        sourceCompatibility = 17
        targetCompatibility = 17
    }
}

repositories {
    mavenCentral()
    maven { url "https://repo.purpurmc.org/snapshots/" }
    maven { url "https://repo.extendedclip.com/content/repositories/placeholderapi/" }
    maven { url "https://repo.aikar.co/content/groups/aikar/" }
    maven { url "https://repo.dmulloy2.net/repository/public/" }
}

dependencies {
    implementation "org.mongodb:mongo-java-driver:3.12.11"
    implementation "commons-io:commons-io:2.11.0"
    implementation "co.aikar:acf-paper:0.5.1-SNAPSHOT"
    implementation "org.ocpsoft.prettytime:prettytime:5.0.3.Final"
    implementation "commons-lang:commons-lang:2.6"
}

Here is the settings.gradle file:
pluginManagement {
    repositories {
        gradlePluginPortal()
        maven { url "https://papermc.io/repo/repository/maven-public/" }
    }
}

rootProject.name = 'version-two'

include(':PixliesCore')
include(':LobbyModule')
include(':MiniMick')
include(':ProtoBusiness')
include(':PixliesFun')
include(':Nations')
include(':DiploMaurice')
include(':PixliesProxyCore')

The PixliesCore project is having these issues with the "Cannot find symbol" error. Here is the PixliesCore subproject build.gradle file:
plugins {
    id 'net.pixlies.java-conventions'
}

dependencies {
    implementation 'com.github.stefvanschie.inventoryframework:IF:0.10.7'
    implementation 'org.projectlombok:lombok:1.18.24'
    implementation 'redis.clients:jedis:4.2.3'
    implementation 'joda-time:joda-time:2.11.1'
    compileOnly 'org.purpurmc.purpur:purpur-api:1.19-R0.1-SNAPSHOT'
    compileOnly 'com.comphenix.protocol:ProtocolLib:4.7.0'
    compileOnly 'me.clip:placeholderapi:2.11.2'
    compileOnly 'net.luckperms:api:5.4'
}

description = 'PixliesCore'

I also ran ./gradlew assemble in the mother project's directory. Here is the output:
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':PixliesCore:compileJava'.
> invalid source release: 17

Perhaps this "invalid source release" is the cause, but I do not know what it means or how to fix it. I'm using the Java 17 SDK for everything.
Oh, also, here is the original POM.xml for the mother project:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <modules>
        <module>PixliesCore</module>
        <module>Nations</module>
        <module>MiniMick</module>
        <module>LobbyModule</module>
        <module>PixliesFun</module>
        <module>PixliesProxyCore</module>
        <module>DiploMaurice</module>
        <module>ProtoBusiness</module>
    </modules>

    <groupId>net.pixlies</groupId>
    <artifactId>version-two</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.12.11</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
        <dependency>
            <groupId>co.aikar</groupId>
            <artifactId>acf-paper</artifactId>
            <version>0.5.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.ocpsoft.prettytime</groupId>
            <artifactId>prettytime</artifactId>
            <version>5.0.3.Final</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>purpur</id>
            <url>https://repo.purpurmc.org/snapshots</url>
        </repository>
        <repository>
            <id>aikar</id>
            <url>https://repo.aikar.co/content/groups/aikar/</url>
        </repository>
            <repository>
                <id>placeholderapi</id>
                <url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
            </repository>
        <repository>
            <id>dmulloy2-repo</id>
            <url>https://repo.dmulloy2.net/repository/public/</url>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>16</source>
                    <target>16</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

And the POM.xml for the PixliesCore subproject:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>version-two</artifactId>
        <groupId>net.pixlies</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>PixliesCore</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>

    <repositories>
        <repository>
            <id>aikar</id>
            <url>https://repo.aikar.co/content/groups/aikar/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>com.github.stefvanschie.inventoryframework</groupId>
            <artifactId>IF</artifactId>
            <version>0.10.7</version>
        </dependency>
        <dependency>
            <groupId>org.purpurmc.purpur</groupId>
            <artifactId>purpur-api</artifactId>
            <version>1.19-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
        <dependency>
            <groupId>com.comphenix.protocol</groupId>
            <artifactId>ProtocolLib</artifactId>
            <version>4.7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>4.3.1</version>
        </dependency>
        <dependency>
            <groupId>me.clip</groupId>
            <artifactId>placeholderapi</artifactId>
            <version>2.11.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.12.2</version>
        </dependency>
        <dependency>
            <groupId>net.luckperms</groupId>
            <artifactId>api</artifactId>
            <version>5.4</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <pluginRepositories>
        <pluginRepository>
            <id>maven-snapshots</id>
            <url>https://repository.apache.org/content/repositories/snapshots/</url>
        </pluginRepository>
    </pluginRepositories>

    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
    </properties>

    <build>
        <defaultGoal>clean package</defaultGoal>
        <finalName>PixliesCore</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.3.1-SNAPSHOT</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <dependencyReducedPomLocation>${project.build.directory}/dependency-reduced-pom.xml</dependencyReducedPomLocation>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
Q: How do you find N integers such that their sum equals to M? How do you find any possible combination of N distinct integers such that their sum equals to a given integer M?
The integers can be between -2^31 to 2^31, with N being less than or equal to 500000 and M also being between -2^31 and 2^31.
An example:

*

*4 is given as N, 8 is given as M.

*A possible combination would be 3, -1, 4, 2

A: Let's say N is odd. We can choose N/2 positive integers that are not M. We also choose the negative of those integers. Finally, we choose M. For example, if N = 5 and M = 9, we can choose 2, -2, 4, -4. Then we simply choose 9, as our final integer, giving us a sum of M.
Let's say N is even. We can use a similar system, but choose N/2-1 positive integers and their negative counterparts, 0, and then M. So for N = 6, M = 11, we can choose 5, -5, 6, -6, 0, 11 for a sum of 11.
These choices are not unique, but simply choosing consecutive integers would be trivial.

A: *

*Fours integers you have provided into the questions don't add up to 8.

*As you have not mentioned in the question, I am assuming that duplicates are allowed. What you can do is to divide M into N-1 equal segments (floor division) and Nth element will be M - M/(N-1) * (N-1)
def findCombination(N, M):
   if N == 1:
      return M
   ans = [(M/(N-1)) * (N-1)]
   ans.append(M - M/(N-1) * (N-1))
   return ans

Update:
As of now, the question has been updated that only distinct elements are allowed, you can follow the process:

*

*If N is odd:
start picking up values with the same absolute value but with different signs like 1 -1 2 -2 3 -3. Don't include M in this process. You can choose N/2 positive elements and N/2 negative elements. The last element you can include in and is M.

*If N is even:
start picking values as described above. Now you need to exclude two elements which sum up to M. So you can exclude 1 and M-1 and later include them into final answer.

A: This is a sample code in GO
package main

import (
    "fmt"
)

func main() {
    n, m := 15, 10

    fmt.Println(m)

    if n == 1 {
        return
    }

    n--

    if n%2 != 0 {
        fmt.Println(0)
        n--
    }

    for i := 1; i < n; i += 2 {
        fmt.Println(-i)
        fmt.Println(i)
    }

}


text:
Q: Django settings.AUTH_USER_MODEL defined in separate module What is the proper way to say what is my AUTH_USER_MODEL?
I have the following set:
Folder structure:
--- backend
----- api
-------- models
----------- user.py
user.py lies within models folder
in settings.py:
AUTH_USER_MODEL = 'myapp.User'

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'api',
]

The model:
class User:

    class Meta:
        app_label = "myapp"

And when I run any manage.py command, for example

python manage.py showmigrations

I get this error:

LookupError: No installed app with label 'myapp'.

The problem solution would be renaming api folder to myapp, which I cannot do due to some restrictions on model names.  Or setting AUTH_USER_MODEL to api.User, but this will incur changing all data table names and those must remain the same
Data table names starting with 'myapp_' should not change

A: Given your folder structure looks like that:
backend
└── api
|   ├── __init__.py
|   ├── apps.py
|   └── models
|       ├── __init__.py
|       └── user.py
├── manage.py
└── settings.py

then you can create an app config in backend/api/ by creating a file called apps.py inside it. There you can rename your app:
backend/api/apps.py:
from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'myapp'
    verbose_name = _('My App')

Also you need to add this to the __init__.py inside that folder:
backend/api/__init__.py:
default_app_config = 'api.apps.MyAppConfig'

Also if you want to use myapp.User as your user model you also have to import in in the models module:
backend/api/models/__init__.py:
from .user import User
# or use "from .user import *" to import everything but then make sure you have __all__ defined in user.py

A: The solution was to change AppConfig.label in class MyAppConfig(AppConfig), so if you update your answer, I will accept it. Changing name ends in nothing, it must be the real name of the module the code sits in, but adding label = 'arbitrary_name' is actually the solution


text:
Q: Reshape 3D Tensor before Dense layer Given a tensor of shape=[batch_size, max_time, 128] (the output of an RNN), for which max_time may vary, I would like to apply a fully connected layer to project the data onto a [batch_size, max_time, 10] shape.
The question is: do I need to reshape the input Tensor first, merging the first two dimensions, then apply tf.layers.dense, then reshape back to 3D? Or can I simply use tf.layers.dense on the 3D tensor to obtain an equivalent effect ?
I would like to have a single weight matrix shared for all the connections between the 128 RNN units and the 10 output classes, allowing at the same a variable length max_time for each batch.

A: After further investigation, is appears that the two options are equivalent.
The Dense.call() method checks the number of dimensions. If this is larger than 2, then it computes a tensordot (an operation which corresponds to numpy.tensordot) between the input and the weights, choosing as axes the last dimension in the input and the first dimension in the weights. Otherwise it applies standard matrix multiplication (matmul).
Source


text:
Q: Get index of selected DOM element return -1? I bind album_item for click event, and I want to get box's index. But I got -1.
HTML

a

b

c

Javascript
    $(function () {
        $(document).on('click', '.album_item', function () {
            alert($(this).find('.box_album_item').index());
        });
    });

A: You are trying to select an element that does not exist:
The find() function searches for children of the given element, in this case .album_item. So, .album_item down not have any children elements, that's why it's index is -1
Instead, you must use closest() function in order to search upwards the DOM tree:
$(document).on('click', '.album_item', function () {

        alert($(this).closest('.box_album_item').index());

    });

A: it should be:
alert($(this).closest('.box_album_item').index());

*

*.find() goes inside of the element to the children.

*.closest() traverses upwards to the parents.

so in your case .box_album_item is the parent, so .closest() should be used.

A: alert($(this).closest('.box_album_item').index());

http://jsfiddle.net/f3okr0ba/1/

A: $(document).on('click', '#album_item', function () {

use id instead class