text:
Q: Installing Git 1.9.5 on Windows 10 Is anybody else having trouble installing Git 1.9.5 on Windows 10 Pro? After numerous restarts, it still will not do anything. E.g., I click the exe - wait, the Windows load pointer shows. Continue waiting. Nothing.
Has anybody managed to install it successfully?

A: Since Git isn't codesigned, Windows is trying to look it up against a corpus of known good (but unsigned) installers.  It downloads the entire list of data (rather than send information about what you're installing to Microsoft.)  You can wait (don't restart!) for this data to download or you can disable this scan.
It should be in Settings > Update & Security > Windows Defender.  Turn off the Real-time Protection and Cloud-based Protection options, then you should be able to install without a delay.

A: I was running into the same issue, followed Matteo's suggestion, except I was able to install it with Windows 8 compatibility turned on.


text:
Q: How to formalize the fact that $f(i)=\lceil i/2\rceil$ is surjective but not one-to-one from $\Bbb N$ to itself?
If the set $S$ is countably infinite, prove or disprove that if $f$ maps $S$ onto $S$ (i.e. $f\colon S\to S$ is a surjective function), then $f$ is one-to-one mapping.
Please give a formal mathematical proof for this statement.

I have a counter-example: Suppose the mapping is from $\Bbb N$ (the natural numbers, a countably infinite set) to $\Bbb N$. And $f(i) = \lceil i/2\rceil$. It is onto function but not one-one.
But I am not getting that how this mapping is onto. Intuitively, since $1$ and $2$ will be mapped to $1$; $3$ and $4$ will be mapped to $2$; $5$ and $6$ will be mapped to $3$; similarly, $n-1$ and $n$ will be mapped to $n/2$. So in the codomain, there will be some elements that have no pre-image for this countably infinite set. So, please correct me where I am wrong.

A: To prove that a function $f\colon A\to B$ is surjective, you need to be able to prove that given $b\in B$, there is some $a\in A$ such that $f(a)=b$.
In your case, $A=B=\Bbb N$, and $f(x)=\lceil \frac x2\rceil$.
So you need to prove that given any $m\in\Bbb N$, there is some $n\in\Bbb N$ such that $\lceil\frac n2\rceil=m$. Even though this $n$ is not unique, I am sure that you can come up with a way to find such $n$, from a given $m$.

A: Maybe I'm missing something. For every n in codomain, 2n and 2n-1 are in preimage, so the mapping is onto but not 1-1

redpajama_set_name: RedPajamaStackExchange


text:
Q: how many ways to create PrintWriter object in jsp and servlets? How many ways to create PrintWriter object using JSP and servlets?
I am using JSP as well as servlets for better performance I am using:
PrintWriter pw = response.getWriter();

How many ways to create write instead of this?

A: You can use following types:
PrintWriter pout = new PrintWriter(out, true);
PrintWriter pout = new PrintWriter(System.out, true); // for console print
PrintWriter pout = new PrintWriter(response.getWriter(), true);
PrintWriter pout = response.getWriter();

A: You can use out PrintWriter object
out.println("...");

You can use pageContext to get JspWriter:
pageContext.getOut()

Or you can just print a value
<% String value ="...";%>
<%=value%>

A: First Import Class :
import java.io.PrintWriter;

You can use it in Jsp and Servlet as :
String output="Something";
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"));

or you can simply output as :
out.println(output);


text:
Q: Handle UIButton click in a custom cell that is loaded in sections (where number of section is not defined. ie: taken dynamically) I am having a view controller where i want to load sections & the count for number of section is taken dynamically, ie: retrieved from database. Now, in each section am having 8 rows where row 2 to 8 are loaded with 5 buttons each.
I want that whenever a button on a cell is pressed a particular value is manipulated & displayed on the extreme right of that cell. Same thing should happen for all the sections.
.
My problem is that when i click a particular button on a cell of one section; some other button on the cells of other sections is selected as well.
.
Please help..

A: you can get a section index as we as cell index as well at button tap Method using bellow code:-
-(IBAction)ActionBttonTap:(UIButton*)sender
{

    CGPoint touchPoint = [sender convertPoint:CGPointZero toView:yourtableview];
    NSIndexPath *indexPath = [tblHistoryYear indexPathForRowAtPoint:touchPoint];
    NSString *strSection=[NSString stringWithFormat:@"%d",indexPath.section];
    NSString *strRow=[NSString stringWithFormat:@"%d",indexPath.row];

    NSLog(@"tag is %d   indexPath is  %d  section is %d",sender.tag,indexPath.section,indexPath.row);

}

Do not forget to set button tag at cellForRowAtIndexPath like self.yourbutton.tag=indexPath.row;

A: Implement prepareToReuse method in your cell, call super implementation of the same and then call – removeTarget:action:forControlEvents: method on the button.
As the cell will be reused, you have to remove the previous target set to the button before adding a new one.
Below is sample code
- (void)prepareForReuse
{
    [super prepareForReuse];
    [yourbuttonInstance removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
}

Passing NULL for action removes all the actions messages paired with the target and update the control events as per your requirement.


text:
Q: How to remove excess whitespace on the first page? The following MWE closely reproduces a LaTeX file I created. I'm using @egreg's solution to my question about programatically creating dummy text.
The issue is that the quoted section on the second page is pushed to
the second page. I suppose this is because of the altered definition
of the quoting environment that I used, namely
\tcolorboxenvironment{quoting}{code={\mbox{}},nobeforeafter,boxrule=2pt,sharp corners,breakable,skin=enhanced,colback=white}

However, I've been using that definition of quoting in a style file
for some time, and it's mostly worked for me. And it's probably used
in a number of existing documents. So I'd like to keep it as it is.
I have the following questions.
1) First, a minor one. I am correct to think that using vskip=10in
in the following line was an error, in the sense that it gets
overwritten by the new definition of quoting?
\usepackage[vskip=10in]{quoting}

I'm only using the quoting environment from the quoting package, as
shown below, nothing else.
If this the case, I'll remove vskip=10in from that package
declaration.
2) My main question is whether there is a graceful way to avoid having
a large amount of empty space at the bottom of the first page.
I suppose this is being caused by the \mbox{} in the
\tcolorboxenvironment declaration.
I was thinking that I could just leave the changed definition of quoting in the preamble as it is, but temporarily alter the definition in such a way as to allow that box on the second page to move to the first page. Is that possible? Or is there a better way to do it?
    \documentclass[12pt, sections, headheight=30pt, headinclude,
    firstfoot=false, enlargefirstpage=true, foldmarks=false,
    foldmarks=blmtP, fromalign=center, fromphone, fromemail, version=last,
    backaddress=false, subject=titled]{scrlttr2}

    \usepackage[most]{tcolorbox}
    \usepackage[vskip=10in]{quoting}
    \usepackage[T1]{fontenc}
    \usepackage{fouriernc}
    \tcolorboxenvironment{quoting}{code={\mbox{}},nobeforeafter,boxrule=2pt,sharp corners,breakable,skin=enhanced,colback=white}

