text:
Q: How can I build a condition based query in Laravel 6.x? public function test(Request $request){
    $apartments = DB::table('apartments');
    if ($request->filled('bathrooms')) {
        $apartments->where('bathrooms', '=' ,$request->input('bathrooms'));
    }
    if ($request->filled('rooms_number')) {
        $apartments->where('rooms_number', '=', $request->input('rooms_number'));
    }
    $apartments->get();
    return view('pages.test2' , compact('apartments'));
}

How can this code be translated so that it works in Laravel?

A: You can use when as a conditional clause:
public function test (Request $request)
{
    $apartments = DB::table('apartments')
        ->when($request->filled('bathrooms'), function ($query) use ($request) {
            return $query->where('bathrooms', '=', $request->input('bathrooms'));
        })
        ->when($request->filled('rooms_number'), function ($query) use ($request) {
            return $query->where('rooms_number', '=', $request->input('rooms_number'));
        })
        ->get();

    return view('pages.test2' , compact('apartments'));
}


text:
Q: Is "to share or to have a common interest" a tautology? I often read and hear "to share a common .." but it seems very pleonastic to me. Isn't it saying the same thing twice? In other words, is it a tautology, and if so, should it be avoided or is it acceptable, even in a scholarly context?

A: A TAUTOLOGY is a needless repetition of an idea, statement, or word.
One can have common interests that are not shared. One can share common platforms, common living spaces, and many other things. One can also share uncommon interests
Share: a part or portion of a larger amount that is divided among a number of people, or to which a number of people contribute. Synonyms include portion, part, division, quota, quantum, allowance, ration, allocation, measure, due. One can portion money, space, etc.

HPRLCL is a location-based social discovery platform that allows travelers, locals and everyone in between to discover and share uncommon urban experiences.

Examples of tautologies include

A major *nuclear disaster* could have been sparked off...
  ...who died of a fatal dose of heroin.
  ...equalized the game to a 2-2 draw
  ...kept it from his friends that he was a secret drinker

A: At first sight, this does look like a tautology, and you might think that sharing something means that it is common to the sharers anyway. But what else can you do with something that is common? These expressions seem rather more like reinforcements than redundancies.

A: I would say, in the meaning in which the phrase is usually understood, to share a common interest is indeed a tautology because it means that some people both have an interest in something that they both are interested in: both share and common indicate that the object is applicable to all subjects involved.
In that case I would indeed say

They share an interest.

or

They have a common interest.

On the other hand, if I invite individual in a group to share some of their personal details with the group, they are certainly invited to list their interests or hobbies. If those interests are not applicable to others in the group, or if those interests are out of the ordinary in general (see my example in my comment to Susan), it would be correct to say they are sharing uncommon interests.
If their interests do apply to the rest of the group as well, one could similarly state (without it being a tautology) that they are sharing common interests.
This would involve a different meaning of the verb to share altogether, though.
In the same way, if we want to express how common (or usual) interests are that two or more individuals share, the statement

They share a common interest.

Could be read as "they are both interested in something that is very common, like pop music." In that case, there is also no tautology.
TLDR:
So, if "share" means "to tell something" or "common" is understood to mean "usual", there is no tautology. In the general sense of "they share an interest" meaning "they have a common interest", I would see "they share a common interest" as a tautology.

redpajama_set_name: RedPajamaStackExchange


text:
Q: 400 Bad Request using Tomcat for Virtual Host I'm trying to load my java web project in the browser but I'm receiving "400 Bad Request", I have in my Tomcat server.xml:
<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
        <Alias>demonstracao.itcmedbr.com></Alias>

        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b" />

        <Context path="" docBase="/opt/tomcat/webapps/demonstracao"
           debug="0" reloadable="true"/>
      </Host>

I'll appreciate any help. Thanks.