\ExplSyntaxOn
\NewDocumentCommand{\dummy}{m m m}
  {
   \prg_replicate:nn { #3 }
     {
      \prg_replicate:nn { #2 } { #1 \hfill } \dummy_endline:
     }
 }
\cs_new:Npn \dummy_endline:
  { { \parfillskip=0pt\par } }

\ExplSyntaxOff

\begin{document}
\setkomavar{fromname}{Name}
\setkomavar{fromaddress}{Address}
\renewcommand{\phonename}{Landline}
\renewcommand{\mobilephonename}{Mobile}
\setkomavar{frommobilephone}{Mobile}
\setkomavar{fromemail}{Email}
\setkomavar{signature}{(\usekomavar{fromname})}
\setkomavar{subject}{Subject}
\setkomavar{date}{\today}

\setkomavar{firsthead}{%
  \parbox{\linewidth}{\centering
    \textbf{\jobname.tex} \input{"| hg log -v -l 1 \jobname.tex --template '{node}  {date|isodate}'"}
    \ifhmode \\ \fi
    {\fontfamily{pzc}\selectfont
    \hspace{\textwidth}
    \usekomavar{fromname}\\
    \usekomavar{fromaddress}\\
    \usekomavar*{mobilephoneseparator}\usekomavar{mobilephoneseparator}\usekomavar{frommobilephone}\\
    \usekomavar*{emailseparator}\usekomavar{emailseparator}\usekomavar{fromemail}
    }
  }%
}

\makeatletter
\@addtoplength{firstheadvpos}{30pt}
\@addtoplength{toaddrvpos}{40pt}
\@addtoplength{refvpos}{10pt}
\@addtoplength{sigbeforevskip}{20pt}
\makeatletter\@setplength{sigindent}{0.5\linewidth}\makeatother
\makeatother

\def\today{20th February, 2019}
\begin{letter}{
    Someone\\
    Company\\
    Building\\
    Street\\
    City
  }

  \opening{Hi}

  \dummy{HelloWorld!}{3}{5}
  \begin{quoting}
    \dummy{HelloWorld!}{3}{3}
  \end{quoting}

  \dummy{HelloWorld!}{3}{3}

  \begin{quoting}
    \begin{tabular}{p{4.5in}r}
      \textbf{\dummy{HelloWorld!}{3}{1}  }  & \\
      \dummy{HelloWorld!}{3}{2}             & \dummy{HelloWorld!}{1}{1}
    \end{tabular}
  \end{quoting}

\closing{Yours Sincerely,}

\end{letter}
\end{document}

A: I suggest to remove code={\mbox{}} and nobeforeafter from the option list passed to the \tcolorbox definition:
\documentclass[12pt, sections, headheight=30pt, headinclude,
    firstfoot=false, enlargefirstpage=true, foldmarks=false,
    foldmarks=blmtP, fromalign=center, fromphone, fromemail, version=last,
    backaddress=false, subject=titled]{scrlttr2}

    \usepackage[most]{tcolorbox}
    \usepackage[vskip=10in]{quoting}
    \usepackage[T1]{fontenc}
    \usepackage{fouriernc}
    \tcolorboxenvironment{quoting}{
        %code={\mbox{}},nobeforeafter,

        before skip=\baselineskip, % or before skip = 1cm or something else

        boxrule=2pt,sharp corners,breakable,skin=enhanced,colback=white}

\ExplSyntaxOn
\NewDocumentCommand{\dummy}{m m m}
  {
   \prg_replicate:nn { #3 }
     {
      \prg_replicate:nn { #2 } { #1 \hfill } \dummy_endline:
     }
 }
\cs_new:Npn \dummy_endline:
  { { \parfillskip=0pt\par } }

\ExplSyntaxOff

\begin{document}
\setkomavar{fromname}{Name}
\setkomavar{fromaddress}{Address}
\renewcommand{\phonename}{Landline}
\renewcommand{\mobilephonename}{Mobile}
\setkomavar{frommobilephone}{Mobile}
\setkomavar{fromemail}{Email}
\setkomavar{signature}{(\usekomavar{fromname})}
\setkomavar{subject}{Subject}
\setkomavar{date}{\today}

\setkomavar{firsthead}{%
  \parbox{\linewidth}{\centering
    \textbf{\jobname.tex} \input{"| hg log -v -l 1 \jobname.tex --template '{node}  {date|isodate}'"}
    \ifhmode \\ \fi
    {\fontfamily{pzc}\selectfont
    \hspace{\textwidth}
    \usekomavar{fromname}\\
    \usekomavar{fromaddress}\\
    \usekomavar*{mobilephoneseparator}\usekomavar{mobilephoneseparator}\usekomavar{frommobilephone}\\
    \usekomavar*{emailseparator}\usekomavar{emailseparator}\usekomavar{fromemail}
    }
  }%
}

\makeatletter
\@addtoplength{firstheadvpos}{30pt}
\@addtoplength{toaddrvpos}{40pt}
\@addtoplength{refvpos}{10pt}
\@addtoplength{sigbeforevskip}{20pt}
\makeatletter\@setplength{sigindent}{0.5\linewidth}\makeatother
\makeatother

\def\today{20th February, 2019}
\begin{letter}{
    Someone\\
    Company\\
    Building\\
    Street\\
    City
  }

  \opening{Hi}

  \dummy{HelloWorld!}{3}{5}
  \begin{quoting}
    \dummy{HelloWorld!}{3}{3}
  \end{quoting}

  \dummy{HelloWorld!}{3}{3}

  \begin{quoting}
    \begin{tabular}{p{4.5in}r}
      \textbf{\dummy{HelloWorld!}{3}{1}  }  & \\
      \dummy{HelloWorld!}{3}{2}             & \dummy{HelloWorld!}{1}{1}
    \end{tabular}
  \end{quoting}

\closing{Yours Sincerely,}

\end{letter}
\end{document}


text:
Q: Referencing (Using an alias) the value from nested MySQL query in an outer conditional statement I'm using a nested query to get the value I need from a table that I then need to use in a conditional statement, however, every time I try this I keep on getting an error saying unknown column (format) in the field list
SELECT

(SELECT format FROM competition_stages WHERE comp_id = "5" AND rid = "24") AS format,

a.tie_id, b.name AS team_a, b.team_id AS team_a_id, c.name AS team_b, c.team_id AS team_b_id, SUM(e.bonus) AS team_a_bonus, SUM(f.bonus) AS team_b_bonus,

SUM(CASE
    WHEN (a.team_a = e.team_id AND format = "0") THEN e.score
END) as team_a_agg,

SUM(CASE
    WHEN (a.team_b = f.team_id AND format = "0") THEN f.score
END) as team_b_agg

FROM competition_tie a

INNER JOIN teams b ON (a.team_a = b.team_id)
INNER JOIN teams c ON (a.team_b = c.team_id)

LEFT JOIN fixtures d ON (a.tie_id = d.tie_id)
LEFT JOIN fixture_scores e ON (d.fx_id = e.fx_id AND a.team_a = e.team_id)
LEFT JOIN fixture_scores f ON (d.fx_id = f.fx_id AND a.team_b = f.team_id)

WHERE a.comp_id = "5" AND a.rid = "24" AND a.season_id = "5"

GROUP BY a.tie_id

ORDER BY a.tie_id ASC

I can get the value of the format column in my results when I go through them but it just seems I can't use it within my query to use in.
Thanks for your help!

A: Instead of using a subquery, simply join the competition_stages table to your query so that you can reference the format column directly. Assuming there is no appearant relation between the competition_stages table and the other tables in the query (at least not from the information on hand), you can just join the table using the two conditions you specified if these conditions would only yield 1 result in the competition_stages table. Something like this:
SELECT cs.format, a.tie_id, ....
FROM competition_tie a ...
INNER JOIN competition_stages cs ON cs.comp_id = "5" AND cs.rid = "24"


text:
Q: null body from email template i create lwc component, i select body from email template. i have error: null body.

public with sharing class SendInvoiceService {
    @AuraEnabled(cacheable=true)
    public static List getPreview(id contentVId){
        return [SELECT Id, Title, FileExtension, ContentDocumentId From ContentVersion where id=:contentVId];
    }
    @AuraEnabled(cacheable=true)
    public static SendInvoice__c getInvoice(id oppId) {
        Opportunity opp=[select id,Invoice_number__c,
                         (select IsPrimary,Contact.Email,Contact.AccountId,Contact.FirstName,Contact.LastName
                          from OpportunityContactRoles where IsPrimary=true)
                         from Opportunity where id=:oppId];
        OpportunityContactRole oppCR=opp.OpportunityContactRoles;

        SendInvoice__c invoice=new SendInvoice__c();

        invoice.Body__c=[select body from EmailTemplate where name='OpportunityAndr'].body+' body';
        return invoice;
    }}

sendInvoiceLWC.html
<template>
<lightning-card title="Send Invoice" >
<lightning-input label="EmailBody" value={realFormData.Body__c} if:true={realFormData} data-field="Subject"></lightning-input>
</lightning-card>
</template>

sendInvoiceLWC.js

import { LightningElement, api, wire } from 'lwc';
import getInvoice from '@salesforce/apex/SendInvoiceService.getInvoice';
import BODY_FIELD from '@salesforce/schema/SendInvoice__c.Body__c';
import { getSObjectValue } from '@salesforce/apex';
import { refreshApex } from '@salesforce/apex';

export default class sendInvoiceLWC extends NavigationMixin(LightningElement) {
@api recordId;
@api wiredContact;
@api realFormData;
@api InvoiceObj;
@wire(getInvoice, { oppId:'$recordId' }) fetchedInvoice( resp){
    this.wiredContact = resp;
    this.realFormData = this.wiredContact.data;
    this.InvoiceObj=resp;
}

get Subject() {
    return this.InvoiceObj.data?getSObjectValue(this.InvoiceObj.data, BODY_FIELD):'nothing';
}
}

my error

my email body

A: A likely reason for this is that you have an HTML (html or custom) email template and the "body" may only be saved in field HTMLValue
execute this query and you'll see:
select id, name, body, htmlvalue, templateType from emailTemplate


text:
Q: Can PySpark Handle os.walk to Iterate Through Sub-Folders? I tested a couple samples of code that list all files in a specific folder (below).  However, neither one can handle iterating through sub-folders using a wildcard.
First Attempt:
import sys, os

root = "/dbfs/mnt/rawdata/2019/01/"+"01"+"/corp/"
path = os.path.join(root, "targetdirectory")
for path, subdirs, files in os.walk(root):
    for name in files:
        print(os.path.join(path, name))

Second Attempt:
import os
for root, dirs, files in os.walk("/dbfs/mnt/rawdata/2019/01/01/corp/"):
    print(root)
    print(dirs)
    print(files)

So, in this example /01/01/ represents January 1st (pretty obvious).  Is there some way to list all files in January all at once?  I'm working with Databricks and PySpark.  Thanks!

A: Yes, sir
It does iterates...
import os
EXT = 'File_Name'
PATH = 'Path_Name'
for subdir, dirs, files in os.walk(PATH):
  for filename in files:
    filepath = subdir + os.sep + filename

    if filepath.endswith(EXT):
        print (filepath)

please check the indentation


text:
Q: View not showing list items when revisiting page I am using ionic, angularfire and firestore to create an app to show a list of wines.
From the homepage I have made a simple button that pushes a new page.
I have made a provider which uses snapshotchanges and return collection, this new page is injecting the provider and using
ionViewDidLoad() {
    this.wineProvider.getWines().subscribe(wines => {
      console.log(wines);
      this.wines = wines;
    })
  }

to write to a local reference
wines: Wine[];

In the html file, I am showing the result in a list using
<ion-content padding>
   <ion-list>
     <ion-item *ngFor="let wine of wines" >
       {{wine.title}}
     </ion-item>
   </ion-list>
</ion-content>

When I start the app and navigate to the page the list is shown and updated as required. If I navigate back to the homepage and the back to the list page, the list is not shown - however, if data changes, the list is shown again.
Please help me understand why this is.
Thank you :)

A: If you look at the docs it says about ionViewDidLoad:

Runs when the page has loaded. This event only happens once per page being created. If a page leaves but is cached, then this event will not fire again on a subsequent viewing.

So it will only load once, instead you would want to use either ionViewDidEnter or ionViewWillEnter, which is fired each time the view is presented.


text:
Q: is it possible to have multiple UDP c# sockets with same localEndPoint?
I wrote a TCP client/server code that works fine. a TCP socket listener accept connections and create many sockets with same localEndPoint and various RemoteEndPoint. now I like to expand to UDP but I have a problem in seerver code. i must bind UDP socket to a localEndPoint for each client object. but I encounter an error: I can't bind multiple UDP sockets with same localEndPoint. I found that is nature of UDP sockets according to Wiki:

A UDP server does not create new child processes for every concurrently served client, but the same process handles incoming data packets from all remote clients sequentially through the same socket. It implies that UDP sockets are not identified by the remote address, but only by the local address, although each message has an associated remote address.

so can I create a distinct UDP socket for each Client like I do for TCP sockets?
note: please explain with socket class if possible not UDPClient class.
    private void SocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success)
        {
            switch (e.LastOperation)
            {
                case SocketAsyncOperation.Accept:
                case SocketAsyncOperation.Connect:
                    UDP.Bind(TCP.LocalEndPoint);

code explanation: I thought I can bind a UDP socket in both sides (client/server) after establishing  TCP connection (connect/accept). it is fine for only one client on server. for new clients server throws an Exception because it can't bind multiple sockets with one localEndPoint . and clients can be more than all available ports. so i can't bind a UDP socket to a distinct localEndPoint for each client.
I knew that i can create a unique UDP socket and pass receiving messages to respective client object on server but its a bit nasty. thanks!

A: You could run a Task per unique source IP:Port combination.  This would allow you to easily maintain a state machine for each unique incoming source IP:PORT combination.  System.IO.Pipelines makes it really easy to tie this together.
First set up a UDPListener Task that kind of mimics a TCPListener, for each new IP:PORT spin up a Task to process that port, create a Pipe and eveytime data comes from that IPEndpoint, put the data into the PipeWriter
    static async Task StartUdpListener()
    {
        // Use a Dictionary to match packets from given connections to give Pipes
        ConcurrentDictionary<string, Pipe> connections = new ConcurrentDictionary<string, Pipe>();

        var udpServer = new UdpClient(new IPEndPoint(IPAddress.Any, 33000));
        while (true)
        {
            // Wait for some data to arrive
            var result = await udpServer.ReceiveAsync();

            if(connections.ContainsKey(result.RemoteEndPoint.ToString()))
            {
                // If we have seen this IPEndpoint before send the traffic to the pipe
                // the task associated with that Pipe willpick the traffic up
                connections.TryGetValue(result.RemoteEndPoint.ToString(), out var p);
                await p.Writer.WriteAsync(result.Buffer);
            }
            else
            {
                // If we have not seen it, make the pipe, stick the data in the pipe
                // and spin up a task to Read/Process the data
                var p = new Pipe();
                connections.TryAdd(result.RemoteEndPoint.ToString(), p);
                await p.Writer.WriteAsync(result.Buffer);
                _ = Task.Run(() => UdpServerClient(result.RemoteEndPoint.ToString(), p));
            }
        }
    }

That's a simplistic view of what the kernel does when it receives a TCPPacket, it sticks it in a socket buffer for you to read via a stream.
A UDP Server Client task would look something like this:
    static async Task UdpServerClient(string serverName,Pipe p)
    {
        while (true)
        {
            var readResult = await p.Reader.ReadAsync();
            var message = Encoding.ASCII.GetString(readResult.Buffer.FirstSpan.ToArray());
            Console.WriteLine($"Server: {serverName} Received: {message}");
            p.Reader.AdvanceTo(readResult.Buffer.End);
        }
    }

And for completeness, a few clients, these would normally be on different machines, but for the sake of simplicity we'll run them as Tasks.
    static async Task UdpClientClient(string messageToSend)
    {
        var client = new UdpClient();
        client.Connect("127.0.0.1", 33000);
        for(var i=0;i<5;i++)
        {
            var message = ASCIIEncoding.ASCII.GetBytes(messageToSend + " #"+ i.ToString());
            await client.SendAsync(message, message.Length);
            await Task.Delay(1000);
        }
    }
}

Link them all together:
    static async Task Main(string[] args)
    {
        _ = Task.Run(() => StartUdpListener());

        _ = UdpClientClient("hi Server!");
        _ = UdpClientClient("I am here server...");
        await UdpClientClient("Me too server!");
    }

And you get this:
Server: 127.0.0.1:53183 Received: Me too server! #0
Server: 127.0.0.1:53182 Received: I am here server... #0
Server: 127.0.0.1:53181 Received: hi Server! #0
Server: 127.0.0.1:53182 Received: I am here server... #1
Server: 127.0.0.1:53183 Received: Me too server! #1
Server: 127.0.0.1:53181 Received: hi Server! #1
Server: 127.0.0.1:53182 Received: I am here server... #2
Server: 127.0.0.1:53183 Received: Me too server! #2
Server: 127.0.0.1:53181 Received: hi Server! #2
Server: 127.0.0.1:53182 Received: I am here server... #3
Server: 127.0.0.1:53181 Received: hi Server! #3
Server: 127.0.0.1:53183 Received: Me too server! #3
Server: 127.0.0.1:53183 Received: Me too server! #4
Server: 127.0.0.1:53181 Received: hi Server! #4
Server: 127.0.0.1:53182 Received: I am here server... #4

Of course you need error checking, seeing if the client is still there etc.


text:
Q: How to Generate a Map in Java? I trying to complete a RPG game for a project, but have no idea on how to make the game map.
It doesn't need to be graphical, but the code for the whole map and each tile must be correct.
So far, I thought about making a non-matricial map (as request by the professor) by using an ArrayList which contain all the linked tiles.
public abstract class Casella {
/**
 * @uml.property name="tabellone"
 * @uml.associationEnd multiplicity="(1 1)" inverse="casella:Tabellone"
 * @uml.association name="contains"
 */

private int id;
private boolean free = true;
private List adjacent;
private List items;
private Tabellone tabellone = null;

public void in(){
    free = false;
}

public void out(){
    free = true;
}

}

This was the code for a single tile (which has 3 classes that extends it). I still have no idea on how to put together and generate a map.
Thank you for your time.

A: Don't start with the implementation, start with how you would like to use the map. That will give you some constraints how to implement it. For example:
When drawing the map, how do you access it? By coordinate? Or by "go west from tile X"?
[EDIT] I suggest to start with the main loop of the RPG game. You'll need to place the character/token somewhere (i.e. it needs some kind of relation to a tile).
Then you need to move the character. A character must be able to examine the current tile (opponents, items, type). It needs a way to know how it can move (i.e. is there a wall to the right?)
This gives you an interface for your map: Services which it renders for other objects in the game. When you have an idea of what the interface needs to provide, that should give you an idea how to implement the map (the data structure).
As for generating a map, use a random number generator plus some "common sense". Have a look at the adjacent tiles: When they are all city, this tile is probably city, too. Same for plains. Hills are singular items, and they are least frequent.
Run this code, print the map as ASCII ("C"ity, "P"lain, "H"ill) to see if it works.

A: To generate a map like this without using a matrix, I recommend starting with a center tile and then populating the map outwards by using a modified breadth first search algorithm. First of all, we'll need something a little better than a list of adjacent tiles. You could simply have four variables, one for each direction that stores the next tile, as such:
private Tabellone up = null;
private Tabellone down = null;
private Tabellone left = null;
private Tabellone right = null;

Say we start with the center-most tile. All you have to do now is figure out how many of the directions are null, and create a new Tablellone object for each direction, making sure to set each of the variables in this current object and to set the appropriate opposite variable in the object created.
Tabellone adj = new Tabellone();
up = adj;
adj.setDown(this);

Once you've filled out all of the directions on this tile, you then choose one of the other tiles you've created and perform the same operation. This is where the breadth-first search algorithm comes in. You can use a queue to go through each tile you've created and fill out the directions. To make the algorithm stop, simply set a limit on the number of tiles you want to create and use a counter to keep track of how many have been created.
int count = 0;
ArrayList<Tabellone> queue = new ArrayList<Tabellone>()
queue.add(/*center tile*/);
while (count < 100) { //if we want 100 tiles
  //take out the center tile from the beginning of the array list, create a tile for each direction and add those tiles to the array list, then increment count by 1.
}

Note: This algorithm as it stands will create a diamond shaped map, if you want a square, you'd need to have a variable for each diagonal direction as well.
Of course, if this seems a little more complicated than you'd like, I'd recommend a coordinate system.

A: The walls, baggs and areas are special containers, which will hold all the walls, baggs and areas of the game.
private String level =
          "    ######\n"
        + "    ##   #\n"
        + "    ##$  #\n"
        + "  ####  $##\n"
        + "  ##  $ $ #\n"
        + "#### # ## #   ######\n"
        + "##   # ## #####  ..#\n"
        + "## $  $          ..#\n"
        + "###### ### #@##  ..#\n"
        + "    ##     #########\n"
        + "    ########\n";

This is the level of the game. Except for the space, there are five characters. The hash (#) stands for a wall. The dollar ($) represents the box to move. The dot (.) character represents the place where we must move the box. The at character (@) is the sokoban. And finally the new line character (\n) starts a new row of the world.

A: Is speed or memory a huge concern for this project?  If not, why don't you use a 2d array?
Something like
Casella map [][] = new Casella[xSize][ySize];

From here it is easy to conceptualize, just picture it as an excel spreadsheet where each cell is a tile on the map.
The way you are going is fine though, just a little hard to conceptualize sometimes. You have a List of adjacent tiles.  So, when creating your map you start somewhere, possibly top left, and go from there.
You could use nested for loops in order to set up the map, and to help determine the edge items.
for(int i = 0; i < XSIZE ; ++i)
    for(int j = 0; j < YSIZE ; ++j)
        if(j==0) //found left edge (i.e. no adjacent ones to the left)
        if(j==(YSIZE)) //found right edge (you get the picture)

The point of using the loops, and checking the edges, is that you are going to need to link backwards and forward, up and down for each tile except at the edges, where you will have either 2 or 3 links instead of 4.

A: The code needs to be correct really isn't a functional requirement, so its hard to say exactly what is correct without knowing more about your game/map.
Assuming you have a map that has X tiles and no ordered adjacency a non-matricial solution is best, a common solution is to just model it like a graph using either adjacency list for non-symmetric adjacency or incidence list for symmetric adjacency. If youre using an incidence list you need an edge object that contain the vertices the edge is connecting, if youre using adjacency list a multimap might be cool to use.
If you want a non-matricial solution with ordered adjacency AlbertoPL has the solution for that.
Assuming you have a map thats X tiles wide and Y tiles tall and the tiles that are next to each other are adjacent, so that each tile has at max 4 and min 2 adjacent tiles you could use a matrix to access the tiles and also represent adjacency by matricial adjacency. The idea is that map[Y][X] is adjacent to map[Y+1][X] and map[Y][X+1] and reversely.
This solution could also fit max 6 and min 3 tile adjacency if tile [Y+1][X+1] is adjacent to tile [Y][X].
Upside to this is that you can easily parse the map, and since it has 2 dimensions its natural to model it like this.
Downside is that once a tile is set, you cant change its adjacency without changing the matrix. As this isnt what you professor suggested you might not want to do it, but if you have (static) ordered adjacency this might be easiest way to do it.

A: I managed this by using adjacency lists.
Each cell will have an ArrayList containing the indexes of the adjacent cells. Those indexes are the ones that the said cell have in the map ArrayList of cells.
http://en.wikipedia.org/wiki/Adjacency_list

A: If it's a tile-based map, then each room has a fixed relationship with its adjacent rooms. You may not need to worry about co-ordinates (although it might be simpler if the tiles are square), but you will need to worry about directions.
If the tiles are square, cardinal directions (n, s, e, w) may be all you need care about. If they're hex tiles, you can number your exits 1-6 (perhaps with static final constants). Then each adjacent tile may be linked to this one along with its exit.

A: As said by Aaron, you need to decide first how the maping coordinates will be.
But you are not constrained by an X-Y-Z coordinate system. For instance, each tile could be linked to any other tile on your map. It all depends on how you want to build it.
You say that you're building an RPG game, then you need to have a good view of the terrain surround your character. Is it multi-level? How does the character move from one tile to another? Is the movement one way?
There are, literally, dozens of question to be asked when designing a map for a game.
You need to plan it very well first, before starting coding.


text:
Q: Apache Arrow in Scala: AbstractMethodError on loadBatch I'm trying to load Arrow file into scala. But every time I call ethier arrowStreamReader.loadNextBatch() nor arrowFileReader.loadRecordBatch(arrowBlock), the JVM print the error below:
An exception or error caused a run to abort: org.apache.arrow.memory.NettyAllocationManager$1.create(Lorg/apache/arrow/memory/BufferAllocator;J)Lorg/apache/arrow/memory/AllocationManager;
java.lang.AbstractMethodError: org.apache.arrow.memory.NettyAllocationManager$1.create(Lorg/apache/arrow/memory/BufferAllocator;J)Lorg/apache/arrow/memory/AllocationManager;

I cannot find out what's going on, so need your help, thanks!
Here is my repo: https://github.com/oliverdding/hpient
It's the test from src/test/scala/ArrowStreamTest.scala
Below is the test code:
  test("arrow from file") {
    Using(getClass.getResourceAsStream("/table_engines.arrow")) {
      arrowFileStream =>
        Using(
          new SeekableInMemoryByteChannel(IOUtils.toByteArray(arrowFileStream))
        ) { channel =>
          val seekableReadChannel = new SeekableReadChannel(channel)
          Using(
            new ArrowFileReader(
              seekableReadChannel,
              new RootAllocator(Integer.MAX_VALUE)
            )
          ) { arrowFileReader =>
            val root = arrowFileReader.getVectorSchemaRoot
            println(s"schema is ${root.getSchema}")

            val arrowBlocks = arrowFileReader.getRecordBlocks
            println(s"num of arrow blocks is ${arrowBlocks.size()}")

            arrowBlocks.asScala.foreach { arrowBlock =>
              if(!arrowFileReader.loadRecordBatch(arrowBlock)) {
                throw new IOException("Expected to read record batch")
              }
              val fieldVectorItr = root.getFieldVectors.iterator()
              val sparkVectors = fieldVectorItr.asScala
                .map[ColumnVector] { fieldVector =>
                  println(s"parsing the vector $fieldVector")
                  new ArrowColumnVector(fieldVector)
                }
                .toArray
              Using(new ColumnarBatch(sparkVectors, root.getRowCount)) {
                columnarBatch =>
                  println("Got it --->")
                  println(
                    s"rows: ${columnarBatch.numRows()}; cols: ${columnarBatch.numCols()}"
                  )
              }
            }
          }
        }
    }
  }

And my sbt file:
ThisBuild / version := "0.1.0-SNAPSHOT"
ThisBuild / scalaVersion := "2.13.7"
ThisBuild / organization := "com.github"

val arrowVersion = "6.0.1"

lazy val root = (project in file("."))
  .settings(
    name := "hpient",
    idePackagePrefix := Some("com.github.oliverdding.hpient"),
    libraryDependencies ++= Seq(
      // Apache Spark
      "org.apache.spark" %% "spark-core" % "3.2.0",
      "org.apache.spark" %% "spark-sql" % "3.2.0" % "provided",
      // Apache Arrow
      "org.apache.arrow" % "arrow-compression" % arrowVersion,
      "org.apache.arrow" % "arrow-format" % arrowVersion,
      "org.apache.arrow" % "arrow-vector" % arrowVersion,
      "org.apache.arrow" % "arrow-memory" % arrowVersion pomOnly(),
      // STTP
      "com.softwaremill.sttp.client3" %% "core" % "3.3.18",
      // Scala Test
      "org.scalatest" %% "scalatest" % "3.2.10" % Test
    )
  )

A: Not sure I can help, but your example code helped me a lot for my own purpose; didn't know about the ColumnarBatch before. Interesting to go back to rows and a DataFrame from there (I get an arrow buffer from somewhere).
We use something like:
    while (reader.loadNextBatch()) {
      reader.getRecordBlocks.asScala.map { row =>
        val fieldVectorItr = root.getFieldVectors.iterator()
        val sparkVectors = fieldVectorItr.asScala
          .map[ColumnVector] { fieldVector =>
            new ArrowColumnVector(fieldVector)
          }
          .toArray
        val cBatch = new ColumnarBatch(sparkVectors, root.getRowCount)
        ...

Still on spark 3.1.2 and arrow 5 here. As arrow libraries in our project we have arrow-vector and arrow-memory-netty.

A: I was having the same error, then I realized that there is some issue with the spark implementation of arrow. If you remove from your sbt the calls to spark it should solve your problem. Also acording to https://arrow.apache.org/docs/java/install.html you should use arrow-memory-netty:
https://mvnrepository.com/artifact/org.apache.arrow/arrow-memory-netty
libraryDependencies += "org.apache.arrow" % "arrow-memory-netty" % arrow_version


text:
Q: In Linux , how to monitor the progress of shell script during execution in remote server using ssh and expect I have below code in a shell script connect.sh. The remote script will take minimum 1 hour to complete the execution. I am able to see the output of the below script in $local_dir/file.tmp only after the remote script execution is completed where I have to wait for one hour.
How to monitor the output/progress of remote script parallely during execution?
cat connect.sh:
#!/bin/bash
local_dir="/scratch"

/usr/bin/expect > "$local_dir/file.tmp" << EOF

    set timeout -1
    spawn ssh -o "StrictHostKeyChecking no" "user@host" "cd /u01; ./remote_script.py arg1 arg2 arg3 arg4"
    expect "user@host's password:"
    send "$pwd\r"
    expect "*#*"
EOF

A: The log will collect whatever remote_script.py prints. There will be buffering, so if it only prints a few lines, you will not see them until the job finishes, or until the writer forcibly flushes the buffers.
As a workaround of sorts, maybe change remote_script.py so that it prints progress reports to standard error.  The Python logging module makes this straightforward and intuitive.
import logging

def main():
    logging.info('Starting up ...')
    # Do startup stuff
    for n in range(100000):
        if n % 10000 == 0:
            logging.info('Progress: {0}/100000'.format(n))
        # do more things in each iteration

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO,
        format='%(module)s:%(asctime)s:%(message)s')
    main()

A: expect has to buffer its output in order to match patterns.
You can define the buffer size and take action when the buffer fills. Like this:
set match_max 4096    ;# or some other value, not too small
expect {
    full_buffer {
        puts -nonewline "."
        fflush stdout
        exp_continue
    }
    "#" {puts ""}
}
send "exit\r"
expect eof

This will should print a dot for each 4K of data seen , a kind of progress bar. But you haven't shared how much data the remote script generates, so this is really a stab in the dark.


text:
Q: Dynamics AX strange index functionality At work we have a customer which doesn't allow synchronizing. They have a database trigger which stops all Dynamics' synchronization stuff.
Now we are moving on to a plan where the synchronisation is allowed but I have to make a list of all indexes that do not match between AX and the SQL database.
That for the story behind my question. The real question is the following:
How does AX determine where it needs to add RecID to the index fields (in SQL only)?
Currently, I have a table with 5 indexes.

(source: smartus.be)

(source: smartus.be)
All these indexes (I know they are not optimal) have 1 field. The properties AllowDuplicates and Enabled are both set to Yes.
At table level they properties PrimaryIndex and ClusteIndex are both empty and CreateRecIdIndex is set
But now if I look at SQL, I can see that one index always has DATAAREAID, field, RECID as its fields.

(source: smartus.be)
The other indexes simply have DATAAREAID and the field specified in AX.

(source: smartus.be)
When I delete all indexes and I synchronize again to test the case, all the indexes are rebuild and the same one has RECID again.
As I can see at property level of the index and the table's fields, there is no indication why that index should have the RecID added. It's the second index from the table.
So does anybody have a clue why AX is doing this? My guess is that AX wants one index to be unique what I understand, but why that specific index.
Regards,
Vincent

A: You see this behavior, when:

*

*you did not enable the CreateRecIdIndex property on the table

*you did not specify a unique index

AX insists on having at least one unique index in order to be able to update a record. It selects the "smallest" index, then appends RecId. The spec states it takes the first.

If you do not create at least one unique index, Microsoft Dynamics AX creates one by combining the first index and the RecId.


text:
Q: Metatags con o sin acento ¿Los metatags deben ponerse con o sin acento?
Es decir, así:
<meta name="keywords" content="camión, árbol, lápiz"/>

¿O así?
<meta name="keywords" content="camion, arbol, lapiz"/>

Mi duda realmente es si los indexadores pueden reconocer los acentos.

A:
Mi duda realmente es sí los indexadores pueden reconocer los acentos.

SI, los buscadores pueden reconocer los acentos de tus metatags sin embargo esto afectará de manera directa los resultados de búsqueda en los mismos, simplemente te aconsejaría añadir la codificación que ocupes, por ejemplo:
<meta charset="UTF-8">

Aquí puedes ver una búsqueda en google y comparar la diferencia de resultados con esta otra respecto a la palabra Avion y Avión, respectivamente.
Como puedes observar la primera búsqueda con la palabra Avion nos arrojó:

Cerca de 100,000,000 resultados (0.63 segundos)

Y con Avión:

Cerca de 56,800,000 resultados (0.66 segundos)

Aquí tienes otro ejemplo con dos palabras más sin tildes, y las mismas con tilde; massotherapie montreal, massothérapie montréal.
En conclusión puedes ponerlos con tilde sin embargo de un modo u otro la búsqueda se verá directamente afectada a través de los navegadores.

A: Creo que no habria problema , aunque haciendo un poco de busqueda la especificacion  del charset no tiene nada que ver con la codificacion de las metas.
charset: Especifica la codificación de caracteres para el documento HTML
<meta charset="UTF-8">

entonces llegamos a concluir que el UTF-8 solo codificara al contenido del html y no así a los meta.
pero dando una alternativa a tu problema, puedes tener varios
<head>
  <meta name="description" content="Free Web tutorials">
  <meta name="keywords" content="HTML,CSS,JavaScript">
  <meta name="author" content="John Doe">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

con eso tu puedes poner un meta con acento y otro sin acento


text:
Q: I seem to be missing a few important concepts with PhoneGap I'm planning on developing an app on multiple platforms and I'm thinking that PhoneGap might be perfect for me. I had been reading that it's one codebase for all platforms but looking at the PhoneGap guide it seems there are separate instructions for each platform. So if i want to develop for iOS, Android, BB and WP7 I need to write 4 different sets of code? I'm sure i'm missing something fundamental here.
Aside from that, how do people usually approach a PhoneGap build? You obviously / probably want the finished app to look like a native app - is it more common than not to use jQuery Mobile together with PhoneGap?
Is there a preferred IDE? I see, in the guide, for iOS they seem to suggest Xcode. I'm fine using Xcode but it seems a bit overkill for HTML & CSS. Do I need to develop in Xcode and if not how do i approach it? Use a different IDE / Text Editor and then copy paste into Xcode for building and testing?
I know this question is long-winded and fundamental but it something which i don't think is properly addressed in the guides.
Thanks.

A: Phonegap only provides the framework for shared code on different platforms. In order to build the app for each platform you have to use the native toolsets so; Visual Studio for WinPhone, XCode for iOS, Eclipse w/ Android SDK for Android, etc.
You can reuse all your PhoneGap code but you need to create projects on each platform to build and submit the apps to the appropriate mobile stores.


text:
Q: Python list can't delete first item I'm trying to create a list of text files from a directory so I can extract key data from them, however, the list my function returns also contains a list of the file pathways as the first item of the list. I've tried del full_text[0] which didn't work, as well as any other value, and also the remove function. Any ideas as to why this might be happening?
Thanks
import glob

file_paths = []
file_paths.extend(glob.glob("C:\Users\12342255\PycharmProjects\Sequence      diagrams\*"))
matching_txt = [s for s in file_paths if ".txt" in s]
print matching_txt
full_text = []
def fulltext():
    for file in matching_txt:
        f = open(file, "r")
        ftext = f.read()
        all_seqs = ftext.split("title ")
        print all_seqs
full_text.append(fulltext())
print full_text

A: You can use slicing to get rid of the first element - full_text[1:]. This creates a copy of the list. Otherwise, you can full_text.pop(0) and resume using full_text

A: I see at least two ways to do so:
1) you can create a new list from first position e.g. newList = oldList[1:]
2) use remove method - full_text.remove(full_text[0])


text:
Q: How to dislay mismatch lines when comparing two text files? I'm new to VB.Net. I've implemented scripting to compare two text files that checks if the value or data is different from each other. The only problem is it shows only one line instead of two
Below is the data that is in text A and C:
Text A: Orange,Apple,Mango,Strawberry,Banana
Text B: Orange, Apple, Mango, Blueberry, Grapes
Here is my script
Sub Main()
    Const ForReading = 1
    Dim objFile1, objFile2, objFile3
    Dim objFSO = CreateObject("Scripting.FileSystemObject")
    objFile1 = objFSO.OpenTextFile("C:\Scripts\A.txt", ForReading) 'Current.txt represents Text from AWS network
    Dim strAddresses, strCurrent, strNoAddress
    strAddresses = objFile1.ReadAll
    objFile1.Close()

    objFile2 = objFSO.OpenTextFile("C:\Scripts\C.txt", ForReading) 'Current.txt represents Text from Shell network

    Do Until objFile2.AtEndOfStream
        strCurrent = objFile2.ReadLine
        If InStr(strAddresses, strCurrent) = 0 Then
            strNoAddress = strCurrent & vbCrLf

        End If
    Loop

    objFile2.Close()

    objFile3 = objFSO.CreateTextFile("C:\Scripts\Differences.txt")

    objFile3.WriteLine(strNoAddress)
    objFile3.Close()
End Sub

A: Your code does not work because you overwrite strNoAddress everytime the if conditions is true:
strNoAddress = strCurrent & vbCrLf

So when you hit Blueberry, strNoAddress becomes Blueberry\n.
When you hit Grapes,  strNoAddress becomes Grapes\n instead of Blueberry\nGrapes\n.
You want to concatenate the strings instead:
strNoAddress &= strCurrent & vbCrLf

A more "up-to-date" version of your code without the legacy/leftover functions of VB6 could look like:
Dim addresses = File.ReadAllLines("C:\Scripts\A.txt")

Dim noAdress = String.Empty
Using reader = new StreamReader("C:\Scripts\B.txt")
    Do Until reader.EndOfStream
        Dim current = reader.ReadLine
        If Not addresses.Contains(current) Then
            noAdress &= current & Environment.NewLine
        End If
    Loop
End Using
...

Or, to make it even more simple (good enough for small files, and without a trainling newline):
Dim fileA = File.ReadAllLines("C:\Scripts\A.txt")
Dim fileB = File.ReadAllLines("C:\Scripts\B.txt")
Dim noAdress = String.Join(Environment.NewLine, fileB.Where(Function(b) Not fileA.Contains(b)))


text:
Q: Navigation in a graph The problem
Let $G=(V,E)$ be a graph. $k = O\left(\log(|V|)\right)$ distinct vertices are picked randomly from $V$. We call the set of chosen $k$ vertices $T$.
We define the graph metric $d$ for every two vertices $x,y$ to be $d(x,y)$: The length of shortest path between $x$ and $y$.
For every $a,b \in T$, $d(a,b)$ is known. This is called the "global knowledge". Also for every $x \in V, a \in T$, the distance $d(x,a)$ is known. This is called the "local knowledge" for the vertex $x$.
For a vertex $x \in V$, The address of $x$, $A(x)$, is a set of shortest paths from $x$ to all the vertices in $T$.
A person should travel from $x$ to $y$. This is done by hopping from one vertex to one of its neighbours.
Information given:

*

*$A(y)$

*The global knowledge

*While staying at the vertex $z$, the local knowledge with respect to $z$ is known.

Find an algorithm to travel from $x$ to $y$. (It might be a probabilistic one).
The following properties are required:

*

*The total length of the journey from $x$ to $y$ should not be more than $\log(|V|)\cdot d(x,y)$

*Assume that use the proposed algorithm to send $R$ people between random pairs $x,y \in V$. Let $J(x)$ be the amount of journeys passing through $x$. Then $J(x) \leq J(y)\cdot\log(|V|)$ with high probability when $R \rightarrow \infty$.

My attempts
I tried a few things, though I didn't have much progress. If you have any kind of idea, please post it.
Naive solution
The naive solution to go from $x$ to $y$ would be to use an intermediate vertex $t \in T$: First we travel from $x$ to $t$, and then as we know $A(y)$, we could follow a shortest path from $t$ to $y$.
This generally works, however the load on the vertices of $T$ will be too high, which means that the second requirement from the algorithm will not be satisfied.
Metric information
Using the basic properties of metrics, we can conclude the following:
$\max_{a \in T} \left|d(a,y) - d(x,a)\right| \leq d(x,y) \leq \min_{a \in T}\left(d(x,a) + d(a,y)\right)$
This could give us some kind of approximation to how far we are from $y$ at any point of the journey, but this approximation is usually not so good.
Continuity
When hopping from a vertex $z$ to his neighbour $w$, one can prove that the distance to each of the vertices inside $T$ will change only by $+1$, $-1$ or $0$. I didn't manage to get further with this idea, but it is kind of interesting.
Embedding
If we manage to embed the graph in an euclidean space (Maybe of high dimension) so that all distances are preserved, we could use euclidean distance and have some better understanding of the geometry of the graph. Just an idea. I never managed to do anything of this sort.


text:
Q: Springboot filter executed in case of permitAll urls as well I am new to springboot and trying to implement security where no filters are applied to my login, signup and home urls.
I am using springboot 2.7.1
I am expecting antMatchers("/**/signup").permitAll() to remain free of any security filter.
Upon debugging, I found that my signup url was being hit and user details were saved, but my AuthorizationFilter was also being executed .
This is my SecurityFilterChain :
@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        AuthenticationManagerBuilder authenticationManagerBuilder=http.getSharedObject(AuthenticationManagerBuilder.class);
        authenticationManagerBuilder.userDetailsService(userLoginService).passwordEncoder(bCryptPasswordEncoder);
        AuthenticationManager authenticationManager=authenticationManagerBuilder.build();

        http.csrf().disable().authorizeHttpRequests()
                .antMatchers("/**/login").permitAll()
                .antMatchers("/**/signup").permitAll()
                .antMatchers("/home/**").permitAll()
                .anyRequest().authenticated().and()
                .addFilter(getAuthenticationFilter(authenticationManager))
                .addFilter(new AuthorizationFilter(authenticationManager))
                .authenticationManager(authenticationManager)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        return http.build();
    }

I don't understand why is it happening this way.

A: When you use permitAll() you are not disabling the filters, you are just specifying that you do not want to apply any authorization checks for that RequestMatcher. All the filters will still work.
The AuthorizationFilter will be invoked but since you configure permitAll() for that endpoint, it will always grant access.


text: Q: Is a surjective isometry an isomorphism? Isomorphism is defined as a bijective linear operator, while isometry is inherently injective but not necessarily surjective. But if we have a surjective isometry, can we say it must be an isomorphism?


text:
Q: Google Drive API. Get id from url I need move a drive file between folders using the Google Drive API and PHP. But in some case I only have the url of the document, and I need to move that file to another folder. But I don't know if is possible to do this having only the file url.
Any body know if its possible and how? I'm looking for it in the documentation but I can't do it.
Thanks.

A: I don't think you can "move" the file like that. The only way it might work would be to try and patch the location of the file  file.patch.  I have never heard of anyone trying to patch the location of a file.
I consulted a colleague who is a Google Drive expert, he said he thought it was broken (patching location). He did a quick test and verified this is a broken feature. All it returns is 403 - insufficient permissions
You will need to download the file and upload it again.

A: I just had a look at the documentation page for patch (https://developers.google.com/drive/v2/reference/files/patch) and it looks like Google has silently changed the API. There are now two new query parameters addParents and removeParents which look like they will do what you want. NB I haven't tested this as it has only appeared in the last couple of weeks.


text:
Q: Component is not defined// React and Webpack I'm building a React App that will pull from Opendota's api and display the heroes to me. This is my first time working with API's. I build the App from scratch, so I didn't use CRA (create-react-app).
This is my App.js
import React from 'react';
import {hot} from "react-hot-loader";
import Heroes from "./components/Heroes"

class App extends Component {
    render() {
        return (
            <Heroes heroes={this.state.heroes} />
        )
    }

    state = {
        heroes: []
    };

    componentDidMount() {
        fetch('https://api.opendota.com/api/heroes')
            .then(res => res.json())
            .then((data) => {
                this.setState({ heroes: data })
            })
            .catch(console.log)
    }
}

export default hot(module)(App);

Heroes.js
import React from 'react'

const Heroes = ({heroes}) => {
    return (

Hero List

            {heroes.map((hero) => (

{hero.name}

{hero.id}

            ))}

    )
};

export default Heroes

Just looking for an answer that will point me in the right direction.

A: You have not imported Component from react.So yo must have to import Component from 'react' .so your code will be looks like
import React,{Component} from 'react';
import {hot} from "react-hot-loader";
import Heroes from "./components/Heroes"

class App extends Component {
   render() {
      return (
          <Heroes heroes={this.state.heroes} />
      )
   }

   state = {
      heroes: []
   };

   componentDidMount() {
      fetch('https://api.opendota.com/api/heroes')
        .then(res => res.json())
        .then((data) => {
            this.setState({ heroes: data })
        })
        .catch(console.log)
    }
   }

 export default hot(module)(App);

A: The way to work with component of React
import React, {Component} from 'react';
class App extends Component{}

other way if you don't import, directly import
import React from 'react';
class App extends React.Component{}


text:
Q: integrating jquery ui dialog with knockoutjs I am trying to create knockoutjs bindings for jquery ui dialogs, and cannot get the dialog to open. The dialog element is created correctly, but seems to have display: none that calling dialog('open') doesn't remove. Also, the call to dialog('isOpen') returns the dialog object rather than a boolean.
I am using the latest knockoutjs and jquery 1.4.4 with jquery ui 1.8.7. I've also tried it with jQuery 1.7.1 with the same results. Here's my HTML:

foo dialog

    <button id="openbutton" data-bind="dialogcmd: {id: 'dialog'}" >Open</button>
    <button id="openbutton" data-bind="dialogcmd: {id: 'dialog', cmd: 'close'}" >Close</button>

and this is the javascript:
var jQueryWidget = function(element, valueAccessor, name, constructor) {
    var options = ko.utils.unwrapObservable(valueAccessor());
    var $element = $(element);
    var $widget = $element.data(name) || constructor($element, options);
    $element.data(name, $widget);

};

ko.bindingHandlers.dialog = {
        init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
            jQueryWidget(element, valueAccessor, 'dialog', function($element, options) {
                console.log("Creating dialog on "  + $element);
                return $element.dialog(options);
            });
        }
};

ko.bindingHandlers.dialogcmd = {
        init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
            $(element).button().click(function() {
                var options = ko.utils.unwrapObservable(valueAccessor());
                var $dialog = $('#' + options.id).data('dialog');
                var isOpen = $dialog.dialog('isOpen');
                console.log("Before command dialog is open: " + isOpen);
                $dialog.dialog(options.cmd || 'open');
                return false;
            });
        }
};

var viewModel = {
    label: ko.observable('dialog test')
};

ko.applyBindings(viewModel);

I have set up a JSFiddle that reproduces the problem.
I am wondering if this has something to do with knockoutjs and event handling. I tried returning true from the click handler, but that did not appear to affect anything.

A: It looks like writing to the widget to .data("dialog") and then trying to operate on it is causing an issue.  Here is a sample where .data is not used and the open/close is called based on the element:  http://jsfiddle.net/rniemeyer/durKS/
Alternatively, I like to work with the dialog in a slightly different way.  I like to control whether the dialog is open or closed by using an observable.  So, you would use a single binding on the dialog itself.  The init would initialize the dialog, while the update would check an observable to see if it should call open or close.  Now, the open/close buttons just need to toggle a boolean observable rather than worry about ids or locating the actual dialog.
ko.bindingHandlers.dialog = {
        init: function(element, valueAccessor, allBindingsAccessor) {
            var options = ko.utils.unwrapObservable(valueAccessor()) || {};
            //do in a setTimeout, so the applyBindings doesn't bind twice from element being copied and moved to bottom
            setTimeout(function() {
                options.close = function() {
                    allBindingsAccessor().dialogVisible(false);
                };

                $(element).dialog(options);
            }, 0);

            //handle disposal (not strictly necessary in this scenario)
             ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
                 $(element).dialog("destroy");
             });
        },
        update: function(element, valueAccessor, allBindingsAccessor) {
            var shouldBeOpen = ko.utils.unwrapObservable(allBindingsAccessor().dialogVisible),
                $el = $(element),
                dialog = $el.data("uiDialog") || $el.data("dialog");

            //don't call open/close before initilization
            if (dialog) {
                $el.dialog(shouldBeOpen ? "open" : "close");
            }
        }
};

Used like:

foo dialog

Here is a sample:
http://jsfiddle.net/rniemeyer/SnPdE/

A: I made a little change to RP Niemeyer's answer to allow the dialog's options to be observables
http://jsfiddle.net/YmQTW/1/
Get the observables values with ko.toJS to initialize the widget
setTimeout(function() {
    options.close = function() {
        allBindingsAccessor().dialogVisible(false);
    };

    $(element).dialog(ko.toJS(options));
}, 0);

and check for observables on update
//don't call dialog methods before initilization
if (dialog) {
    $el.dialog(shouldBeOpen ? "open" : "close");

    for (var key in options) {
        if (ko.isObservable(options[key])) {
            $el.dialog("option", key, options[key]());
        }
    }
}

A: Adding this here because this is what most people find when searching on issues with jQuery UI Dialog and Knockout JS.
Just another option to avoid the "double binding" issue explained in the above answer.  For me, the setTimeout() was causing other bindings to fail that require the dialog to be initialized already.  The simple solution that worked for me was making the following changes to the accepted answer:

*

*Add class='dialog' to any elements using the custom dialog binding.

*Call this after page load, but before calling ko.applyBindings():
$('.dialog').dialog({autoOpen: false});
Remove the setTimeout inside the init of the custom binding, and just call the code directly.
Step 2 makes sure that any jQuery UI Dialogs have been initialized prior to any KO bindings.  This way jQuery UI has already moved the DOM elements, so that you don't have to worry about them moving in the middle of applyBindings.  The init code still works as-is (other than removing setTimeout) because the dialog() function will just update an existing dialog if already initialized.
An example of why I needed this is due to a custom binding I use to update the title of the dialog:
ko.bindingHandlers.jqDialogTitle = {
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).dialog('option', 'title', value);
    }
};