text:
Q: How to avoid underfull \hbox when using subfigures? When compiling the MWE below with pdflatex, I get the warnings Underfull \hbox (badness 10000) in paragraph at lines 26--27 and Underfull \hbox (badness 10000) in paragraph at lines 36--37.
I tried to avoid this by using \hfill between the subfigures, but it didn't work.
\documentclass{scrbook}
\usepackage[utf8]{inputenx}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{epstopdf}
\usepackage{subcaption}
\usepackage{gnuplottex}
\usepackage{xparse}
\ExplSyntaxOn
\DeclareExpandableDocumentCommand{\convertlen}{ O{cm} m }
 {
  \dim_to_unit:nn { #2 } { 1 #1 } cm
 }
\ExplSyntaxOff

\begin{document}
\begin{figure}[htbp]
 \centering
 \begin{subfigure}[b]{.45\textwidth}
  \begin{gnuplot}[terminal = cairolatex, terminaloptions = {size \convertlen{\textwidth},\convertlen{.3\textheight}}]
   plot sin(x)
  \end{gnuplot}
  \caption{A subfigure}
  \label{fig:1a}
 \end{subfigure}%
 \hfill
 \begin{subfigure}[b]{.45\textwidth}
  \begin{gnuplot}[terminal = cairolatex, terminaloptions = {size \convertlen{\textwidth},\convertlen{.3\textheight}}]
   plot sin(x)
  \end{gnuplot}
  \caption{Another subfigure}
  \label{fig:1b}
 \end{subfigure}
 \caption{A figure}\label{fig:1}
\end{figure}
\end{document}

A: If you add
\showboxdepth3
\showboxbreadth10
\tracingonline1

to see which box is underfull you see
\hbox(178.66272+0.0)x188.21371
.\hbox(0.0+0.0)x0.0
.\hbox(178.66272+0.0)x187.69623
..\special{ps: currentpoint currentpoint translate 1 1 scale neg exch neg exch
t\ETC.}
..\hbox(178.66272+0.0)x0.0, glue set - 187.69623fil
...\hbox(178.66272+0.0)x187.69623 []
...\glue 0.0 plus 1.0fil minus 1.0fil
..\special{ps: currentpoint currentpoint translate 1 1 div 1 1 div scale neg ex
c\ETC.}
.\glue(\rightskip) 0.0

So the line is trying to be 188.21371pt  but the box with the plot is 187.69623pt  the only glue on the line is \rightskip and that is zero, so the box is underful.
That's slightly odd as a one line paragraph usually has \parfillskip  at the end but that has been removed here somewhere in the verbatim handling for gnuplot.
rather than debug exactly where \parfillskip went, a simpler fix is to make \rightskip non zero, and if you uncomment the %\centering the warning goes away.
(I updated the name of \dim_to_decimal_in_unit:nn)
\documentclass{scrbook}
\usepackage[utf8]{inputenx}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{epstopdf}
\usepackage{subcaption}
\usepackage{gnuplottex}
\usepackage{xparse}
\ExplSyntaxOn
\DeclareExpandableDocumentCommand{\convertlen}{ O{cm} m }
 {
  \dim_to_decimal_in_unit:nn { #2 } { 1 #1 } cm
 }
\ExplSyntaxOff
%\showoutput
\showboxdepth3
\showboxbreadth10
\tracingonline1
\begin{document}
\begin{figure}[htbp]
 \centering
 \begin{subfigure}[b]{.45\textwidth}
%\centering
\begin{gnuplot}[terminal = cairolatex, terminaloptions = {size \convertlen{\textwidth},\convertlen{.3\textheight}}]
   plot sin(x)
  \end{gnuplot}
  \caption{A subfigure}
  \label{fig:1a}
 \end{subfigure}%
 \hfill
 \begin{subfigure}[b]{.45\textwidth}
\centering
  \begin{gnuplot}[terminal = cairolatex, terminaloptions = {size \convertlen{\textwidth},\convertlen{.3\textheight}}]
   plot sin(x)
  \end{gnuplot}
  \caption{Another subfigure}
  \label{fig:1b}
 \end{subfigure}
 \caption{A figure}\label{fig:1}
\end{figure}
\end{document}


text:
Q: Composite template being sent multiple times When sending out the composite email each Recipient is getting two status records generated and need to sign all documents twice.
I've tried changing the sequence to be incremented, and also moving the composite template to different places in the json constructed. Nothing seems to effect the number of times the signers are required to respond.
Here's the JSON output
{
    "emailSubject": "Documents",
    "emailBlurb": "Email subject, sign these documents",
    "templateId": "template 1 Id",
    "SourceId": "an opportunity Id",
    "envelopeIdStamping": "false",
    "templateRoles": [
        {
        "roleName": "Signer 1",
        "name": "First Signername",
        "email": "First Signer email",
        "recipientId": "first signers Id"
        },{
        "roleName": "Signer 2",
        "name": "Second Signername",
        "email": "Second Signer email",
        "recipientId": "second signers Id"
        }],
    "status": "sent",
    "notification":
        {
        "UseAccountDefaults": "true"
        },
    "compositeTemplates": [
        {
        "serverTemplates": [
            {
            "sequence": "1",
            "templateId": "template 1 Id"
            }
        ],
        "inlineTemplates": [
            {"sequence": "1",
            "customFields":
                {
                "textCustomFields":[
                    {
                    "value":"an opportunity Id",
                    "name":"Opportunity",
                    "configurationType":"salesforce"
                    },{
                    "value": "an opportunity Id",
                    "show": "false",
                    "required": "true",
                    "name": "DSFSSourceObjectId",
                    "fieldId": null
                    }]
                },
                "recipients":
                    {"signers":[
                        {"roleName": "Signer 1",
                        "name": "Second Signername",
                        "email": " Second Signer email",
                        "recipientId": "second signers Id"
                        },{
                        "roleName": "Signer 2",
                        "name": "First Signername",
                        "email": " First Signer email",
                        "recipientId": "first signers Id"
                        }]
                    }
            }]
        },{
        "serverTemplates": [
            {
            "sequence": "1",
            "templateId": "template 2 Id"
            }
        ],
        "inlineTemplates": [
            {
            "sequence": "1",
            "customFields":
                {
                "textCustomFields":[
                    {
                    "value":"an opportunity Id",
                    "name":"Opportunity",
                    "configurationType":"salesforce"
                    },{
                    "value": "an opportunity Id",
                    "show": "false",
                    "required": "true",
                    "name": "DSFSSourceObjectId",
                    "fieldId": null
                    }
                ]
                },
                "recipients":
                    {
                    "signers":[
                        {
                        "roleName": "Signer 1",
                        "name": "Second Signername",
                        "email": " Second Signer email",
                        "recipientId": "second signers Id"
                        },
                        {
                        "roleName": "Signer 2",
                        "name": "First Signername",
                        "email": " First Signer email",
                        "recipientId": "first signers Id"
                        }]
                    }
            }]
        },{
        "serverTemplates": [
            {
            "sequence": "1",
            "templateId": "template 3 Id"
            }
        ],
        "inlineTemplates": [
            {
            "sequence": "1",
            "customFields":
                {
                "textCustomFields":[
                    {
                    "value":"an opportunity Id",
                    "name":"Opportunity",
                    "configurationType":"salesforce"
                    },{
                    "value": "an opportunity Id",
                    "show": "false",
                    "required": "true",
                    "name": "DSFSSourceObjectId",
                    "fieldId": null
                    }
                ]
                },
                "recipients":
                    {
                    "signers":[
                        {
                        "roleName": "Signer 1",
                        "name": "Second Signername",
                        "email": " Second Signer email",
                        "recipientId": "second signers Id"
                        }]
                    }
            }]
        }
    ]
}

A: The TemplateRoles parameter in the root Envelope Definition should not be used with CompositeTemplates - You'll need to remove that.
Once that's gone, you'll want to check your ServerTemplates to confirm your signer roles are in alignment. In order for roles to merge correctly, both the RoleName and the RoutingOrder must match in all templates.


text:
Q: wheel colliders went bonkers (unity URP) I got a simple script for driving.
(https://www.youtube.com/watch?v=Z4HA8zJhGEk)
I used this script before everything ok.
I did everything like the youtuber but my wheel colliders are weird.
When ever I accelerated 10kmh or so my car would start shaking and flip over.
Why and how can it be fixed.
Thanks!

A: I had this problem a while back!
It's from the physics and not all of the wheels being aligned correctly.
Start from scratch using:
https://docs.unity3d.com/Manual/WheelColliderTutorial.html
Make sure all the coordinates are an exact match.
Then u can work off of that to match your transform.
Hope this helps!


text:
Q: Robocode - how to calculate rounds won at end of a battle? I thought I might be able to calculate the rounds won value by subtracting deaths from number of rounds, but my counters are not being incremented:
public void onRoundEnded(RoundEndedEvent event)
{
    roundCount++;
}

public void onDeath(DeathEvent event)
{
    deathCount++;
}

Not getting any compile errors or any other errors in the log. When I output the variables to the log in the onBattleEnded event, the output (after 100 rounds) is:
roundCount=1
deathCount=0

Full code below:
public class AB extends AdvancedRobot
{
    private int deathCount;
    private int roundCount;

    public void run()
    {
        while(true)
        {
            ahead(100);
            turnGunRight(360);
            back(100);
            turnGunRight(360);
        }
    }

    public void onScannedRobot(ScannedRobotEvent e)
    {
        fire(1);
    }

    public void onHitByBullet(HitByBulletEvent e)
    {
        back(10);
    }

    public void onHitWall(HitWallEvent e)
    {
        back(20);
    }

    public void onRoundEnded(RoundEndedEvent event)
    {
        roundCount++;
    }

    public void onDeath(DeathEvent event)
    {
        deathCount++;
    }

    public void onBattleEnded(BattleEndedEvent event)
    {
        System.out.println("roundCount=" + roundCount);
        System.out.println("deathCount=" + deathCount);
    }
}

Robocode version used is 1.9.2.6

A: So a new instance is created for each round. Making the fields static makes it a class variable, which is shared by each instance as well. You can find more information here.


text:
Q: SQL for Splitting a string by hyphen, and then generating all the suffixes for each chunk that is 3 or more chars in length? I am working with a Prefix Search engine, and I am trying to generate suffix keywords for my part numbers.
**Example String: 123456-7890-A-BCDEF-GHIJ-KL
I am looking to split this string into chunks, like this:
  123456
  7890
  A
  BCDEF
  GHIJ
  KL

Then I need to generate the suffixes of each chunk that is more that 3 chars in length, into one comma delimited list.

--For chunk 123456, I would get the suffixes 23456, 3456, 456, 56
--For chunk 7890, I would get the suffixes 890, 90
--For chunk A, it would be ignored as it is less than 3 chars in Length
--For chunk BCDEF, I would get the suffixes CDEF, DEF, EF
--For chunk GHIJ, I would get the suffixes HIJ, IJ
--For chunk KL, it would be ignored as it is less than 3 chars in Length

My string could have any amount of chars in each chunk, they are not always formatted like the example.
So the final result for string 123456-7890-A-BCDEF-GHIJ would look like this;
23456, 3456, 456, 56, 890, 90, CDEF, DEF, EF, HIJ, IJ

My string could have any amount of chars in each chunk, they are not always formatted like the example.
Some other example strings;
123-4567890-ABC-DEFGHIJ-K-L

--Result: 23, 567890, 67890, 7890, 890, 90, BC, EFGHIJ, FGHIJ, GHIJ, HIJ, IJ

123456-7-890AB-CDEFG-H-IJKL

--Result: 23456, 3456, 456, 56, 90AB, 0AB, AB, DEFG, EFG, FG, JKL, KL

A: I acknowledge this is not quite what you are looking for, but it is close. Perhaps this will give you or someone else an idea to get exactly what you want. This assumes SQL Server 2017 or higher.
So I am using STRING_SPLIT() to divide the string into one row for each chunk numbering those rows using ROW_NUMBER(). There is a problem with this in that STRING_SPLIT() does not guarantee order.
I then use a CTE to basically come up with index values to step through the each chunk from 2 to chunk length - 1 putting those strings back into a comma-separated list for each chunk using STRING_AGG().
I insert those results to a temp table so that I can select them in order by row number and assemble the suffixes from each chunk into the final comma-separated list.
DECLARE @MyString VARCHAR(50);
SET @MyString = '123456-7890-A-BCDEF-GHIJ';

WITH   cte
AS     (SELECT
          2 AS n -- anchor member
        , value
        , ROW_NUMBER() OVER (ORDER BY value) AS [rn]
        FROM STRING_SPLIT(@MyString, '-')
        WHERE LEN(value) >= 3
        UNION ALL
        SELECT
          n + 1
          , cte.value -- recursive member
          , cte.rn
        FROM   cte
        WHERE  n < (LEN(value) - 1) -- terminator
       )
SELECT STRING_AGG(SUBSTRING(value, n, LEN(value) - n + 1), ', ') as [Chunk]
INTO #Temp
FROM   cte
GROUP BY rn
ORDER BY rn;

SELECT STRING_AGG(Chunk, ', ')
FROM #Temp

Here is the dbfiddle.

A: There is probably a more elegant way to do this and likely better string manipulators than t-sql, but this seems to work: (requires DB to be compatibility mode = SQL 2016 or above to use STRING_SPLIT)
DECLARE @STRING     VARCHAR (100)
DECLARE @DIVIDEON   CHAR (1)
DECLARE @FULLSTRING VARCHAR (100)
DECLARE @SUBSTR     VARCHAR (100)
DECLARE @WRKSTRING  VARCHAR (100)
DECLARE @LEN        TINYINT

SELECT  @STRING = '123456-7-890AB-CDEFG-H-IJKL'
SELECT  @DIVIDEON = '-'
SELECT  @FULLSTRING =''

IF OBJECT_ID('tempdb..#mytable') IS NOT NULL
DROP TABLE #mytable

select RIGHT(value,LEN(value)-1) as MyString
into #mytable
from STRING_SPLIT (@STRING, @DIVIDEON)  -- only SQL 2016 and above
where len(value)>2 -- ignore subsets that do not have 3 or more chars

while exists (select MyString from #mytable)
begin
   select @WRKSTRING = (select top 1 MyString from #mytable)
   select @LEN = len(@WRKSTRING)
   select @SUBSTR=@WRKSTRING
   while @LEN>2
   begin
      select @SUBSTR=@SUBSTR+', '+RIGHT(@WRKSTRING,@LEN-1)
      select @LEN=@LEN-1
   end
   delete from #mytable where MyString = @WRKSTRING
   --select @SUBSTR as Fullstr
   select @FULLSTRING=@FULLSTRING+@SUBSTR+','

end
   select LEFT(@FULLSTRING,LEN(@FULLSTRING)-1)
drop table #mytable

A: --not performant...maybe good enough(?)
declare @t table
(
id int identity primary key clustered,
thecol varchar(40)
);

insert into @t(thecol)
values('1-2-3-4-5-6'), ('abcd') /*??*/;

insert into @t(thecol)
select top (10000) newid()
from master.dbo.spt_values as a
cross join master.dbo.spt_values as b;

select *,
thelist= replace(
cast('<!--'+replace(thecol, '-', '--><!--')+'-->' as xml).query('
let $seq := (2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20) (: note: max 22 chars per string-part:)
for $a in comment()
  let $str := string($a), $maxlen := string-length($str)-1
  for $i in $seq[. <= $maxlen]
    return concat(substring($str, $i, 100), "," )
').value('.', 'varchar(max)')+'_', ',_', '')
from @t;


text:
Q: Adb connection Error EOF + Sending jdwp tracking request failed In eclipse(latest version) when running my android project i get this DDMS error again and again:
Adb connection Error:EOF
[2014-03-06 11:44:58 - DeviceMonitor] Sending jdwp tracking request failed!
I have tried about everything
Killed the adb server, reseting it, cleaned the project, restarted, chmoded the file permissions to ddms and android files in the tools folder
Its driving me nuts...
My platform is mac osx ver:10.9.1
/Any help would be greatly appreciated


text:
Q: Notice: Undefined index: picCat in E:\xampp\htdocs\Evako\admin.php on line 313 if not in the form I choose my category returns an error :

Notice: Undefined index: picCat in E:\xampp\htdocs\Evako\admin.php on line 313

Code: form
<form class="form" method="GET">
            <input type="text" id="nmPic" name="nmPic" placeholder="име на снимката" onfocus="this.placeholder = ''" onblur="this.placeholder = 'име на снимката'">

                <input type="text" id="price" class="priceFrom" name="priceFrom" placeholder="цена от" onfocus="this.placeholder = ''" onblur="this.placeholder = 'цена от'">
                <input type="text" id="price" class="priceTo" name="priceTo" placeholder="цена до" onfocus="this.placeholder = ''" onblur="this.placeholder = 'цена до'">

                <select name="picCat" id="picCat">
                    <option value="" selected disabled>Изберете категория</option>
                    <option>Детски</option>
                    <option>Сватби</option>
                    <option>Рожден ден</option>
                    <option>18+</option>
                    <option>Други</option>
                </select>

                <input type="text" id="numPic" name="numPic" placeholder="номер на снимката" onfocus="this.placeholder = ''" onblur="this.placeholder = 'номер на снимката'">

                <input type="submit" name="showFilter" value="покажи" />
            </form>

And php:
if (isset($_GET["showFilter"]))
            {
                $picName = $_GET['nmPic'];
                $priceFrom = $_GET['priceFrom'];
                $priceTo = $_GET['priceTo'];
                $picCat = $_GET['picCat'];
                $numPic = $_GET['numPic'];

                $filter = " SELECT * FROM images WHERE status = '1'";
                if ($numPic && !empty($numPic)) {
                    $filter .= " AND id='$numPic'";
                }
                if ($picName && !empty($picName)) {
                    $filter .= " AND img_content='$picName'";
                }
                if ($picCat && !empty($picCat)) {
                    $filter .= " AND category='$picCat'";
                }
                if ($priceTo && !empty($priceTo)) {
                    $filter .= " AND price < '$priceTo'+1";
                }
                $resFilter = $connect->query($filter);

                if ($resFilter->num_rows > 0)
                {

                    while($row = mysqli_fetch_array($resFilter))
                    {

                        echo    "

№ ".$row['id']." | име: ".$row['img_content']." | категория: ".$row['category']." | цена: ".$row['price']."лв. | дата: ".$row['time']."ч.

";

                    }

                }

I can not understand where wrong to let me return this error. And if you choose a category everything works without a problem ...?
line 313 is:
$picCat = $_GET['picCat'];

Thank you.

A: Your select box option need value tag it would be
<select name="picCat" id="picCat">
                    <option value="" selected disabled>Изберете категория</option>
                    <option value="Детски">Детски</option>
                    <option value="Сватби">Сватби</option>
                    <option value="Рожден ден">Рожден ден</option>
                    <option value="18+">18+</option>
                    <option value="Други">Други</option>
                </select>

Read html select tag
Youe script is open for sql injection read How can I prevent SQL injection in PHP? to prevent it


text:
Q: pdflatex stops when both german and hungarian languages are set in babel This is a MWE:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[german,hungarian]{babel}

\begin{document}

babel test

\end{document}

When I run pdflatex on this MWE the program stops with:
pdflatex babel-test.tex
This is pdfTeX, Version 3.141592653-2.6-1.40.24 (TeX Live 2022) (preloaded format=pdflatex)
 restricted \write18 enabled.
entering extended mode
(./babel-test.tex
LaTeX2e <2021-11-15> patch level 1
L3 programming layer <2022-04-10>
(/usr/local/texlive/2022/texmf-dist/tex/latex/base/article.cls
Document Class: article 2021/10/04 v1.4n Standard LaTeX document class
(/usr/local/texlive/2022/texmf-dist/tex/latex/base/size10.clo))
(/usr/local/texlive/2022/texmf-dist/tex/latex/base/fontenc.sty)
(/usr/local/texlive/2022/texmf-dist/tex/latex/base/inputenc.sty)
(/usr/local/texlive/2022/texmf-dist/tex/generic/babel/babel.sty
(/usr/local/texlive/2022/texmf-dist/tex/generic/babel/txtbabel.def)
(/usr/local/texlive/2022/texmf-dist/tex/generic/babel-german/german.ldf
(/usr/local/texlive/2022/texmf-dist/tex/generic/babel-german/germanb.ldf))
(/usr/local/texlive/2022/texmf-dist/tex/generic/babel-hungarian/magyar.ldf))
(/usr/local/texlive/2022/texmf-dist/tex/latex/l3backend/l3backend-pdftex.def)
(./babel-test.aux)
(/usr/local/texlive/2022/texmf-dist/tex/latex/base/article.cls) [1{/usr/local
/texlive/2022/texmf-var/fonts/map/pdftex/updmap/pdftex.map}]
(./babel-test.aux
! Missing number, treated as zero.
<to be read again>
                   \hskip
l.4 \catcode `"
               \active
?

Why is this and how can I fix it?
I have freshly installed TeXLive 2022 on linux.
Thanks.

A: magyar.ldf patches the (internal) latex command \@begindocumenthook to inject some code into the aux-file:
{\toks@\expandafter{\expandafter\@@magyar@protect@backtick\@begindocumenthook}%
   \xdef\@begindocumenthook{\the\toks@}}% Dat: \@begindocumenthook has #1 #2 etc.

With the introduction of the new hook system in latex this no longer works as intended. The catcode change is to late.
The author has been notified two years ago about this but magyar.ldf has not been adapted.
As a work-around you can reset the problematic catcode before \begin{document}:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[german,hungarian]{babel}

\AddToHook{begindocument}[test]{\catcode\string``=12 }
\DeclareHookRule{begindocument}{test}{before}{babel}

\begin{document}
babel test
\end{document}

I removed the inputenc line as it is no longer needed: utf8 is the default since a few years.


text:
Q: ASP.NET Core dependency injection c# how to instantiate classes? I created a class
public class DefaultLogin
{
    [Inject]
    public UserManager<ApplicationUser> userManager { get; set; }

    public DefaultLogin(UserManager<ApplicationUser> userManager)
    {
        this.userManager = userManager;
    }
}

I tryed to use the [Inject] Attribute for resolve the UserManager<ApplicationUser>. But it not worked. I'm not sure why it can be sometimes used like in classed derived from ComponentBase. Maybe someone know why?
So Inject Attribute not working. I remove [Inject] and make a constructor instead of [Inject] like in the code above. My Question now is how i can instantiate DefaultLogin class?
I can't do:
new DefaultLogin();

I not want to do this:
 serviceCollection.AddScoped<DefaultLogin>();

I want to do something like this (Extension class):
    public static void UseDefaultLogin(this IApplicationBuilder app)
    {
        var configuration = (IConfiguration) app.ApplicationServices.GetService(typeof(IConfiguration));
        var userManager = (UserManager<ApplicationUser>) app.ApplicationServices.GetService(typeof(UserManager<ApplicationUser>));
        string defaultUserUserName = configuration["DefaultUser:UserName"];
        string defaultUserEmail = configuration["DefaultUser:Email"];
        string defaultUserPassword = configuration["DefaultUser:Password"];
        if (userManager.FindByEmailAsync(defaultUserEmail).Result == null)
        {
            ApplicationUser user = new ApplicationUser
            {
                UserName = defaultUserUserName,
                Email = defaultUserEmail ?? defaultUserUserName
            };

            IdentityResult result = userManager.CreateAsync(user, defaultUserPassword).Result;
            if (result.Succeeded)
            {
                userManager.AddToRoleAsync(user, "Admin").Wait();
            }
        }
    }

IConfiguration can be resolved.
But UserManager<ApplicationUser> not,
Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[InfoApp.Repository.ApplicationUser]' from root provider
I call  app.UseDefaultLogin(); at end of Configure method in Startup class.

A: You'll have to go with the second method, with constructor injection.
To use a DefaultLogin object, you can do the same thing in the classes where you need it.
So let's say you have a LoginController. This should work:
public class LoginController : ControllerBase
{

   private readonly DefaultLogin _defaultLogin;

   public LoginController(DefaultLogin defaultLogin)
   {
      _defaultLogin = defaultLogin;
   }
}

Note: General rule of thumb is to hold the injected references as fields, not as properties.


text:
Q: Service Fabric set instance count -1 I see the web instance count is set to -1. What does -1 mean?
<Parameter Name="Web1_InstanceCount" Value="-1" />

A: In you example, -1 means just a parameter value, out of context it does not mean anything. By the name of your variable, it is a parameter likely to be used on service declaration on your ApplicationManifest.xml.
You will probably have something like this:
<?xml version="1.0" encoding="utf-8"?>
<ApplicationManifest ApplicationTypeName="MyAppTypeName" ApplicationTypeVersion="1.0.0" xmlns=...>
  <Parameters>
    <Parameter Name="Web1_InstanceCount" Value="-1" />
    <Parameter Name="FEPlacementConstraints" Value="NodeTypeName==FrontEnd" />
  </Parameters>
  <ServiceManifestImport>
    <ServiceManifestRef ServiceManifestName="MyServicePkg" ServiceManifestVersion="1.0.0" />
    <ConfigOverrides />
  </ServiceManifestImport>
  <DefaultServices>
    <Service Name="Web1">
      <StatelessService ServiceTypeName="MyServiceType" InstanceCount="[Web1_InstanceCount]">
        <SingletonPartition />
        <PlacementConstraints>[FEPlacementConstraints]</PlacementConstraints>
      </StatelessService>
    </Service>
  </DefaultServices>
</ApplicationManifest>

If you pay attention, at the beggining your define the parameters, and at the bottom you use them enclosed by [ ] when declaring the services.
Now, regarding the meaning of the value -1.
-1 is a dynamic instance count, that means that the number of instances of your named service(Web1) will scale dynamically with the number of valid nodes available. Pay attention here to 'valid nodes available' not 'all nodes'
Why valid nodes available?

*

*Let's assume you have 2 node types, FrontEnd & BackEnd. If you add a placement constraints to your service to run only on FrontEnd (like in the example) your service will run on all nodes where the type is 'FrontEnd'.

*The other point is the number of instances will change every time the number of valid nodes available(those that fits your service rules), for example, you scale up/down the number of nodes in a node type scale set. Some nodes fails, or some rules changes, for example, you create a rule based on node labels and these labels change.

You can find more info here

A: A Service Fabric cluster consist of one or more nodes (For testing/development purposes it can have 1 or 3 nodes, production environments typically have >= 5 nodes). When the Web1 service is deployed, it will run on x nodes where x is determined by the value of Web1_InstanceCount.
When to value is set to -1 the service will be deployed to all nodes.
Traffic will be routed to one of the instances of Web1 running on a node in a round robin fashion.
I strongly advice to read this part of the docs.

Scaling by creating or removing stateless service instances
One of the simplest ways to scale within Service Fabric works with stateless services. When you create a stateless service, you get a chance to define an InstanceCount. InstanceCount defines how many running copies of that service's code are created when the service starts up. Let's say, for example, that there are 100 nodes in the cluster. Let's also say that a service is created with an InstanceCount of 10. During runtime, those 10 running copies of the code could all become too busy (or could be not busy enough). One way to scale that workload is to change the number of instances. For example, some piece of monitoring or management code can change the existing number of instances to 50, or to 5, depending on whether the workload needs to scale in or out based on the load.

A: Its mean -1 is the default value of instance count of an service. So Service Fabric will run it on all node. So if you have 5 nodes then SF will deploy that service into 5 nodes. You then can use Load Balancer or Reverse proxy to direct your traffic to each node
More info here
https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-concepts-scalability


text:
Q: Emacs ignores Ctrl+/ keystroke When I run emacs on an ssh session to a Linux box via Terminal.app, it ignores Ctrl + / key combo (undo). How to stop this?

A: This is part of the reason I don't use Terminal.app anymore and use rxvt under Xquartz. You'll need a way to either modify the way Terminal.app handles ctrl/meta character (this question has a solution for that), or use an alternate term application.


text:
Q: VBA - Pasting only specific columns from array following a question I have asked recently I have created an array to copy data from one worksheet to another. My problem is that the array includes many columns I do not need in the new worksheet.
x = Sheets("Sheet1").Range("A1048576").End(xlUp).Row
Set my_range = Sheets("Sheet1").Range("A2:AM" & x)
DirArray = my_range

Sheets("Sheet2").Select

Set Destination = Range("A3")
Destination.Resize(UBound(DirArray, 1), UBound(DirArray, 2)).Value = DirArray

This code copies all the data from the array but I only want specific columns from the array. How would I have to go about this to get only columns A:E, AA, L, M:K?
Any help is appreciated. Thanks in advance.

A: Well if you are going to use arrays, then maybe something along these lines might help:
Sub foo()
    Dim ColumnAarray() As Variant
    Dim my_Arange As Range
    LastRow = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row

    'Get one column's data
    Set my_Arange = Sheets("Sheet1").Range("A2:A" & LastRow) ' get specific column
    ReDim ColumnAarray(LastRow) 'Re size your array to fit data
    ColumnAarray = my_Arange 'add data to array
    ''
    ''Repeat the process to copy more columns

    ''
    Set Destination = Sheet2.Range("A3")
    Destination.Resize(UBound(ColumnAarray, 1), UBound(ColumnAarray, 2)).Value = ColumnAarray 'add column A to Range A3 on Sheet2
End Sub

Or where you go about pasting the array values, you could change this to only paste specific columns from your original range... such as:
Sub foo()
    Dim ColumnAarray() As Variant
    Dim my_Arange As Range
    LastRow = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row
    Set my_Arange = Sheets("Sheet1").Range("A2:AM" & LastRow) ' get specific range
    ReDim ColumnAarray(LastRow) 'Re size your array to fit data
    ColumnAarray = my_Arange 'add data to array

    For i = LBound(ColumnAarray) To UBound(ColumnAarray)
        Sheet2.Range("A" & i) = ColumnAarray(i, 1) 'paste first column from original range
        Sheet2.Range("B" & i) = ColumnAarray(i, 2) 'paste second column from original range into column B in Sheet 2
    Next i
End Sub


text:
Q: Challenging Recursion Question - Tree Nodes Representing Processes Thank you for reading this thread. I have a challenging question regarding using tree nodes to represent system processes.
Below is what my code has to print out when the tree nodes of the below processes are already connected like below,
1000
  1001
        100101
            10010101
                 1001010101
  100102
          10010201
  1002
  1003
  1004
As you can see, 1000 is the root process, it has 4 child processes, 1001, 1002, 1003 and 1004. Processes 100101 is child of 1001, 10010101 is child process of 100101 and 1001010101 is child process of 10010101.
Despite root having 4 child processes, to get from root to the first child process, it is root->child_node. Child process 1001 has "next" process of 1002, and 1002 has next process 1003 and it has 1004 as 1003's next process. Therefore, to at to each child process on the same level, it has to go from one child process to the next child process using next_node.
Below is the result my code generates. Each process, such as 1000, is a TreeNode. Right now, my code can print from 1000 to 1001010101, such as below,
1000
  1001
        100101
            10010101
                 1001010101
However, my current issue is how do I handle the next (neighboring node), such as 1001 and 1002 are neighbors because 1001's next_node is 1002.
// Tree Node.
struct TreeNode {
    pid_t pid;
    char *name;
    struct TreeNode *child_node;     // A list of child processes
    struct TreeNode *next_node;    // A link to the next sibling processes.

};
// My print_processes method.
void print_processes(struct TreeNode *root, int space_level, int level_limit) {

    int i;

    for (i = 0; i < space_level; i++) {
        sleep(1);
        printf("  ");
    }

    printf("%d: %s\n", root->pid, root->name);

    struct TreeNode *node;

    while ((node = root->child_node) != NULL && level_limit != 0) {
        print_processes(node, space_level + 1, level_limit - 1);

    }

    //printf("hoho");
    exit(0);
}

int main(int argc, char **argv) {

struct TreeNode *root = malloc (sizeof (struct TreeNode));
root->pid = 1000;
root->name = "sshd";
root->child_node = NULL;
root->next_node = NULL;

struct TreeNode *c1 = malloc (sizeof (struct TreeNode));
c1->pid = 1001;
c1->name = "sshd";
c1->child_node = NULL;
c1->next_node = NULL;

struct TreeNode *c2 = malloc (sizeof (struct TreeNode));
c2->pid = 1002;
c2->name = "bash";
c2->child_node = NULL;
c2->next_node = NULL;

struct TreeNode *c3 = malloc (sizeof (struct TreeNode));
c3->pid = 1003;
c3->name = "sshd";
c3->child_node = NULL;
c3->next_node = NULL;

struct TreeNode *c4 = malloc (sizeof (struct TreeNode));
c4->pid = 1004;
c4->name = "sshd";
c4->child_node = NULL;
c4->next_node = NULL;

struct TreeNode *c5 = malloc (sizeof (struct TreeNode));
c5->pid = 1005;
c5->name = "bash";
c5->child_node = NULL;
c5->next_node = NULL;

struct TreeNode *n1 = malloc (sizeof (struct TreeNode));
n1->pid = 1011;
n1->name = "bash";
n1->child_node = NULL;
n1->next_node = NULL;

c4->child_node = c5;
c3->child_node = c4;
c2->child_node = c3;
c1->child_node = c2;
c1->next_node = n1;
root->child_node = c1;

print_processes(root, 0, 3);

return 0;

}
Again, below is what my code has to generate in Terminal.
1000
  1001
        100101
            10010101
                 1001010101
  100102
          10010201
  1002
  1003
  1004
Thank you for reading this question.

A: You can simplify and extend print_processes() quite a lot, and definitely make the main() function a lot shorter too:
#include <stdio.h>

struct TreeNode
{
    int    pid;
    char  *name;
    struct TreeNode *child_node;     // A list of child processes
    struct TreeNode *next_node;    // A link to the next sibling processes.
};

static
void print_processes(struct TreeNode *root, int space_level, int level_limit)
{
    for (int i = 0; i < space_level; i++)
        printf("  ");

    printf("%d: %s\n", root->pid, root->name);

    if (root->child_node != NULL && level_limit > 0)
        print_processes(root->child_node, space_level + 1, level_limit - 1);
    if (root->next_node != NULL)
        print_processes(root->next_node, space_level, level_limit);
}

int main(void)
{
    struct TreeNode n1   = { 1011, "bash",   NULL, NULL };
    struct TreeNode c5   = { 1005, "bash",   NULL, NULL };
    struct TreeNode c4   = { 1004, "sshd-3", &c5,  NULL };
    struct TreeNode c3   = { 1003, "sshd-2", &c4,  NULL };
    struct TreeNode c2   = { 1002, "bash",   &c3,  NULL };
    struct TreeNode c1   = { 1001, "sshd-1", &c2,  &n1  };
    struct TreeNode root = { 1000, "sshd",   &c1,  NULL };

    print_processes(&root, 0, 3);

    return 0;
}

Output:
1000: sshd
  1001: sshd-1
    1002: bash
      1003: sshd-2
  1011: bash

For the sake of reducing the #include lines to 1, I changed pid_t into int.


text:
Q: Error al cambiar permisos - Tinymce: Responsive FileManager Al parecer, tengo bien integrado ResponsiveFilemanager con TinyMCE, pero al cambiar los permisos de archivos y directorios, se genera un error, y no muestra el mensaje que le corresponde que sería algo como: No tiene permisos.
Específicamente solo he dejado que el usuario cargue archivos y cree directorios, pero nada de mover, copiar, pegar, cortar, editar, eliminar.
Entonces, por ejemplo, cuando intento mover un archivo, se generaron errores con el archivo execute.php, ajax_calls.php, y siempre anda con una variable $_POST[ 'path' ], como undefined index.
Algo curioso que descubrí fue que al dejar el privilegio de rename_files en true, todo funcionaba normalmente. Pareciera que hubiera un conflicto con ese parámetro de configuración.

case 'copy_cut':
    if($_POST[sub] != 'copy' && $_POST['sub_action'] != 'cut')
    {
        response(trans('wrong sub-action').AddErrorLocation())->send();
        exit;
    }
    if (strpos($_POST['path'],'../') !==FALSE
        || strpos($_POST['path'],'./') !==FALSE
        || strpos($_POST['path'],'..\\') !==FALSE
        || strpos($_POST['path'],'.\\') !==FALSE
    {
        response(trans('wrong path'.AddErrorLocation()))->send();
        exit;
    }
    if(trim($_POST['path']) == '')
    {
        response(trans('no path').AddErrorLocation())->send();
    }
    $msg_sub_action = ($_POST['sub_action'] == 'copy' ? trans('Copy') : trans('Cut') );
    $path = $current_path . $_POST['path'];

    if (is_dir($path))
    {
        // can't copy/cut dirs
        if($copy_cut_dirs === false)
        {
            response(sprintf(trans('Copy_Cut_Not_Allowed'), $msg_sub_action, trans('Folders')).AddErrorLocation())->send();
            //...
        }
        //...
    }
    //...


text:
Q: Is it possible to link to another function in Swift documentation? Say I have two functions that are documented like this:
/**
 Fetches something.

 - PostCondition: 'displaySomething()' is called by the presenter
*/
func fetchSomething() {
    interactor?.fetchSomething()
}

/**
 Displays something.

 - Parameter viewModel: A viewmodel containing the parsed data
*/
func displaySomething(viewModel: ViewModel) {
    text = viewModel.text
}

Is there a way to make the reference to displaySomething() in the fetchSomething() documentation link to the actual function so that it is clickable in quick help? As far as I can tell it is currently only possible to link to web pages.


text:
Q: Writing and reading to a memory mapped file in OCaml I am experimenting in OCaml to see how I can read/write a numerical array to/from a memory mapped file.
I think I'll need to use Bigarray but not sure how to write down a Bigarray array to a memory mapped file, and then read it back?
I cannot seem to find an example anywhere. I have checked the source code of Jane St. core but to no avail.

A: Since it seems like you're interested in using core:
Here's map_file from their docs (https://ocaml.janestreet.com/ocaml-core/109.58.00/doc/core/#Bigstring)
val map_file : shared:bool -> Unix.file_descr -> int -> t

map_file shared fd n memory-maps n characters of the data associated with descriptor fd to a bigstring. Iff shared is true, all changes to the bigstring will be reflected in the file.

You should accept the answer Jonathan creates however.

A: I'm making this an answer (I was originally afraid that I missed your point). The OCaml library provides a mechanism for this by default, namely, the map_file function from the Bigarray.Genarray module. It does precisely what you want and amounts to mmap'ing the file under Unix. I'm unsure about the Windows specifics.
This has the advantage of being well-supported and well-tested, as well as not requiring you to import JaneSt's Core into your project if you didn't need it already.


text:
Q: cutting titles/features/subvideos out of a VOB file using ffmpeg I have a VOB video file obtained from a DVD. The video contains several separate subvideos from the DVD, which play one-after-another (e.g., the first subvideo is the main feature, the second subvideo is a bonus feature, the third subvideo is another bonus feature, etc.). So when I play the VOB file using a program such as VLC, the time display starts at 00:00, and then resets to 00:00 several times throughout the video when each of the subvideos begins. Also note that I'm not sure if the correct term for "subvideo" is "title", "feature", or something else.
Since the start times of each subvideo are somehow embedded in the VOB file, is there a way to use ffmpeg to automatically cut these subvideos out of the video into separate VOB files? I'm trying to avoid having to cut them out manually by specifying their start and end timepoints via the -ss and -to options, which is tedious.

A: A fork of ffmpeg can help :
vgtMPEG which is based on FFmpeg and makes it easy to extract individual titles, chapters and language tags from DVD and BD.
To show tracks, chapters and titles :
vgtmpeg.exe -i dvd://d:\
and to extract for example data from title #10 :
vgtmpeg.exe -i dvd://d:\?title=10 -map 0:v -map 0:a -map 0:s -c copy -f dvd title10.mpg -f ffmetadata title10.chap


text:
Q: Cannot connect to MemSQL through SQLApi++ I'm trying to connect to MemSQL database from c++ code and I'm using SQLApi++ library. MySQL client is compatible with MemSQL and SQLApi++ has support of MySQL. However I can't connect and get different errors.
For example, I'm calling connect with the following parameters
Connect("tcp://localhost:3307", "root", "", SA_MySQL_Client)

and get an error saying Access denied for user 'root'@'localhost' (using password: NO).
I have searched on the internet and tried several versions of specifying DB hostname, however non of them have worked. What am I doing wrong? What is the correct version? Any Ideas?
NOTE: I can successfully connect to MemSQL with command-line by just executing
memsql -P 3307.

A: Do you have MySQL installed on the same machine as MemSQL?  localhost can redirect to MySQL in some clients, but 127.0.0.1 won't (see https://docs.memsql.com/v5.7/docs/how-to-connect-to-memsql)
Does Connect("tcp://127.0.0.1:3307", "root", "", "SA_MySQL_Client") work?

A: When I provided local IP address and port, for some reason SQLApi++ ignored it and always tried to connect to MySQL's socket in default path (i.e. /var/lib/mysql/mysql.sock).
However, after reading documentation once more, it turned out that it is possible to pass socket's path as a host name. So I passed MemSQL's socket path and it worked!

A: I faced the same issue, and nabroyan has already mentioned one solution. Just providing some details on it and adding another possible solution as well.
Seems like when SQLAPI figures out that the server is running on local host, then it goes directly to the socket file, and unfortunately it always goes to the MySQL's socket file i.e. /var/lib/mysql/mysql.sock
Now there can be two possible solutions here:
1- Update your MemSQL instance to use the same socket file as that of MySQL (it may only be a choice if you are not running MySQL as well on that same box)
(haven't tested it myself, so maybe missing some steps here) You can probably do this by updating the value of "socket" in memsql.cnf file, so it should look like:
socket = /var/lib/mysql/mysql.sock
You can find the location of memsql.cnf file using the command that is used to figure out the socket file location, memsql.cnf file will be in the same directory:
memsql -u root --password=YOUR_PASSWORD_HERE -P 3306 -e "show variables like 'socket'"

Once done, you should restart the memsql:
memsql-ops memsql-restart

2- OR Modify your connection string to provide the MemSQL socket path.
You can figure out memsql socket file using the command mentioned under first option.
In my case the file was : /app/memsql/master-3306-NJG846fb0e/data/memsql.sock
so I modified my connection call to use this file:
Connect("/app/memsql/master-3306-NJG846fb0e/data/memsql.sock@", "myuser", "mypassword", SA_MySQL_Client);


text:
Q: ERROR ITMS-4134: "Duplicate in-app purchase product_id: '010'." at Software/SoftwareMetadata My app already has a few non consumable in-app purchase without content hosting. One of them has product id 010.
I have created a new in-app purchase with content hosting, when I try to upload the content via Application Loader I get this:
ERROR ITMS-4134: "Duplicate in-app purchase product_id: '010'." at Software/SoftwareMetadata

The ContentInfo.plist of the uploading content contains:
IAPProductIdentifier: T01
Where am I wrong?

A: Unfortunately, once you've created an In-App purchase product, it seems that the ID is stored permanently, even after your remove it). You have to create a new ID


text:
Q: Solve quadratic equations modulo prime powers To find if $x^2 = a \mod p$, I use the Tonelli-Shanks algorithm. However, how do I find the roots for $x^2 = a \mod p^t$, if I have solved the previous equation?
Thanks

A: We can use a special case of Hensel lifting. We show how to lift a $b_1$ such that $b_1^2\equiv a\pmod{p}$ to a solution of $x^2\equiv a\pmod{p^2}$. Let $p$ be an odd prime.
Any solution of $x^2\equiv a\pmod{p^2}$ which is congruent to $b_1$ modulo $p$ has the shape $b_1+tp$. Square this. We want to have $b_1^2+2b_1tp+p^2\equiv a\pmod{p^2}$, so we want
$$2b_1tp\equiv a-b_1^2\pmod{p^2}.$$
Note that $p$ divides $a-b_1^2$. Let $a-b_1^2=cp$. We want to solve
$$2b_1t\equiv c\pmod{p}.$$
This is cheap to solve for $t$.
Now we have found a $b_2$ such that $b_2^2\equiv a \pod{p^2}$. We can lift this to a solution $b_3$ of $x^2\equiv a\pmod{p^3}$ by using the same method. Any such solution congruent to $b_2$ modulo $p^2$ has the shape $b_2+tp^2$. Continue.


text:
Q: How is the AKS primality test Rosetta code so simple? Skip to the end to see alternative question.
The following is a Python implementation of the AKS Primality Test.
from sympy import *

def expand_x_1(n):
    # This version uses a generator and thus less computations
    c = 1
    for i in range(n//2 + 1):       # // means flooring after divide
        c = c*(n - i)//(i + 1)
        yield c

def aks(p):
    if p==2:
        return True

    for i in expand_x_1(p):
        if i % p:
            # we stop without computing all possible solutions
            return False
    return True

for n in range(2, 10000):
    primality = aks(n)
    primality1 = isprime(n)
    if primality != primality1:
        print("Fails @", n)  # Never prints
        assert (0)
    else:
        print(primality)

How is it possible that they took that much more in-depth pseudocode of the algorithm (that involves polynomial operations), and converted it into this 10-line version?
Is the above really the AKS primality test?  I got it from:
https://rosettacode.org/wiki/AKS_test_for_primes#Python

Let the input be called $n$, not $p$.
The code in expand_x_1(n) must be computing:
$$c_0 = 1, c_i = \lfloor \dfrac{c_{i-1}(n-i)}{i + 1}\rfloor$$
Where $c_i = $ the $i$th yielded value.  The other code using this value simply tests whether $c_i \neq 0 \pmod n$, in which case (if true) it returns False for composite.  Else if for all $c_i$ values at $i = 0..\lfloor \dfrac{n}{2} \rfloor + 1$ we have $c_i = 0 \pmod n$, then True is returned.
The recursion plus this test don't seem at all like what makes up the AKS algorithm.  So I was hoping an analytic number theorist could explain the formula.
Alternatively, if you can't answer the above, then:
How can we study the formula for $c_i$; can you think of any rearrangments it has? Such as maybe the denominators combining across recursive subcalls that have floor etc.
This is so I don't have to open up another question regarding this formula.

For example, I modified the code to:
def expand_x_1(n):
   c = 1
   d = 1
   for i in range(n//2 + 1):
       d *= (i + 1)
       c = c*(n - i)
       yield c//d

Therefore, since it's getting no failures when I run it, I can somewhat safely assume that "denominators can be combined" algebraically, i.e. there is some
identity made use of that derives from the basic properties of floor.
What else can we say and how does this formula relate to polynomial arithmetic?

A: The numbers you've labelled as $c_i$ are the binomial coefficients $\binom ni$; the code checks whether $\binom ni \equiv 0 \pmod n$ for all $0 < i \le \frac n2$.  This is not the AKS algorithm.  It's the exponential-time brute force algorithm listed in the Wikipedia article to motivate the AKS algorithm.


text:
Q: xml schema - single and multi element occurrence I have an XML schema with my "video" element and "youtube" element inside:
<xs:element name="video">
  <xs:complexType>
    <xs:sequence>
      <xs:element ref="youtube" minOccurs="0" maxOccurs="1"/>
    </xs:sequence>
    <xs:attribute name="file" type="xs:string"/>
  </xs:complexType>
</xs:element>

and I want to add to available video types another element "param":
<xs:element name="param">
   <xs:complexType>
     <xs:attribute name="name" type="xs:string" use="required"/>
     <xs:attribute name="value" type="xs:string" use="required"/>
   </xs:complexType>
</xs:element>

I would have "param" element inside next to "youtube".
Restrictions:

*

*youtube can occur only one time in my xml

*param - can occur many times in my xml

like this:
<video>
<youtube file = "aaa"/>
<param name="a1" value"b1"/>
<param name="a2" value"b2"/>
</video>

How to maintain this restrictions in this schema?
If I do something like this:
<xs:sequence>
      <xs:element ref="youtube" minOccurs="0" maxOccurs="1"/>
      <xs:element ref="param" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>

if the sequence is specified like this
<xs:sequence>
      <xs:element ref="youtube" minOccurs="0" maxOccurs="1"/>
      <xs:element ref="param" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>

it determines that param has to be after youtube - but I don't want to specify the sequence

A: Here is XSD schema:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="video">
        <xs:complexType>
            <xs:choice minOccurs="1" maxOccurs="2">
                <xs:element ref="youtube"/>
                <xs:element ref="param" minOccurs="1" maxOccurs="unbounded"/>
            </xs:choice>
        </xs:complexType>
    </xs:element>

    <xs:element name="youtube">
        <xs:complexType>
            <xs:attribute name="file" type="xs:string" use="required"/>
        </xs:complexType>
    </xs:element>

    <xs:element name="param">
        <xs:complexType>
            <xs:attribute name="name" type="xs:string" use="required"/>
            <xs:attribute name="value" type="xs:string" use="required"/>
        </xs:complexType>
    </xs:element>
</xs:schema>

Example (well-formed and valid) XML:
<?xml version="1.0" encoding="UTF-8"?>
<video>
    <youtube file="aaa"/>
    <param name="a1" value="b1"/>
    <param name="a2" value="b2"/>
</video>

There is one issue with above solution. xs:choice allows two youtube elements. There is xs:all element, which solve that, but unfortunately it's impossible to get param's maxOccurs more than one with it (xs:all limitation).
In other words there is no 100% solution using XML Schema 1.0. If above is not sufficient you can use another schema language such as RELAX NG or Schematron.
edit:
In XML Schema 1.1 (superset of XML Schema 1.0) you can write video element as:
<xs:element name="video">
    <xs:complexType>
        <xs:all>
            <xs:element ref="youtube"/>
            <xs:element ref="param" minOccurs="0" maxOccurs="unbounded"/>
        </xs:all>
    </xs:complexType>
</xs:element>


text:
Q: Dimension of range of an function Let $f$ be a rational function from affine variety $X$ to affine variety $Y$. Is it always true that $\dim X \geq \dim f(X)$? If it is can someone provide me with a proof of it? To me, this is intuitively true.
Also, is this true for functions in general?

A: It is true if $X$ and $f(X)$ are locally noetherian schemes, and $f$ is an open or closed morphism.  See (EGA, IV_2, 5.4.1).  Here is the proof when $f$ is open.
By the definition of dimension it is sufficient to prove that for every sequence $(y_i)$ $(0 \le i \le n)$ of distinct points of $f(X)$ with $y_i \in \overline{\{ y_{i+1}\}}$ for $0 \le i \le n-1$, there exists a sequence $(x_i)$ $(0 \le i \le n)$ of points of $X$ such that $x_i \in \overline{\{x_{i+1}\}}$ for $0 \le i \le n-1$ and $f(x_i) = y_i$ for all $i$.  The existence of $x_0 \in X$ is clear.  Suppose that the points $x_i$ are determined for $i \le m$.  Since $f$ is open, and $y_m$ is a specialization of $y_{m+1}$, there exists a point $x_{m+1} \in f^{-1}(y_{m+1})$ such that $x_m$ is a specialization of it.  This last fact can be seen by reducing to the affine case.  Hence the claim follows inductively.


text:
Q: graphframes for pySpark v3.0.1 I'm trying to use the graphframes library with pySpark v3.0.1. (I'm using vscode on debian but trying to import the package from pyspark shell didn't work either)
According to the documentation, using $ pyspark --packages graphframes:graphframes:0.6.0-spark2.3-s_2.11 I should be able to work with it.
This sample code was taken from another post in StackOverflow posing the same question, although its solution didn't do the trick for me.
localVertices = [(1,"A"), (2,"B"), (3, "C")]

localEdges = [(1,2,"love"), (2,1,"hate"), (2,3,"follow")]

v = sqlContext.createDataFrame(localVertices, ["id", "name"])

e = sqlContext.createDataFrame(localEdges, ["src", "dst", "action"])

g = GraphFrame(v, e)

throws error
py4j.protocol.Py4JJavaError: An error occurred while calling o63.createGraph.

java.lang.NoSuchMethodError: 'scala.collection.mutable.ArrayOps scala.Predef$.refArrayOps(java.lang.Object[])'

A: You need to use the correct graphframes version for Spark 3.0. You have used the graphframes for Spark 2.3 (0.6.0-spark2.3-s_2.11), which caused a Spark version conflict. You can try 0.8.1-spark3.0-s_2.12, which is currently the latest version of graphframes for Spark 3.0.
pyspark --packages graphframes:graphframes:0.8.1-spark3.0-s_2.12


text:
Q: Passing list index as an argument in subprocess.call() I'm not sure what's wrong here. I'm getting 0 0 0 0 as a output.
#!/usr/bin/env python3

import subprocess

fourletterwords = ["srvr", "stat", "mntr"]

for fourlw in fourletterwords:

    output = subprocess.call("echo {fourlw} | nc localhost 2181", shell=True)

    print (output)

A: The return value of subprocess.call() is the the return code, i.e. the exit status, of the call, not the output.  Try using subprocess.check_output() instead:
output = subprocess.check_output(f"echo {fourlw} | nc localhost 2181", shell=True)

See the docs here


text:
Q: What is the benefit of having a whole program contained in a class? Sometimes, when looking at Python code examples, I'll come across one where the whole program is contained within its own class, and almost every function of the program is actually a method of that class apart from a 'main' function.
Because it's a fairly new concept to me, I can't easily find an example even though I've seen it before, so I hope someone understands what I am referring to.
I know how classes can be used outside of the rest of a program's functions, but what is the advantage of using them in this way compared with having functions on their own?
Also, can/should a separate module with no function calls be structured using a class in this way?

A: A module is preferred when it is a collection of pure functions i.e. no shared state like module level variables. A big class is often used when there are multiple functions operating on a shared state.
In Python scripts, you will often see the pattern of the main function being just the instantiation of a class and calling a method for e.g youtube-dl. This is done for various reasons:

*

*Can instantiate multiple objects without mixing state. It is easier to make it threadsafe.

*Classes can be inherited or composed (for e.g. see BaseHTTPRequestHandler

*Classes have more features than modules like constructors, iteration support etc.

In general, classes offer more power with slight added complexity. Some people prefer functions for simplicity esp in the case of one-time scripts. The tradeoff is upto the developer and both are valid options in Python.

A: A program often has to maintain state and share resources between functions (command line options, dB connection, etc). When that's the case a class is usually a better solution (wrt/ readability, testability and overall maintainability) than having to pass the whole context to every function or (worse) using global state.


text:
Q: Json to Dataframe Conversion using Python I want to convert the below json to dataframe which looks like in the picture attached.
I have tried below code but gives an error " string indices must be integers".
Please help.
def on_input(data):
#    df = pd.DataFrame.from_dict(data["data"])
    api.send("output", df)

api.set_port_callback("input1", on_input)

JSON FORMAT
Expected DF


text: Q: Защита android приложения и идентификация устройства на днях появился вопрос, как можно идентифицировать смартфон, чтобы в приложении работала такая схема: один аккаунт - одно устройство, и какие есть способы обезопасить приложение


text:
Q: load html page in div without refresh when a link inside that div is clicked Here is what I need to get done:
Basically I have a 'map' with some 'dots' on it; when a dot gets clicked, I want to load another image instead with some other dots on it (dots are the links) without refreshing the page. One way of doing it was to get the div's dispaly:none, and when clicked, hide() current image (and dots on it) and fadeIn() the new one, but I don't want to load all the images every time the page is accessed.
The issue:
When doing it with plain PHP, it works perfectly fine: when it is on 'main.php' it opens image '1-25.png', when a link (dot) is clicked it opens the 'main.php?m=mapname' and opens 'mapname.png'. But, I want the page to stay still, and to have the content changed (without refresh).
I have first page with some navigation buttons, and a div where another page with links is loaded. I need to get the content inside the div changed when the link is clicked, without refreshing the browser. It works great if I am using any links or buttons outside the div, but as soon as I am trying to navigate inside the div, it does not work.
here is some code:
the index.php
First

Second

Third

<?PHP
include ('div.php');
?>

the div.php

and the content.php
if (!isset($_GET['m']) || empty($_GET['m'])) {
    echo "

";
} else if ($_GET['m'] == 'l50') {
    echo "

";
} else if ($_GET['m'] == 'r50') {
    echo "

";
}

UPDATE\Fix
I have deleted the
   $('#map').load('content.php');
from div.php, and then changed the click event to
    $('#map').on('click', 'a#1', function(event) {

        $("#map").load('map.php?m=l50');
        event.preventDefault();
    });

A: Try replacing your current click event with this:
$('#map').on('click', 'a', function(event) {
    $('#map').load($(this).attr('href'));
    event.preventDefault();
});

http://api.jquery.com/on/

A: If I was not wrong, it could be the link on the return content from ajax not working.
You should use live() instead to keep the click event still live after ajax request has been done
$('a').live('click', function(){
//do something
});

Edited:

The .live() method has been deprecated since jQuery 1.7 and has been
  removed in 1.9. We recommend upgrading code to use the .on() method
  instead. To exactly match $("a.foo").live("click", fn), for example,
  you can write $(document).on("click", "a.foo", fn). For more
  information, see the .on() documentation. In the meantime, the jQuery
  Migrate plugin can be used to restore the .live() functionality.
  live() removed

In case of after all does not work, you can put the script into the function in order to rebind them when ajax completed

A: Sounds to me as if an iframe is quite reasonable for you to use.
Then you would need two div's: one for the main map and one for the detail maps with the iframe on it. Then you would be able to refresh the content of the second div without refreshing the entire page.
It is also possible to execute javascript/jquery from inside an iframe on the outer parent page and vice versa.
This would be the way I would go for first. I am sure it is also possible without an iframe, but with a lot more programming work.

A: The JQuery .load function is built for this purpose (http://api.jquery.com/load/).  It will save you a lot of hassle.
Basicall the function loads content into your chosen selector e.g:
$("#myDiv").load('page_going_somewhere_else.php');

You can wrap this in a click event to fire when something is clicked like this:
$("a#myLink").on('click', function(e){
    e.preventDefault();
    e.stopPropagation();
    var url = $(this).attr("href");
    $("#myDiv").load(url);
});

and if you need to send data to your loaded page to check against you can send data like this:
$("a#myLink").on('click', function(e){
   e.preventDefault();
   e.stopPropagation();
   var url = $(this).attr("href");
   $("#myDiv").load(url, {"myData":"myAnswer"});
});


text:
Q: Apache Knox for SAML2 authentication keeps using NameIDFormat entity instead of what is configured I am trying to enable SSO capabilities for Apache Zeppelin, using Apache Knox, which is configured to redirect auth requests to a Siteminder IdP.
The issue I am having is related to the NameID format configuration, and the signing configuration.
No matter what I configure in the sp/idp metadata, the NameID format used is
urn:oasis:names:tc:SAML:2.0:nameid-format:entity
And the requests are always being sent with Signed requests set to true.
My SP configuration is as follows:
<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="https://knox.test.com/gateway/knoxsso/api/v1/websso?pac4jCallback=true%26client_name=SAML2Client">
<SPSSODescriptor AuthnRequestsSigned="false" WantAssertionsSigned="false" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol urn:oasis:names:tc:SAML:1.1:protocol http://schemas.xmlsoap.org/ws/2003/07/secext">
<NameIDFormat>
  urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified
</NameIDFormat>
    <SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://knox.test.com/gateway/knoxsso/api/v1/websso?pac4jCallback=true%26client_name=SAML2Client"/>
   <AssertionConsumerService
            Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" index="1" isDefault="true"  Location="https://knox.test.com/gateway/knoxsso/api/v1/websso?pac4jCallback=true%26client_name=SAML2Client"/>
</SPSSODescriptor>

I activated a SAML tracer and attempted the logon user journey. The AuthNRequest being sent to the Siteminder IdP based on this configuration looks like this:
<saml2p:AuthnRequest xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol"
                 AssertionConsumerServiceURL="https://knox.test.com/gateway/knoxsso/api/v1/websso?pac4jCallback=true%26client_name=SAML2Client"
                 Destination="https://test-siteminder.com/test/saml2sso"
                 ForceAuthn="false"
                 ID="_yp52mio0oj4ho2niijmnnaikgbkid9tnc5h5ear"
                 IsPassive="false"
                 IssueInstant="2020-02-17T10:19:24.279Z"
                 ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
                 ProviderName="pac4j-saml"
                 Version="2.0"
                 >
<saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion"
              Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity"
              NameQualifier="https://knox.test.com/gateway/knoxsso/api/v1/websso?pac4jCallback=true%26client_name=SAML2Client"
              >https://knox.test.com/gateway/knoxsso/api/v1/websso?pac4jCallback=true%26client_name=SAML2Client</saml2:Issuer>

I can see a signature value in the Parameters section of the request, which is why I'm assuming that the AuthNRequest is signed (though my understanding of this is minimal, so that could be a wrong assumption!).
Can anyone help explain why the NameIDFormat is coming through as entity, as opposed to unspecified?
Does Apache knox support SAML1 protocols?
Thanks in advance!

A: You mentioned NameID format to be urn:oasis:names:tc:SAML:2.0:nameid-format:entity in your post but in the code you pasted it is urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified, just a copy paste error ? Looks like protocolSupportEnumeration is also referencing SAML 1 protocol. Knox uses Pac4J under the hood which does not support SAML 1, this might be the reason.


text:
Q: Sound Issue: Dummy Output in Ubuntu 20.04.1 I am facing an issue with sound output and input.
It can read from an external BlueTooth headset but won't show internal output hardware(I have a monitor with a built-in speaker on it) or front panel input (I am using Desktop).
Image


text:
Q: Can tikz menu items (as defined by menukeys pkg) be made to go across multiple lines? I have a big problem regarding the menukeys package, which uses tikz to allow you to graphically represent menus/file paths. The major problem: no linebreaks. If a menu item happens to exceed the line length, instead of switching to a new line, it just keeps going endlessly (becoming unreadable).
So, my question is: How do I get the individual tikz drawings to adhere to line breaks?
For the record, I mean something like:
                  |---------||----------------------------||---------
Lorem ipsum dolor |sit amet || consectetur adipiscing elit|| sed do
                  |---------||----------------------------||---------
-------------------------|
eiusmod tempor incididunt| ut labore et dolore magna aliqua.
-------------------------|

I've already seen this wonderful post (Boxed text, multiline), but since I'm a LaTeX novice, I'm struggling to understand how it works and how I can apply it to the menu design I have to use (not by choice XD).
I'd be super-grateful if the community could help me figure this out!
Here's the current menu style code I'm using (sorry for the bleep-outs, but I don't want to get in trouble for revealing the custom macro names):
\usepackage{menukeys}
\copymenustyle{********}{roundedmenus}
\newmenustylesimple{xxxxxxxx}{%
  tw@set@tikz@colors,
  rounded corners=0.3ex,
  inner sep=0pt,
  inner xsep=2pt,
  text height=1.825ex,
  text depth=0.7ex,
  minimum width=0.7ex,
  font=\relsize{-1}\xxxfontnamexxx,
  signal,
  signal to=nowhere,
  signal pointer angle=110,
}{gray}
\makeatletter
\tw@declare@style*{*******}{% create style manually due to signal to and signal from diffs
   \tikz[baseline={($(tw@node.base)+(0,-0.2ex)$)}]{%
         \node(tw@node)[tw@roundedmenus@base,font=\relsize{-1}\normalfont,signal to=east,fill=gray!25]%
               {\strut\CurrentMenuElement};}%
}[\hspace{-0.2em}\hspace{0em plus 0.1em minus 0.05em}]%
{%
   \tikz[baseline={($(tw@node.base)+(0,-0.2ex)$)}]{%
         \node(tw@node)[tw@roundedmenus@base,font=\relsize{-1}\normalfont,signal from=west,signal to=east,fill=gray!25]%
               {\strut\CurrentMenuElement};}%
}{% Last Item
   \tikz[baseline={($(tw@node.base)+(0,-0.2ex)$)}]{%
         \node(tw@node)[tw@roundedmenus@base,font=\relsize{-1}\normalfont\bfseries,color=white,signal from=west,fill=gray]%
               {\strut\CurrentMenuElement};}%
}{% Other Items
   \tikz[baseline={($(tw@node.base)+(0,-0.2ex)$)}]{%
         \node(tw@node)[tw@roundedmenus@base,font=\relsize{-1}\normalfont,color=white,fill=gray]{\strut\CurrentMenuElement};}%
}{gray}
\makeatother
\renewmenumacro{\menu}{********} % default: menus
\renewmenumacro{\directory}{xxxxxxx} % default: paths
\renewmenumacro{\keys}{xxxxxxxxxx} % default: roundedkeys
\renewmenumacro{\directory}[/]{paths}

((btw, apologies for the (somewhat) duplicate post. I couldn't expand on the original since I posted that before I signed up to the site. orz))

A: This is not yet an answer, but it is far too long as a comment
Well I can't know for sure if this will help but it may serve as a starting point for discussion. After removing all unnecessary or incomplete code, here is a working example that breaks the paths.
Could you have a look at this and edit your question so that we may move forward. Otherwise this question will be closed because of its incomplete informations.
\documentclass{article}
\usepackage{menukeys}
\makeatletter
\tw@declare@style*{mystyle}{% create style manually due to signal to and signal from diffs
   \tikz[baseline={($(tw@node.base)+(0,-0.2ex)$)}]{%
         \node(tw@node)[tw@roundedmenus@base,font=\relsize{-1}\normalfont,signal to=east,fill=gray!25]%
               {\strut\CurrentMenuElement};}%
}[\hspace{-0.2em}\hspace{0em plus 0.1em minus 0.05em}]%
{%
   \tikz[baseline={($(tw@node.base)+(0,-0.2ex)$)}]{%
         \node(tw@node)[tw@roundedmenus@base,font=\relsize{-1}\normalfont,signal from=west,signal to=east,fill=gray!25]%
               {\strut\CurrentMenuElement};}%
}{% Last Item
   \tikz[baseline={($(tw@node.base)+(0,-0.2ex)$)}]{%
         \node(tw@node)[tw@roundedmenus@base,font=\relsize{-1}\normalfont\bfseries,color=white,signal from=west,fill=gray]%
               {\strut\CurrentMenuElement};}%
}{% Other Items
   \tikz[baseline={($(tw@node.base)+(0,-0.2ex)$)}]{%
         \node(tw@node)[tw@roundedmenus@base,font=\relsize{-1}\normalfont,color=white,fill=gray]{\strut\CurrentMenuElement};}%
}{gray}
\makeatother

\renewmenumacro{\directory}[/]{mystyle}

\begin{document}
\directory{Macintosh HD/Users/Your Name/Documents/Users/Your Name/Documents/Users/Your Name/Documents/Users/Your Name/Documents/Users/Your Name/Documents}
\end{document}


text:
Q: how to assign java.util.LinkedHashMap<*, *> to kotlin.collections.Map<*, *> I have declared a method which takes map as parameter:
fun myKotlinMethod(myParameter:Map<String,String>)...

Later I read data from json. I get an object of type: java.util.LinkedHashMap<*, *> I need to use reflection to invoke myKotlinMethod. Before that, I test if the value is assignable to myParameter. I ask parameter type using kotlin reflection and I get kotlin.collections.Map<*, *>.
bottom line is that java.util.LinkedHashMap<*, *> does not implement kotlin.collections.Map<*, *> (it cannot) and therefore is not assignable.
I'm using this method to check assignability
inline fun isAssignable(parameterType: KType, valueType: KType): Boolean {
    if (parameterType == valueType) return true
    return parameterType.isSubtypeOf(valueType)
}

and I test like
if (isAssignable(parameter.type.classifier!!.starProjectedType, parameterValue::class.starProjectedType))

I read about some dark magic kotlin does to collection during compile time, but during runtime, java classes should be used. This is not my case since I get kotlin classes in runtime.
So, How do I correctly check for collection types compatibility?

A: You seem to have written this the other way around:
// you can even delete the parameterType == valueType check
// isSubtypeOf returns true if the types are the same
return parameterType.isSubtypeOf(valueType)

The method call is valid if the type of the value is a subtype of the parameter type, so it should be:
return valueType.isSubtypeOf(parameterType)

However, note that this is not safe at all. Since you only know that the value is a LinkedHashMap<*, *>, what if the map has Ints, Doubles, or UUIDs in it? That would still pass the subtype check. Because you used starProjectedType on the parameter type, you threw away the <String, String> part of the type, and didn't actually check that the value actually only has strings.
To make sure that the collections are compatible, you should also check the collection's elements:
fun isAssignableToMapStringString(value: Any) =
    if (value is Map<*, *>) {
        value.all { it.value is String && it.key is String }
    } else {
        false
    }

It can be quite hard to generalise this to any KType though. You'd have to do a lot of reflection to get the elements out of the collection. And you'd have to handle maps and collections separately, since Map and Collection are unrelated interfaces :(


text:
Q: Router.use() requires middleware function but got a undefined at function use im following this tutorial to work with authentication with node.js and i have some problems that i didn't figure out how to solve yet. Basicly i set the server like this
var express         = require('express');
var bodyParser      = require('body-parser'); // necessário para PUT e POST
var mongoose        = require('mongoose');
var expressLayouts  = require('express-ejs-layouts');
var passport        = require('passport');
var flash           = require('connect-flash');
var morgan          = require('morgan');
var cookieParser    = require('cookie-parser');
var session         = require('express-session');
var configDB        = require('./config/database.js');

// conexão à base de dados (o servidor MongoDB necessita já ter sido iniciado)
mongoose.Promise = global.Promise; //resolução de warning:
mongoose.connect(configDB.url);

//require('./config/passport')(passport); // pass passport for configuration

// Configura a aplicação Express (e seus middlewares)

var app = express();

app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms

app.set('views', './views');
app.set('view engine','ejs');

app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash());

app.use(expressLayouts);
app.use(express.static('./public'));
app.use('/', require('./routes/register')(passport));
app.use('/', require('./routes/login')(passport));
app.use('/', require('./routes/profile')(passport));
app.use('/', require('./routes/main')(passport));
app.use('/', require('./routes/logout')(passport));

//middlewares de terceiros
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//middlewares de roteamento

// inicia servidor
var server = app.listen(8081, function() {
 console.log('Express server listening on port ' + server.address().port);
});

i think the problem has something to do with my routes or the passport module to do the authentication.
Here is my register route
var User = require('../models/user');
var express = require('express');
// routeamento do Express
var router = express.Router();
//GET request - /movies
module.exports = function(passport) {

    router.route('/register')
        .get(function(req, res) {
            res.render('./pages/register',{ message: req.flash('signupMessage') });
        })
        .post(passport.authenticate('local-signup', {
            successRedirect : '/profile', // redirect to the secure profile section
            failureRedirect : '/register', // redirect back to the signup page if there is an error
            failureFlash : true // allow flash messages
        }));
}

to end this i need to show how my passport is set, i don't know very well what i am missing here and why i get that error, maybe it has something to do with the order of the middlewares?
passport
/ config/passport.js

// load all the things we need
var LocalStrategy   = require('passport-local').Strategy;
// load up the user model
var User            = require('../models/user');

// expose this function to our app using module.exports
module.exports = function(passport) {
    // =========================================================================
    // passport session setup ==================================================
    // =========================================================================
    // required for persistent login sessions
    // passport needs ability to serialize and unserialize users out of session

    // used to serialize the user for the session
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

    // =========================================================================
    // LOCAL SIGNUP ============================================================
    // =========================================================================
    // we are using named strategies since we have one for login and one for signup
    // by default, if there was no name, it would just be called 'local'

    passport.use('local-signup', new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, email, password, done) {

        // asynchronous
        // User.findOne wont fire unless data is sent back
        process.nextTick(function() {

        // find a user whose email is the same as the forms email
        // we are checking to see if the user trying to login already exists
        User.findOne({ 'local.email' :  email }, function(err, user) {
            // if there are any errors, return the error
            if (err)
                return done(err);

            // check to see if theres already a user with that email
            if (user) {
                return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
            } else {

                // if there is no user with that email
                // create the user
                var newUser            = new User();

                // set the user's local credentials
                newUser.local.email    = email;
                newUser.local.password = newUser.generateHash(password);

                // save the user
                newUser.save(function(err) {
                    if (err)
                        throw err;
                    return done(null, newUser);
                });
            }

        });

        });

    }));

};

error on the cmd:
us);
        } else {
          var challenges = failures\.map(function(f) { return f\.challenge; });
          var statuses = failures\.map(function(f) { return f\.status; });
          return callback(null, false, challenges, statuses);
        }
      }

      \/\/ Strategies are ordered by priority\.  For the purpose of flashing a
      \/\/ message, the first failure will be displayed\.
      var failure = failures[0] || {}
        , challenge = failure\.challenge || {}
        , msg;

      if (options\.failureFlash) {
        var flash = options\.failureFlash;
        if (typeof flash == 'string') {
          flash = { type: 'error', message: flash };
        }
        flash\.type = flash\.type || 'error';

        var type = flash\.type || challenge\.type || 'error';
        msg = flash\.message || challenge\.message || challenge;
        if (typeof msg == 'string') {
          req\.flash(type, msg);
        }
      }
      if (options\.failureMessage) {
        msg = options\.failureMessage;
        if (typeof msg == 'boolean') {
          msg = challenge\.message || challenge;
        }
        if (typeof msg == 'string') {
          req\.session\.messages = req\.session\.messages || [];
          req\.session\.messages\.push(msg);
        }
      }
      if (options\.failureRedirect) {
        return res\.redirect(options\.failureRedirect);
      }

      \/\/ When failure handling is not delegated to the application, the defaul
t
      \/\/ is to respond with 401 Unauthorized\.  Note that the WWW-Authenticate

      \/\/ header will be set according to the strategies in use (see
      \/\/ actions#fail)\.  If multiple strategies failed, each of their challen
ges
      \/\/ will be included in the response\.
      var rchallenge = []
        , rstatus, status;

      for (var j = 0, len = failures\.length; j < len; j++) {
        failure = failures[j];
        challenge = failure\.challenge;
        status = failure\.status;

        rstatus = rstatus || status;
        if (typeof challenge == 'string') {
          rchallenge\.push(challenge);
        }
      }

      res\.statusCode = rstatus || 401;
      if (res\.statusCode == 401 && rchallenge\.length) {
        res\.setHeader('WWW-Authenticate', rchallenge);
      }
      if (options\.failWithError) {
        return next(new AuthenticationError(http\.STATUS_CODES[res\.statusCode],
 rstatus));
      }
      res\.end(http\.STATUS_CODES[res\.statusCode]);
    }

    (function attempt(i) {
      var layer = name[i];
      \/\/ If no more strategies exist in the chain, authentication has failed\.

      if (!layer) { return allFailed(); }

      \/\/ Get the strategy, which will be used as prototype from which to creat
e
      \/\/ a new instance\.  Action functions will then be bound to the strategy

      \/\/ within the context of the HTTP request\/response pair\.
      var prototype = passport\._strategy(layer);
      if (!prototype) { return next(new Error('Unknown authentication strategy "
' + layer + '"')); }

      var strategy = Object\.create(prototype);

      \/\/ ----- BEGIN STRATEGY AUGMENTATION -----
      \/\/ Augment the new strategy instance with action functions\.  These acti
on
      \/\/ functions are bound via closure the the request\/response pair\.  The
 end
      \/\/ goal of the strategy is to invoke (.*)one(.*) of these action methods
, in
      \/\/ order to indicate successful or failed authentication, redirect to a
      \/\/ third-party identity provider, etc\.

      \/(.*)(.*)
       (.*) Authenticate `user`, with optional `info`\.
       (.*)
       (.*) Strategies should call this function to successfully authenticate a
       (.*) user\.  `user` should be an object supplied by the application after
 it
       (.*) has been given an opportunity to verify credentials\.  `info` is an
       (.*) optional argument containing additional user information\.  This is
       (.*) useful for third-party authentication strategies to pass profile
       (.*) details\.
       (.*)
       (.*) @param {Object} user
       (.*) @param {Object} info
       (.*) @api public
       (.*)\/
      strategy\.success = function(user, info) {
        if (callback) {
          return callback(null, user, info);
        }

        info = info || {};
        var msg;

        if (options\.successFlash) {
          var flash = options\.successFlash;
          if (typeof flash == 'string') {
            flash = { type: 'success', message: flash };
          }
          flash\.type = flash\.type || 'success';

          var type = flash\.type || info\.type || 'success';
          msg = flash\.message || info\.message || info;
          if (typeof msg == 'string') {
            req\.flash(type, msg);
          }
        }
        if (options\.successMessage) {
          msg = options\.successMessage;
          if (typeof msg == 'boolean') {
            msg = info\.message || info;
          }
          if (typeof msg == 'string') {
            req\.session\.messages = req\.session\.messages || [];
            req\.session\.messages\.push(msg);
          }
        }
        if (options\.assignProperty) {
          req[options\.assignProperty] = user;
          return next();
        }

        req\.logIn(user, options, function(err) {
          if (err) { return next(err); }

          function complete() {
            if (options\.successReturnToOrRedirect) {
              var url = options\.successReturnToOrRedirect;
              if (req\.session && req\.session\.returnTo) {
                url = req\.session\.returnTo;
                delete req\.session\.returnTo;
              }
              return res\.redirect(url);
            }
            if (options\.successRedirect) {
              return res\.redirect(options\.successRedirect);
            }
            next();
          }

          if (options\.authInfo !== false) {
            passport\.transformAuthInfo(info, req, function(err, tinfo) {
              if (err) { return next(err); }
              req\.authInfo = tinfo;
              complete();
            });
          } else {
            complete();
          }
        });
      };

      \/(.*)(.*)
       (.*) Fail authentication, with optional `challenge` and `status`, default
ing
       (.*) to 401\.
       (.*)
       (.*) Strategies should call this function to fail an authentication attem
pt\.
       (.*)
       (.*) @param {String} challenge
       (.*) @param {Number} status
       (.*) @api public
       (.*)\/
      strategy\.fail = function(challenge, status) {
        if (typeof challenge == 'number') {
          status = challenge;
          challenge = undefined;
        }

        \/\/ push this failure into the accumulator and attempt authentication
        \/\/ using the next strategy
        failures\.push({ challenge: challenge, status: status });
        attempt(i + 1);
      };

      \/(.*)(.*)
       (.*) Redirect to `url` with optional `status`, defaulting to 302\.
       (.*)
       (.*) Strategies should call this function to redirect the user (via their

       (.*) user agent) to a third-party website for authentication\.
       (.*)
       (.*) @param {String} url
       (.*) @param {Number} status
       (.*) @api public
       (.*)\/
      strategy\.redirect = function(url, status) {
        \/\/ NOTE: Do not use `res\.redirect` from Express, because it can't dec
ide
        \/\/       what it wants\.
        \/\/
        \/\/       Express 2\.x: res\.redirect(url, status)
        \/\/       Express 3\.x: res\.redirect(status, url) -OR- res\.redirect(u
rl, status)
        \/\/         - as of 3\.14\.0, deprecated warnings are issued if res\.re
direct(url, status)
        \/\/           is used
        \/\/       Express 4\.x: res\.redirect(status, url)
        \/\/         - all versions (as of 4\.8\.7) continue to accept res\.redi
rect(url, status)
        \/\/           but issue deprecated versions

        res\.statusCode = status || 302;
        res\.setHeader('Location', url);
        res\.setHeader('Content-Length', '0');
        res\.end();
      };

      \/(.*)(.*)
       (.*) Pass without making a success or fail decision\.
       (.*)
       (.*) Under most circumstances, Strategies should not need to call this
       (.*) function\.  It exists primarily to allow previous authentication sta
te
       (.*) to be restored, for example from an HTTP session\.
       (.*)
       (.*) @api public
       (.*)\/
      strategy\.pass = function() {
        next();
      };

      \/(.*)(.*)
       (.*) Internal error while performing authentication\.
       (.*)
       (.*) Strategies should call this function when an internal error occurs
       (.*) during the process of performing authentication; for example, if the

       (.*) user directory is not available\.
       (.*)
       (.*) @param {Error} err
       (.*) @api public
       (.*)\/
      strategy\.error = function(err) {
        if (callback) {
          return callback(err);
        }

        next(err);
      };

      \/\/ ----- END STRATEGY AUGMENTATION -----

      strategy\.authenticate(req, options);
    })(0); \/\/ attempt
  }\/?$/: Nothing to repeat
    at RegExp (native)
    at pathtoRegexp (C:\Users\Filipe\ShareIdea\node_modules\path-to-regexp\index
.js:128:10)
    at new Layer (C:\Users\Filipe\ShareIdea\node_modules\express\lib\router\laye
r.js:45:17)
    at Function.route (C:\Users\Filipe\ShareIdea\node_modules\express\lib\router
\index.js:494:15)
    at EventEmitter.app.(anonymous function) [as post] (C:\Users\Filipe\ShareIde
a\node_modules\express\lib\application.js:480:30)
    at module.exports (C:\Users\Filipe\ShareIdea\routes\routes.js:14:10)
    at Object.<anonymous> (C:\Users\Filipe\ShareIdea\app.js:43:30)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

A: Yes, the order of middlewares matter. You should place these:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); on the top of your routes or any other middleware that are suppose to receive data, otherwise any data that you may get in your server, will not be parsed by the body-parser, and req.body will always be undefined.


text:
Q: get user after LockedOut time has passed AspNetCore I'm logging my login
I've logged the first time user tries to sign in and fails
and when user gets locked out
but now I need on how to log when users lockedout time has passed and can try to sign in again
something like : the user {UserName} has been unlocked and can try to sign in again
   var result = await _SignInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememeberMe, true);
                                if (result.Succeeded)
                                {
                                    if (!string.IsNullOrEmpty(ReturnUrl) || Url.IsLocalUrl(ReturnUrl))
                                        return Redirect(ReturnUrl);
                                    else
                                    {
                                        //messages with title == null are used in relationship (chat) page
                                        unreadReceivedMessages = _MessageRepository.GetReceivedMessages(producer.UserId).Where(m => m.Title != null && !m.IsRead).AsQueryable();
                                        unreadSentMessages = _MessageRepository.GetSentMessages(producer.UserId, null).Where(m => m.Title != null && !m.IsRead).AsQueryable();
                                        Response.Cookies.Append("noOfUnreadReceivedMessages", unreadReceivedMessages.Count().ToString());
                                        Response.Cookies.Append("noOfUnreadSentMessages", unreadSentMessages.Count().ToString());

                                        string protectedUserId = _protector.Protect(producer.UserId);
                                        AlarmViewModel alrm = new AlarmViewModel();
                                        alrm.Link = protectedUserId;
                                        Response.Cookies.Append("UidUs", protectedUserId);
                                        #region UserLog
                                        UserLog userLog = new UserLog
                                        {
                                            UserId = producer.UserId,
                                            Ip = remoteIpAddress.ToString(),
                                            LoginDateTime = DateTime.Now
                                        };
                                        _AccountRepository.AddUserLog(userLog);
                                        #endregion
                                        return RedirectToAction("Alarm", "Notification"/*, new { userId = protectedUserId }*/, alrm);

                                    }
                                }

when it gets locked
                                if (result.IsLockedOut)
                                {

                                    _Logger.LogInformation($"The User {currentUserID} Has been LockedOut with Ip: {Ip}");

                                    return View("AccountLocked");
                                }

The first time user fails
                    _Logger.LogInformation($"The User {currentUserID} Had a Failed Login attempt  with Ip: {Ip}");

Actually I want to know how can i set smth like trigger in sql server in the aspnet core backend that if smthing changed smthing happens?