I use a separate binding for this instead of the update function for the main dialog binding, because I only want to update the title, not other properties such as height and width (don't want the dialog to resize just because I change the title).  I suppose I could also use update and just remove height/width, but now I can do both/either and not worry about the setTimeout being completed or not.

A: This is a variation of the great RP Niemeyer binding handler, which is useful for a differente scenario.
To allow the edition of an entity, you can create a
 with edition controls, and use a with binding, which depends on an observable made on purpose for the edition.
For example, to allow the edition of a person, you can create and observable like editedPerson, and create a div with edition controls, with a binding like this:
data-bind="with: editedPerson"

When you add a person to the observable lke so:
vm.editedPerson(personToEdit);

the binding makes the div visible. When you finish the edition, you can set the observable to null, like so
vm.editedPerson(null);

and the div will close.
My variation of RP Niemeyer's bindingHandler allows to automatically show this div inside a jQuery UI dialog. To use it you simply have to keep the original with binding, and specify the jQuery UI dialog options like so:
data-bind="with: editedPerson, withDialog: {/* jQuery UI dialog options*/}"

You can get the code of my binding handler, and see it in action here:
http://jsfiddle.net/jbustos/dBLeg/
You can modify this code easily to have different defaults for the dialog, and even to make these defaults configurable by enclosing the handler in a js module, and adding a public configuration function to modify it. (You can add this function to the binding handler, and it will keep working).

// Variation on Niemeyer's http://jsfiddle.net/rniemeyer/SnPdE/

/*
This binding works in a simple way:
1) bind an observable using "with" binding
2) set the dialog options for the ui dialog using "withDialog" binding (as you'd do with an standard jquery UI dialog) Note that you can specify a "close" function in the options of the dialog an it will be invoked when the dialog closes.

Once this is done:
- when the observable is set to null, the dialog closes
- when the observable is set to something not null, the dialog opens
- when the dialog is cancelled (closed with the upper right icon), the binded observable is closed

Please, note that you can define the defaults for your binder. I recommend setting here the modal state, and the autoOpen to false.

*/

ko.bindingHandlers.withDialog = {
        init: function(element, valueAccessor, allBindingsAccessor) {
            var defaults = {
                modal: false,
                autoOpen: false,
            };
            var options = ko.utils.unwrapObservable(valueAccessor());
            //do in a setTimeout, so the applyBindings doesn't bind twice from element being copied and moved to bottom
            $.extend(defaults, options)
            setTimeout(function() {
                var oldClose = options.close;
                defaults.close = function() {
                    if (options.close) options.close();
                    allBindingsAccessor().with(null);
                };

                $(element).dialog(defaults);
            }, 0);

            //handle disposal (not strictly necessary in this scenario)
             ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
                 $(element).dialog("destroy");
             });
        },
        update: function(element, valueAccessor, allBindingsAccessor) {
            var shouldBeOpen = ko.utils.unwrapObservable(allBindingsAccessor().with),
                $el = $(element),
                dialog = $el.data("uiDialog") || $el.data("dialog");

            //don't call open/close before initilization
            if (dialog) {
                $el.dialog(shouldBeOpen ? "open" : "close");
            }
        }
};

var person = function() {
    this.name = ko.observable(),
    this.age = ko.observable()
}

var viewModel = function() {
    label= ko.observable('dialog test');
    editedPerson= ko.observable(null);
    clearPerson= function() {
       editedPerson(null);
    };
    newPerson= function() {
        editedPerson(new person());
    };
    savePerson= function() {
        alert('Person saved!');
        clearPerson();
    };
    return {
        label: label,
        editedPerson: editedPerson,
        clearPerson: clearPerson,
        newPerson: newPerson,
        savePerson: savePerson,
    };
}

var vm = viewModel();

ko.applyBindings(vm);
.header {
    font-size: 16px;
    font-family: sans-serif;
    font-weight: bold;
    margin-bottom: 20px;
}

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" rel="stylesheet"/>

    Person editor

    Name:
<input type="text" data-bind="value: $data.name"/>

    Age:
<input type="text" data-bind="value: $data.age"/>

    <button data-bind="click: $parent.savePerson">Ok</button>
    <button data-bind="click: $parent.clearPerson">Cancel</button>

    <button data-bind="click: clearPerson">Clear person</button>
    <button data-bind="click: newPerson">New person</button>

A: There's now this library that has all the JQueryUI bindings for KnockoutJS including, of course, the dialog widget.


text:
Q: Clear Magento Enterprise FPC for specific product We want to clear the full page cache for a specific product - based on the ID of the product (or the URL if needs be). I have found this line:
Mage::app()->cleanCache('catalog_product_'.$this->getId());

In app/code/core/Mage/Catalog/Model/Product.php:
public function cleanCache()
{
    Mage::app()->cleanCache('catalog_product_'.$this->getId());
    return $this;
}

I tried using this like:
Mage::app()->cleanCache('catalog_product_1234');

But it doesn't work. How can we clear the FPC just for one specific product?

A: if you look into Mage_PageCache_Model_Observer_Index
protected function _cleanEntityCache(Mage_Core_Model_Abstract $entity, array $ids)
        {
            $cacheTags = array();
            foreach ($ids as $entityId) {
                $entity->setId($entityId);
                $cacheTags = array_merge($cacheTags, $entity->getCacheIdTags());
            }
            if (!empty($cacheTags)) {
                Mage_PageCache_Model_Cache::getCacheInstance()->clean($cacheTags);
            }
        }

So it looks you should do something like:
 $cacheTags = $product->getCacheIdTags();
 Mage_PageCache_Model_Cache::getCacheInstance()->clean($cacheTags);


text:
Q: What Fedora version has the same base as RHEL and CentOS? RHEL is based on Fedora and the other way around. The present or a future Fedora will be the base of the future RHEL, while the present version of RHEL is based on an older Fedora, which is much longer-term, longer tested, with longer support, with rare updates etc, while present Fedora (27) is fast updating.
There must be a past version of Fedora which is/was the equivalent of the present version of RHEL - and CentOS, which is based on RHEL. Both are now version 7. What older version of Fedora would correspond to their level?

A: This is documented in the Fedora documentation. From the version table there, RHEL 7 is based on Fedora 19 with some changes taken from later versions.
The relationship is quite a bit more complex than a simple table can represent. In particular, the RHEL kernel receives many updates and backports throughout its life, which Fedora kernels don't (the kernels in supported versions of Fedora are continually updated to the latest upstream kernel).


text:
Q: JQuery Content Click Not working I have a class inside an iframe. I am able to change the color of this class using the following jquery code:
$("#chart_iframe0").contents().find(".btn-green").css("background","#BADA55");

This is working fine.
I now what to click on it with jquery so I'm using this code:
However, now i want to perform the same action using "click" event of jquery:
$("#chart_iframe0").contents().find(".btn-green").click();

But this is not working as I want.
Can anyone guide me what's wrong with the second jquery code ? Is it related to the syntax or something else?
Here is the html area of it:

Click me

A: Try using .on() to bind the click event to the element.
$("#chart_iframe0").contents().find(".btn-green").on( "click", function(){
    alert('test');
});


text:
Q: Why do players shift-move units back and forth? I see players shift-click move their units back and forth all the time in replays online. Why do they do that? Wouldn't a hold position command achieve the same thing?

A: A unit moving back-and-forth is can be harder for enemy units to kill (especially with melee units).
A common example of this is in PvZ when Protoss sends a Probe to try and block Zerg's Hatchery.  If the Probe was stationary, it would be a lot easy/quick to kill it; for this reason, Protoss players shift-click and move their Probe all around the Hatchery location to stay alive as long as possible, thereby delaying Zerg's Hatchery.

A: The shift-move, or the "queue" command, can have different meanings.
Shift-move:

*

*To scout different locations around the map, so the scouting unit
checks out more places and dont go somewhere in a straight line.

*To scout around your own or the enemy base.

*To block off the enemy trying to expand or similar buildings.

Shift-attack:

*

*To focus fire a group of units, by killing them one by one. Example:
TvZ Shift-attacking Collosi with Vikings has a better outcome than just
attack moving into them. It saves you time, and enables you to
focus on the other units with your other troops.

*To scout attack, and clean up Pylon, Overlords and such.

A: shift clicking your units around lets the unit move while you go back to your base and keep your macro up and you don't have to worry your units getting surrounded and dead
this is crucial during early game harass/scout to keep the harassing/scouting unit alive


text:
Q: PLCrashReporter header implementation? I need to implement the PLCrashReporter to my application, i have added framework and the code to use it, but i need add header files. I am not sure what to add as header files.
Could you please help me?

A: #import "CrashReporter/CrashReporter.h"

Would be the right answer, if all is right configured.


text:
Q: how to undo and redo chess moves using chessboard.js for analyze mode I am using the chess.js and chessboard.js for my chess a project.
I just want to implement the undo and redo functionality of chess moves.
I am creating "Move Recorder" for chess moves using chessboard.js, through which users can undo and redo chess moves. User is playing from both sides to analyze chess puzzle.
Please let me know if any one can help on this.

A: Typically the game logic, validation and move history recording, aren't done with chessboard.js but with an engine, such as chess.js.
With an engine there might be an undo() or takeback() function, see the chess.js docs for an example:
chess.move('e4');
chess.fen();
// -> 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1'

chess.undo();
// -> { color: 'w', from: 'e2', to: 'e4', flags: 'b', piece: 'p', san: 'e4' }
chess.fen();
// -> 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'

There is also an open branch at chess.js, https://github.com/jhlywa/chess.js/pull/48
this code implements next() and back() functions into the engine, (and a future array for storing the history). These might be what you're looking for, because after you undo, you mention you want to redo.
This branch isn't merged, and I don't think it will be, but it's there to look at; basically just add these two functions:
back: function() {
  var moves = this.history();
  var tmp = new Chess();
  var previous = moves.length-future.length-1;
  for(var i=0;i<previous;i++) {
    tmp.move(moves[i]);
  }
  var previous_fen = tmp.fen();
  tmp.move(moves[previous]);
  future.push(tmp.fen());
  return previous_fen;
},

next: function() {
  return future.pop();
},

and an array
var future = [];

Then you can call back(), analyze the position, and then next() to return to the game state.

A: Start here for the basic design.
data structure used to implement UNDO and REDO option
And I presume there are methods in this framework to keep track of the commands you'll need for designated past actions.
Hope that helps!


text:
Q: Accessing dictionary inside Python List I have a list which contains dictionaries like this:
json_obj = [[{'id': None},{'id': '5b98d01c0835f23f538cdcab'},{'id': '5b98d0440835f23f538cdcad'},{'id': '5b98d0ce0835f23f538cdcb9'}],[{'id': None},{'id': '5b98d01c0835f23f538cd'},{'id': '5b98d0440835f23f538cd'},{'id': '5b98d0ce0835f23f538cdc'}]]

I want it to store in list of lists like this:
y=[['None','5b98d01c0835f23f538cdcab','5b98d0440835f23f538cdcad','5b98d0ce0835f23f538cdcb9'],['None','5b98d01c0835f23f538cd','5b98d0440835f23f538cd','5b98d0ce0835f23f538cdc']]

For reading the id from the dictionary I tried
for d in json_obj:
    print(d['id'])

But I see this error with the above code:
TypeError: list indices must be integers or slices, not str

A: You have a nested list of lists. It sometimes helps to observe this visibly, note the nested [] syntax:
json_obj = [[{'id': None}, {'id': 'abc'}, {'id': 'def'}, {'id': 'ghi'}],
            [{'id': None}, {'id': 'jkl'}, {'id': 'mno'}, {'id': 'pqr'}]]

Your syntax would works for single list:
json_obj = [{'id': None}, {'id': 'abc'}, {'id': 'def'}, {'id': 'ghi'},
            {'id': None}, {'id': 'jkl'}, {'id': 'mno'}, {'id': 'pqr'}]

for d in json_obj:
    print(d['id'])

For nested lists, you can use itertools.chain.from_iterable from the standard library:
json_obj = [[{'id': None}, {'id': 'abc'}, {'id': 'def'}, {'id': 'ghi'}],
            [{'id': None}, {'id': 'jkl'}, {'id': 'mno'}, {'id': 'pqr'}]]

from itertools import chain

for d in chain.from_iterable(json_obj):
    print(d['id'])

Or, without an import you can use a nested for loop:
for L in json_obj:
    for d in L:
        print(d['id'])

A: Using a nested list comprehension.
json_obj = [[{'id': None},{'id': '5b98d01c0835f23f538cdcab'},{'id': '5b98d0440835f23f538cdcad'},{'id': '5b98d0ce0835f23f538cdcb9'}],[{'id': None},{'id': '5b98d01c0835f23f538cd'},{'id': '5b98d0440835f23f538cd'},{'id': '5b98d0ce0835f23f538cdc'}]]
print( [[j["id"] for j in i] for i in json_obj] )

or
for i in json_obj:
    for j in i:
        print(j["id"])

Output:
[[None, '5b98d01c0835f23f538cdcab', '5b98d0440835f23f538cdcad', '5b98d0ce0835f23f538cdcb9'], [None, '5b98d01c0835f23f538cd', '5b98d0440835f23f538cd', '5b98d0ce0835f23f538cdc']]


text:
Q: Render collection of models fields I have AR relation of Post objects. Each post has body field. I need to render collection of this fields through array of posts.
old version (bad perfomance way)
- user.posts.each do |post|
  - if post.body.present?
    = render partial: "application/body", locals: {body: post.body}

I need something like this:
= render partial: "application/body", collection: user.posts, as: :body (but body is posts->post.body)

How to do it right?

A: Since body is a post's field, you can select posts bodies and pass as collection. There is useful pluck method, it selects only specified fields - it is more performant than posts.map(&:body)
= render partial: "application/body", collection: user.posts.pluck(:body), as: :body

A: Just a tip. When iterating active record collection, it's better to use find_each instead of each: https://medium.com/@jonathanabrams/doing-stuff-with-rails-find-each-3f592ae02136
Rewriting it into render .. collection is also a nice option.
If you need to put all code into one line, you can write this:
= render partial: 'application/body', collection: user.posts.where.not(body: [nil, false]), as: :post
Or this:
= render partial: 'application/body', collection: user.posts.where.not(body: [nil, false]).map(&:body), as: :body
Also it would be good to put where condition into scope in Post.rb:
scope :with_title, -> { where.not(posts: { body: [nil, false] })  }
So final version of code would be this:
= render partial: 'application/body', collection: user.posts.with_title.map(&:body), as: :body
For further reading:
https://thoughtbot.com/blog/activerecord-s-where-not-and-nil
https://www.rubyguides.com/2018/10/ruby-map-method/


text:
Q: Regarding the usage of lock records in the implementation of thin-locks in HotSpot I'm having some trouble understanding what the lifecycle of lock records is when dealing with "thin-locks" on HotSpot.
My understanding is that:

When a thread T first attempts to acquire a
lock on object o, it triggers a "thin lock" creation -- a lock record is created on T's stack, on the current frame F, and a copy of
the mark work (that will now be referred as a displaced header) plus a reference
to o is stored on F. Through a CAS operation o's header is made
to reference the lock record (and the last two bits are set to 00
to mark this object as thin-locked!).
There are multiple reasons why the CAS operation could fail, though:

*

*Another thread was quicker to grab the lock, we'll need to turn this thin-lock into a full-blown monitor instead;

*The CAS failed but it can be seen that the reference to the lock record belongs to Ts stack, so we must be attempting to re-enter
the same lock, which is fine. In that case, the lock record of the
current stack-frame is kept null.

Given this, I have a couple of questions:

*

*Why would we create a new lock record each time we attempt to enter a lock? Wouldn't it be preferable to just keep a single lock record for each object o?

*When leaving a synchronized block, I failed to understand how can the VM know whether we should release the lock or whether we're still "unwinding" from a recursive lock.

Anyone could shed some light on this?
References

*

*https://blogs.oracle.com/dave/lets-say-youre-interested-in-using-hotspot-as-a-vehicle-for-synchronization-research

*https://wiki.openjdk.java.net/display/HotSpot/Synchronization

*http://www.diva-portal.org/smash/get/diva2:754541/FULLTEXT01.pdf

*https://www.oracle.com/technetwork/java/biasedlocking-oopsla2006-wp-149958.pdf
Let me quote a paragraph from the last link:

Whenever an object is lightweight locked by a monitorenter bytecode, a
lock record is either implicitly or explicitly allocated on the stack
of the thread performing the lock acquisition operation. The lock
record holds the original value of the object's mark word and also
contains metadata necessary to identify which object is locked. During
lock acquisition, the mark word is copied into the lock record (such a
copy is called a displaced mark word), and an atomic compare-and-swap
(CAS) operation is performed to attempt to make the object's mark word
point to the lock record. If the CAS succeeds, the current thread owns
the lock. If it fails, because some other thread acquired the lock, a
slow path is taken in which the lock is inflated, during which
operation an OS mutex and condition variable are associated with the
object. During the inflation process, the object's mark word is
updated with a CAS to point to a data structure containing pointers to
the mutex and condition variable. During an unlock operation, an
attempt is made to CAS the mark word, which should still point to the
lock record, with the displaced mark word stored in the lock record.
If the CAS succeeds, there was no contention for the monitor and
lightweight locking remains in effect. If it fails, the lock was
contended while it was held and a slow path is taken to properly
release the lock and notify other threads waiting to acquire the lock.
Recursive locking is handled in a straightforward fashion. If during
lightweight lock acquisition it is determined that the current thread
already owns the lock by virtue of the object's mark word pointing
into its stack, a zero is stored into the on-stack lock record rather
than the current value of the object's mark word. If zero is seen in a
lock record during an unlock operation, the object is known to be
recursively locked by the current thread and no update of the object's
mark word occurs. The number of such lock records implicitly records
the monitor recursion count. This is a significant property to the
best of our knowledge not attained by most other JVMs.

Thanks

A:
Why would we create a new lock record each time we attempt to enter a lock? Wouldn't it be preferable to just keep a single lock record for each object o?

Seems like you've missed the main point of lock records. Lock record is not some per object entity, but rather per lock site. If, for example, a method has 3 synchronized blocks, its stack frame may have up to 3 lock records, no matter if it will be 3 different locked objects, or the same object recursively locked 3 times.
Lock records (actually, they are not called so in HotSpot sources; they are usually referred to as a "monitor", "monitor slot", "monitors block", etc.) help to maintain the mapping between a stack frame and its locked monitors. In particular, when a stack frame is removed due to an exception, all locks need to be automatically released. So, think of the monitor slots as something like local variable slots, which can hold references to the same or different objects. Like local variables, monitors are associated with a given stack frame. They hold references to the locked objects, but they are not "locks" themselves.

When leaving a synchronized block, I failed to understand how can the VM know whether we should release the lock or whether we're still "unwinding" from a recursive lock.

A lock record (a monitor slot) holds two things: a reference to the locked object and a so called "displaced header". Displaced header is either a previous (unlocked) value of the object header, or zero, if it was a recursive lock.
As I explained above, if we lock an object 3 times, there will be 3 lock records. Only the first one holds the actual non-zero displaced header, other two will have zeros. This means, first two monitorexit instructions will pop lock records with zeros, realize that it is a recursive lock, and thus will not update the object. When the last lock record is removed, the JVM sees a non-zero value in the displaced header, and stores it back into the real object header, thus marking it unlocked.

A: Note that this is my original attempt to answer the question. It's quite clear to me that the docs linked above answer everything on their own.
As for the first question, the new lock record is created on the stack because it's much cheaper than allocating it on the heap. In many cases, a monitor is never contended, and so this can be a huge win. Stack alloc/free can sometimes be so cheap that it's not even worth considering.
The second question can be answered by noticing that the doc refers to the current frame F. There's always a frame pointer register, and so the monitorexit instruction can simply check if the current frame pointer matches the address of the thin lock record. If so, then it knows it's the last one out.
A key aspect is that the monitorenter/exit instructions must be properly balanced, and the JVM tries to prove this. Otherwise, a ref count would be needed to detect when the last monitorexit instruction was reached. It seems that instead, HotSpot just doesn't bother compiling the code or optimize monitor acquisition if the monitorenter/exit instructions aren't balanced.


text:
Q: PHPQuery... trying to get all links of all images from page I am trying to get all links of all images on a given page using PHPQuery. I am using the PHP support syntax of PHPQuery.
This is the code I have so far:
include('phpQuery-onefile.php');

$all = phpQuery::newDocumentFileHTML("http://www.mysite.com", $charset = 'utf-8');

// in theory this gives me all image sources
$images = $all->find('img')->attr('src');

// but if I do `echo $images;` what I get is the src to the first image

Out of curiosity I have tried
$images = $all->find('img:first')->attr('src');

and
$images = $all->find('img:last')->attr('src');

and it prints correctly the first and the last image's addresses, respectively, but how in hell can I get an array of all links?

A: Within your foreach loop, you need to wrap the $a with a pq().
For example:
$all = phpQuery::newDocumentFileHTML("http://www.mysite.com", $charset = 'utf-8');

$imgs = $all['img'];

foreach ($imgs as $img) {
    // Note: $img must be used like "pq($img)"
    echo pq($img)->attr('src');
}


text:
Q: Reverse proxy on my Linux VPS I have a Linux Server with several docker instance running. it looks like that :

*

*SSH Port: 22

*Container1 port : 4000

*Container2 ports: 5000, 5001, 50002
Currently, i'm using https://nginxproxymanager.com/, but when I bind domain.extension,it binds all the ports on my server, I want domain A to bind to Container1 only, Domain B to container 2 etc... But I dont want domain A to bind my ssh pôrt and domain B ports
What could I use ?


text:
Q: Why is my intuition about probability in this regard so flawed? Take the following example:
Take a sample from 100 people and measure their height. Assume that we know that height is approximately normally distributed, with a sample mean of 175 cm and sample standard deviation of 3.
Why is it so intuitive for me to think that the most probable distribution of height just based on this observation is a normal distribution with parameters (175,3)?
The probability of observing this sample is 0 and that is for all parameter pairs. Why do I still intuitively think that this distribution is the most probable one?


text:
Q: Remove or truncate site rss in  By default, all post's content is included into rss (content:encoded element).
I would like to convert reader to visit website.
Currently, description element is truncated, but content:encoded contains full post. Eg:
    <description><![CDATA[
Po przeszło roku inwest...

The post Robocash Recenzja (2022): 12,74% zysku appeared first on Wolny Finansowo.
]]></description>
    <content:encoded><![CDATA[<a ... {full post's content}</content:encoded>

How to trim or even remove content:encoded element?

A: You may achieve this by adding a code snippet to truncate get_the_content_feed via filter:
function truncateFeedContent( $content )
{
    $content = get_the_excerpt();

    return $content;
}
add_filter( 'the_content_feed', 'truncateFeedContent' );

By default, get_the_content_feed show all content


text:
Q: Watch NetFlix on Chromium or Firefox Since Chrome will soon no longer provide updates for 14.04 LTS and this leaves at least a one month gap until 14.04 LTS 64bit comes out I need a way to watch Netflix on either Chromium or Firefox.  I prefer Firefox.  I've tried many of the suggestions in the forums but with out luck.
I've succeeded in converting many of my family members off Windows to 14.04 LTS and I LOVE it, they LOVE it and I spend WAY less time repairing their machines now.  But no Netflix is going to be a problem.
Can someone point me to a reliable way to make this work?

A: Possibly the only use that I personally have for Chrome is to make a 'Netflix App' out of it.
google-chrome-stable --app=http://netflix.com

Running that, or editing the launcher for Chrome to run this command will open Google Chrome and launch the netflix website without any pesky window dressing like a location bar, buttons, tabs.....just Netflix.
Of course going full screen works too, if you aren't multitasking while watching a show or movie.


text:
Q: Math function to calculate a timespan for next day I am currently writing a PowerShell Script which basically reads a file where it searches for a pattern and gets time Values like: 15:22:33. The Values are stored in 2 Arrays - Out Array and In Array that both hold the same type of values.
So I am subtracting the 2 values and I am creating a timespan that for example calcs the time between this two values.

*

*11:20:33 and 2. 12:21:33 - so the timespan correctly shows me that the difference is 01:01:00 which is correct ofc.

Now my problem is that I also need to calculate the difference if the next date is tomorrow.
So take this example:

*

*12:00:00 and 2. 05:00:00 - if I use the same function I do above, so just subtract the values I get -07:00:00 but the value I need would be 17:00:00.

How would a math function look like to calculate the value for next day? I can check it with an IF Statement because if the second value is smaller that the first one its obviously the next day. But I really don't know how to calc the time correctly.
Some code:
for($i = 0; $i -lt $outVar.Length; $i++) {
    $testOut = $outVar[$i].Line.Split("(")[0]
    $testIn  = $inVar[$i].Line.Split("(")[0]

    $userOut = $outVar[$i].Line.Split('"')[2]
    $userIn = $inVar[$i].Line.Split('"')[2]

    #$testOut + $testIn
    $ConvertedStart = [datetime]::Parse($testOut)
    $ConvertedEnd = [datetime]::Parse($testIn)

    $loggedTimeTestSTART = New-TimeSpan  $ConvertedStart
    $loggedTimeTestEND = New-TimeSpan  $ConvertedEnd

    [System.Collections.ArrayList]$resultArray = @();

    if($loggedTimeTestSTART -gt $loggedTimeTestEND) {
        $loggedTimeTestFinal = $loggedTimeTestSTART.Subtract($loggedTimeTestEND)
       # $resultArray.Add($loggedTimeTestFinal)
        #$resultArray += $loggedTimeTestFinal
        $array += $loggedTimeTestFinal.ToString() + $userOut
        } else {
            $loggedTimeTestFinal = "Minus cuz next day " + $loggedTimeTestSTART.Subtract($loggedTimeTestEND)
           # $resultArray.Add($loggedTimeTestFinal);
            #$resultArray += $loggedTimeTestFinal
            $array += $loggedTimeTestFinal.ToString() + $userOut
        }

    }

as you can see in my If the else part would need to do some different calculation to get the real time difference (timespan) between two values if the second one is smaller.

A: Keep the first item ($a) as a [TimeSpan] and convert the second ($b) to [DateTime]. Than subtract the [TimeSpan] from the [DateTime] and select the TimeOfDay part to get the time difference:
$a = [TimeSpan]'11:20:33'
$b = [DateTime]'12:21:33'
($b - $a).TimeOfDay

yields:
Days              : 0
Hours             : 1
Minutes           : 1
Seconds           : 0
Milliseconds      : 0
Ticks             : 36600000000
TotalDays         : 0.0423611111111111
TotalHours        : 1.01666666666667
TotalMinutes      : 61
TotalSeconds      : 3660
TotalMilliseconds : 3660000

$a = [TimeSpan]'12:00:00'
$b = [DateTime]'05:00:00'
($b - $a).TimeOfDay

yields:
Days              : 0
Hours             : 17
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : 612000000000
TotalDays         : 0.708333333333333
TotalHours        : 17
TotalMinutes      : 1020
TotalSeconds      : 61200
TotalMilliseconds : 61200000

Alternatively, you might just add one day, if the result is less then 0:
$a = [TimeSpan]'12:00:00'
$b = [TimeSpan]'05:00:00'
$Result = $b - $a
If ($Result -lt 0) {$Result += [TimeSpan]'1:00:00:00'}


text:
Q: PyTorch adapt binary classification model to output probabilities of both classes My dataset has 14 features and a target containing {0,1}.
I have trained this binary classifier:
class SimpleBinaryClassifier(nn.Module):
    def __init__(self,input_shape):
        super().__init__()
        self.fc1 = nn.Linear(input_shape,64)
        self.fc2 = nn.Linear(64,32)
        self.dropout = nn.Dropout(p=0.1)
        self.fc3 = nn.Linear(32,1)

    def forward(self,x):
        x = torch.relu(self.fc1(x))
        x = torch.relu(self.fc2(x))
        x = self.dropout(x)
        x = self.fc3(x)
        return x

with the following criterion and training loop:
criterion   = nn.BCEWithLogitsLoss()

def binary_acc(y_pred, y_test):
    y_pred_tag = torch.round(torch.sigmoid(y_pred))
    correct_results_sum = (y_pred_tag == y_test).sum().float()
    acc = correct_results_sum/y_test.shape[0]
    acc = torch.round(acc * 100)

    return acc

model.train()
for e in range(1, EPOCHS+1):
    epoch_loss = 0
    epoch_acc = 0
    for X_batch, y_batch in train_loader:
        X_batch, y_batch = X_batch.to(device), y_batch.to(device)
        optimizer.zero_grad()

        y_pred = model(X_batch)

        loss = criterion(y_pred, y_batch.unsqueeze(1))
        acc = binary_acc(y_pred, y_batch.unsqueeze(1))

        loss.backward()
        optimizer.step()

        epoch_loss += loss.item()
        epoch_acc += acc.item()

    print(f'Epoch {e+0:03}: | Loss: {epoch_loss/len(train_loader):.5f} | Acc: {epoch_acc/len(train_loader):.3f}')

This model, when called like sigmoid(model(input_tensor)) outputs a single number in [0,1]. The pipeline I'm working with, expects a model to output probabilities [p_class1, p_class2].
How can I adapt the model and the training loop?
If I set the output of the last layer to 2, I have problems with the criterion inside the training loop.
class SimpleBinaryClassifier2(nn.Module):
    def __init__(self,input_shape):
        super().__init__()
        self.fc1 = nn.Linear(input_shape,64)
        self.fc2 = nn.Linear(64,32)
        self.dropout = nn.Dropout(p=0.1)
        self.fc3 = nn.Linear(32,2) # now it's 2

    def forward(self,x):
        x = torch.relu(self.fc1(x))
        x = torch.relu(self.fc2(x))
        x = self.dropout(x)
        x = self.fc3(x)
        return x

I use the CrossEntropy
model = SimpleBinaryClassifier2(input_shape=14)
model.to(device)
print(model)
optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)
criterion   = nn.CrossEntropyLoss()

and replace y_pred_tag = torch.round(torch.sigmoid(y_pred)) with argmax(softmax)
def binary_acc2(y_pred, y_test):
    y_pred_tag = torch.argmax(torch.softmax(y_pred), dim=1)
    correct_results_sum = (y_pred_tag == y_test).sum().float()
    acc = correct_results_sum/y_test.shape[0]
    acc = torch.round(acc * 100)
    return acc

Then the train loop rises an error:
model.train()
for e in range(1, EPOCHS+1):
    epoch_loss = 0
    epoch_acc = 0
    for X_batch, y_batch in train_loader:
        X_batch, y_batch = X_batch.to(device), y_batch.to(device)
        optimizer.zero_grad()

        y_pred = model(X_batch)

        loss = criterion(y_pred, y_batch)
        acc = binary_acc(y_pred, y_batch)

        loss.backward()
        optimizer.step()

        epoch_loss += loss.item()
        epoch_acc += acc.item()

    print(f'Epoch {e+0:03}: | Loss: {epoch_loss/len(train_loader):.5f} | Acc: {epoch_acc/len(train_loader):.3f}')

The error is the following:
RuntimeError: "nll_loss_forward_reduce_cuda_kernel_2d_index" not implemented for 'Float'

I already looked up on this other post where the cause of that error was that the element was a Float and not a tensor, but in my case the datasets are tensors:
train_dataset = GenericDataset(torch.FloatTensor(X_train), torch.FloatTensor(y_train))
test_dataset = GenericDataset(torch.FloatTensor(X_test), torch.FloatTensor(y_test))

A: According to nn.CrossEntropyLoss description it expects target as long and not float, while in your train_dataset you clearly convert it to float


text:
Q: Oracle 12c with Websphere 8.5 migration issue In My application we were using WAS 6.x and Oracle 10g, we were using EJBs as Persistence layer. In EJBs we used predefined methods to store the data in the table as shown below
UsersLocalHome usrLocalHome =  (UsersLocalHome)getEJBLocalHome(Parameters.USERS_LOCAL_JNDI_LOOKUP);
      UsersLocal    usrLocal        =  usrLocalHome.create(getKey(Constants.USERS_MODULE), userTO, request.getUserInfo());

After the up-gradation from Websphere 6.x to Websphere 8.5 and Oracle 10g to Oracle 12c, we are getting following exception in the above peace of code
EJB threw an unexpected (non-declared) exception during invocation of method "findByPrimaryKey". Exception data: java.lang.NoClassDefFoundError: oracle/xdb/XMLType
        at oracle.jdbc.driver.NamedTypeAccessor.getString(NamedTypeAccessor.java:410)
        at oracle.jdbc.driver.GeneratedStatement.getString(GeneratedStatement.java:327)
        at oracle.jdbc.driver.GeneratedScrollableResultSet.getString(GeneratedScrollableResultSet.java:973)
        at com.ibm.ws.rsadapter.cci.WSRdbResultSetImpl.getString(WSRdbResultSetImpl.java:2827)
        at com.ibm.ws.ejbpersistence.dataaccess.RawBeanData.getString(RawBeanData.java:1424)

Can some one pls help to solve the issue.

A: Check to make sure you configured your data source in WebSphere to use the Oracle11gDataStoreHelper. For more information on data source configuration, see http://www14.software.ibm.com/webapp/wsbroker/redirect?version=phil&product=was-base-dist&topic=rdat_minreqoracle.