text:
Q: Exception when parsing xml file (Invalid byte 2 of 3-byte UTF-8 sequence) I'm trying to parse an xml file from an external source which contains invalid UTF-8 bytes

Using the following java code
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setIgnoringComments(true);
factory.setNamespaceAware(false);
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
try (InputStream in = getMyInputStream()) {
    Document doc = documentBuilder.parse(new InputSource(in));
    ...
}

And I'm getting the following exception
Caused by: org.xml.sax.SAXParseException: Invalid byte 2 of 3-byte UTF-8 sequence.
    at java.xml/com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:262)
    at java.xml/com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
    ... 10 common frames omitted
Caused by: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 2 of 3-byte UTF-8 sequence.
    at java.xml/com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.invalidByte(UTF8Reader.java:702)
    at java.xml/com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.read(UTF8Reader.java:409)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(XMLEntityScanner.java:1904)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.peekChar(XMLEntityScanner.java:508)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2649)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:605)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:534)
    at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:888)
    at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:824)
    at java.xml/com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
    at java.xml/com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:246)

I realise that the XML contains an invalid UTF-8 character but I'd like the XML parser to gracefully handle this rather than throwing an exception

A: I solved this by passing a java.io.Reader to the DocumentBuilder instead of a java.io.InputStream. So now the DocumentBuilder is acting upon a stream of characters instead of a stream of bytes and does not attempt to validate the bytes and hence does not throw exceptions. The byte to character transformation is now done by the InputStreamReader
So I changed
try (InputStream in = getMyInputStream()) {
   Document doc = documentBuilder.parse(new InputSource(in));
   ...
}

To
try (Reader reader = new InputStreamReader(getMyInputStream(), StandardCharsets.UTF_8)) {
   Document doc = documentBuilder.parse(new InputSource(reader));
   ...
}


text:
Q: Python Request Post does not respond properly in a Korean Website I am trying to scrape some data from a Korean website for goods.
The website displays general data such as arrival date, department date, mother ship name of cargo ships.
Website Link
The black button on the right is the search button.
In order to obtain data from it, some radio buttons have to be set up then hit search.
So what I thought was I could do a Post request to the website so I can extract data from the response.
Unfortunately, the response was just a plain page without the Post request.
This is the Post request
POST /Berth_status_text_servlet_sw_kr HTTP/1.1
Accept: text/html, application/xhtml+xml, image/jxr, */*
Referer: http://info.bptc.co.kr:9084/content/sw/frame/berth_status_text_frame_sw_kr.jsp
Accept-Language: en-US,en;q=0.7,ko;q=0.3
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Content-Length: 40
Host: info.bptc.co.kr:9084
Pragma: no-cache
Connection: close

v_time=month&ROCD=ALL&ORDER=item2&v_gu=S

And this is what I did in Python
from bs4 import BeautifulSoup
import requests

params ={'v_time': 'month',
         'ROCD': 'ALL',
         'ORDER': 'item2',
         'v_gu': 'S'}

response = requests.post(url, data = params)

soup = BeautifulSoup(response.content,"html")

print(soup)

I did try to put encoding and other things in the headers like below
response = requests.post(url, data = params,
                         headers={'Accept': 'text/html, application/xhtml+xml, image/jxr, */*',
                             'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko',
                                  'Content-type': 'application/x-www-form-urlencoded; text/html; charset=euc-kr',
                                  'Accept-Language': 'en-US,en;q=0.7,ko;q=0.3'
                                 })

It did not work either.
The codes work fine on the other websites, so I guess it is something related to Korean characteristic.
I tried to search solutions for the issue, but I didn't have a luck.
Would you mind help me?
Thanks !

A: Your approach is correct. The response returns html and you need to parse it into a more usable format. The following code converts the table from the html response into a list if dicts:
from bs4 import BeautifulSoup
import requests

params = {"v_time": "month", "ROCD": "ALL", "ORDER": "item2", "v_gu": "S"}

response = requests.post(
    "http://info.bptc.co.kr:9084/Berth_status_text_servlet_sw_kr", data=params
)

soup = BeautifulSoup(response.content, features="html.parser")
keys = [th.get_text(strip=True) for th in soup("th")]
data = [
    {key: value.get_text(strip=True) for key, value in zip(keys, row("td"))}
    for row in soup("tr")
]
print(data)

Prints:
[
    {
        "S/H": "0",
        "모선항차": "DPYT-21",
        "반입 마감일시": "",
        "선박명": "PEGASUS YOTTA",
        "선사": "DYS",
        "선석": "2",
        "선적": "0",
        "양하": "0",
        "입항 예정일시": "2020/06/08 21:00",
        "입항일시": "",
        "전배": "",
        "접안": "P",
        "출항 예정일시": "2020/06/09 11:00",
        "출항일시": "",
        "항로": "NCK",
    }
    ...
]

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to refresh parent window by using Javascript in .cs How to refresh the parent window while closing the popup window(child window).
We are calling the java script functions in code behind to refresh the parent window by using page.ClientScript.RegisterStartupScript().But t is working fine in IE(internet explorer) but not working in Mozilla Firefox and Google Chrome.
In the Mozilla Firefox the pop up value is saving in the database but it is not updating into the parent page.If i did refresh manually the value is getting updating into the parent page. If i put debugger in RefreshPage()(javascript function) function in IE it is firing but not in Firefox.
The below code for call the javascript function in .cs class.
 page.ClientScript.RegisterStartupScript(this.GetType(), "PopupSave", "<script>javascript:alert('" + dsMessage.Tables[0].Rows[0]["ErrorMessage"].ToString() + "');window.open('','_self','');window.close();window.document.forms[0].submit();</script>");

The above code RefreshPage() is the javascript function to refresh the page
i.e.
function RefreshPage() { window.document.forms[0].submit(); }

Please help me i tried with different scenarios but no output.
instead of RefreshPage() i used different functions
like reload(),
window.opener.forms[0].submit(),
likewise but still no output anyone knows please help me.

A: Try this function
on submit button click run this script
<script language='javascript'> window.opener.frames.location='somepage.aspx';window.close();</script>

this will help you !!!

A: Before trying to make js calls between windows.
Set 'document.domain' to the same value on both pages.

A: protected void ButtonClick(object sender, EventArgs e)
{
    string closeAndRefreshScript = @"<script type='text/javascript'>
    window.opener.location.reload();
    window.close();
    </script>";
    base.Response.Write(closeAndRefreshScript);
}


text:
Q: How to join four tables in sql I have four tables in SSMS, I'm trying to write a script for a table variable that will hold the results of all four, basically, it will be like my table tshow which is in the picture.
This is what I have so far for the Table Variable so far:

DECLARE @mShowsTable Table(
MaskedSinger NCHAR(50) NOT NULL,
Costumes NCHAR(50) NOT NULL,
Song NCHAR(50) NOT NULL,
DateSung DATE NOT NULL
);

INSERT INTO @mShowsTable

A: I suppose you have been required to use the Table Variable, so the solution as shown below. Otherwise, I agree with the comment saying Temp Table is better in terms of performance.
Note: You need to replace the data types with what matches your requirements.
DECLARE @mShowsTable TABLE (
    MaskedSinger VARCHAR(200)
    ,Costumes VARCHAR(200)
    ,Song VARCHAR(200)
    ,DateSung DATETIME
    );

INSERT INTO @mShowsTable
SELECT M.MaskedSinger
    ,C.Customes
    ,SO.Song
    ,D.DateSung
FROM tShow S
INNER JOIN tCustomes C ON S.CustomesID = C.CustomesID
INNER JOIN tMaskedSingers M ON S.MaskedSingerID = M.MaskedSingerID
INNER JOIN tSong SO ON S.SongID = SO.SongID
INNER JOIN tDateSung D ON S.DateSungID = D.DateSungID

SELECT *
FROM @mShowsTable

The full script I used is as below.
CREATE TABLE tCustomes (CustomesID INT, Customes varchar(200))
CREATE TABLE tMaskedSingers (MaskedSingerID INT, MaskedSinger varchar(200))
CREATE TABLE tSong (SongID INT, Song varchar(200))
CREATE TABLE tDateSung (DateSungID INT, DateSung DateTime)
CREATE TABLE tShow (MaskedSingerID INT, CustomesID INT, SongID INT, DateSungID INT, ShowID INT)

INSERT INTO tCustomes  VALUES (1, 'ABCD'), (2, 'XYZ')
INSERT INTO tMaskedSingers  VALUES (1, 'SINGER 1'), (2, 'SINGER 2'), (3, 'SINGER 3')
INSERT INTO tSong  VALUES (1, 'SONG 1'), (2, 'SONG 2'), (3, 'SONG 3')
INSERT INTO tDateSung  VALUES (1, '2020-10-28'), (2, '2020-10-29'), (3, '2020-10-29'), (4, '2020-10-30')
INSERT INTO tShow  VALUES (1, 1,1,1,1), (2, 1,2,2,2), (2, 2,2,2,3)

DECLARE @mShowsTable TABLE (
    MaskedSinger VARCHAR(200)
    ,Costumes VARCHAR(200)
    ,Song VARCHAR(200)
    ,DateSung DATETIME
    );

INSERT INTO @mShowsTable
SELECT M.MaskedSinger
    ,C.Customes
    ,SO.Song
    ,D.DateSung
FROM tShow S
INNER JOIN tCustomes C ON S.CustomesID = C.CustomesID
INNER JOIN tMaskedSingers M ON S.MaskedSingerID = M.MaskedSingerID
INNER JOIN tSong SO ON S.SongID = SO.SongID
INNER JOIN tDateSung D ON S.DateSungID = D.DateSungID

SELECT *
FROM @mShowsTable

DROP TABLE tCustomes
DROP TABLE tMaskedSingers
DROP TABLE tSong
DROP TABLE tDateSung
DROP TABLE tShow

Giving the results


text:
Q: Unable to set width inside ASP repeater I am having below repeater with table tr and td I have assigned width to these but that doesn't work. I have tried with px and % both doesn't work in my case.

                    <asp:Repeater ID="rptIncrementalInt" runat="server" Visible="true" OnItemDataBound="rptIncrementalInt_ItemDataBound">
                        <HeaderTemplate>

                                        Company Group
                                        Entity
                                        Category
                                        Legislation
                                        Nature of Proceeding
                                        Interest Type
                                        Section
                                        Rate (%)
                                        Mode of interest computation
                                        Start Date Type
                                        Start Date dd-mmm-yy
                                        End Date dd-mmm-yy
                                        Adjustment for part of the month

                                        No. of days in a month
                                        No. of days in a year
                                        Amount on which Int to be computed
                                        Net Amount
                                        Break-up, if available
                                        Interest compounded on
                                        Period
                                        Interest
                                        Existing Open Issues
                                        Risk Apportionment

                                        Base Exposure
                                        Interest
                                        Penalty
                                        Month
                                        Days
                                        Probable
                                        Possible
                                        Remote
                                        Probable
                                        Possible
                                        Remote

                        </HeaderTemplate>
                        <ItemTemplate>

                                <%# DataBinder.Eval(Container.DataItem, "CGroupName") %>
                                    <asp:HiddenField ID="hiddMainProceedingId" runat="server" Value='<%#DataBinder.Eval(Container.DataItem,"MainProceedingId") %>' />
                                    <asp:HiddenField ID="hiddRowIndex" runat="server" Value='<%#DataBinder.Eval(Container.DataItem,"RoWID") %>' />
                                    <asp:HiddenField ID="hiddInterestCalcId" runat="server" Value='<%#DataBinder.Eval(Container.DataItem,"InterestCalcId") %>' />

                                <%# DataBinder.Eval(Container.DataItem, "EntityName") %>
                                <%# DataBinder.Eval(Container.DataItem, "Category") %>
                                <%# DataBinder.Eval(Container.DataItem, "Legislation") %>
                                <%# DataBinder.Eval(Container.DataItem, "NOP") %>

                                    <%# DataBinder.Eval(Container.DataItem, "InterestType") %>
                                    <asp:HiddenField ID="hiddInterestTypeID" runat="server" Value='<%#DataBinder.Eval(Container.DataItem,"InterestTypeID") %>' />

                                    <%# DataBinder.Eval(Container.DataItem, "SectionRef") %>
                                    <asp:HiddenField ID="hiddSecRefID" runat="server" Value='<%#DataBinder.Eval(Container.DataItem,"SectionRefID") %>' />

                                <%# DataBinder.Eval(Container.DataItem, "IntRate") %>
                                <%# DataBinder.Eval(Container.DataItem, "IntModeComputation") %>
                                <%# DataBinder.Eval(Container.DataItem, "StartDateType") %>
                                <%# DataBinder.Eval(Container.DataItem, "StartDate") %>
                                <%# DataBinder.Eval(Container.DataItem, "EndDate") %>
                                <%# DataBinder.Eval(Container.DataItem, "AdjPartOfMonth") %>

                                <%# DataBinder.Eval(Container.DataItem, "NoOfDaysMonths") %>
                                <%# DataBinder.Eval(Container.DataItem, "NoOfDaysYr") %>
                                <%# DataBinder.Eval(Container.DataItem, "AmtIntComputatedOn") %>
                                <%# DataBinder.Eval(Container.DataItem, "NetAmt") %>
                                <%# DataBinder.Eval(Container.DataItem, "DutyAmt") %>
                                <%# DataBinder.Eval(Container.DataItem, "InterestAmt") %>
                                <%# DataBinder.Eval(Container.DataItem, "PenaltyAmt") %>

                                    <asp:TextBox ID="txtInterestComputedOn" Width="90px" CssClass="Amount" OnKeyUp="javascript:NumberWithCommas(this, this.value);"
                                        runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "IntComputatedOn") %>'></asp:TextBox>
                                    <asp:RegularExpressionValidator ID="reAmount" runat="server" ControlToValidate="txtInterestComputedOn"
                                        ErrorMessage='<%# String.Format("Please Enter Only Numbers in Interest Computed On in Row No {0}", Container.ItemIndex + 1) %>' CssClass="errors"
                                        ValidationExpression1="^\d+(\.\d{1,2})?$"
                                        ValidationExpression="^(?:\d|[,])+$" ValidationGroup="Main">*</asp:RegularExpressionValidator>

                                <%# DataBinder.Eval(Container.DataItem, "PeriodMonth") %>
                                <%# DataBinder.Eval(Container.DataItem, "PeriodDays") %>

                                    <asp:TextBox ID="txtInterest" runat="server" Width="90px" CssClass="Amount" OnKeyUp="javascript:NumberWithCommas(this, this.value);"
                                        Text='<%# DataBinder.Eval(Container.DataItem, "Interest") %>'></asp:TextBox>
                                    <asp:RegularExpressionValidator ID="reInterest" runat="server" ControlToValidate="txtInterest"
                                        ErrorMessage='<%# String.Format("Please Enter Only Numbers in Interest in Row No {0}", Container.ItemIndex + 1) %>' CssClass="errors"
                                        ValidationExpression="^(?:\d|[,])+$" ValidationGroup="Main">*</asp:RegularExpressionValidator>

                                <%# DataBinder.Eval(Container.DataItem, "Probable") %>
                                <%# DataBinder.Eval(Container.DataItem, "Possible") %>
                                <%# DataBinder.Eval(Container.DataItem, "Remote") %>

                                    <asp:TextBox ID="txtRiskProbable" runat="server" Width="90px" CssClass="Amount" OnKeyUp="javascript:NumberWithCommas(this, this.value);"
                                        Text='<%# DataBinder.Eval(Container.DataItem, "ProbableApp") %>'></asp:TextBox>
                                    <asp:RegularExpressionValidator ID="reRiskProbable" runat="server" ControlToValidate="txtRiskProbable"
                                        ErrorMessage='<%# String.Format("Please Enter Only Numbers in Risk Probable in Row No {0}", Container.ItemIndex + 1) %>' CssClass="errors"
                                        ValidationExpression="^(?:\d|[,])+$" ValidationGroup="Main">*</asp:RegularExpressionValidator>

                                    <asp:TextBox ID="txtRiskPossible" runat="server" Width="90px" CssClass="Amount" OnKeyUp="javascript:NumberWithCommas(this, this.value);"
                                        Text='<%# DataBinder.Eval(Container.DataItem, "PossibleApp") %>'></asp:TextBox>
                                    <asp:RegularExpressionValidator ID="reRiskPossible" runat="server" ControlToValidate="txtRiskPossible"
                                        ErrorMessage='<%# String.Format("Please Enter Only Numbers in Risk Possible in Row No {0}", Container.ItemIndex + 1) %>' CssClass="errors"
                                        ValidationExpression="^(?:\d|[,])+$" ValidationGroup="Main">*</asp:RegularExpressionValidator>

                                    <asp:TextBox ID="txtRiskRemote" runat="server" Width="90px" CssClass="Amount" OnKeyUp="javascript:NumberWithCommas(this, this.value);"
                                        Text='<%# DataBinder.Eval(Container.DataItem, "RemoteApp") %>'></asp:TextBox>
                                    <asp:RegularExpressionValidator ID="reRiskRemote" runat="server" ControlToValidate="txtRiskRemote"
                                        ErrorMessage='<%# String.Format("Please Enter Only Numbers in Risk Remote in Row No {0}", Container.ItemIndex + 1) %>' CssClass="errors"
                                        ValidationExpression="^(?:\d|[,])+$" ValidationGroup="Main">*</asp:RegularExpressionValidator>

                        </ItemTemplate>
                        <FooterTemplate>

                                Total

                                    <asp:Label ID="lblTotal" runat="server"></asp:Label>

                                    <asp:Label ID="lblRiskProbableTotal" runat="server"></asp:Label>

                                    <asp:Label ID="lblRiskPossibleTotal" runat="server"></asp:Label>

                                    <asp:Label ID="lblRiskRemoteTotal" runat="server"></asp:Label>

                        </FooterTemplate>
                    </asp:Repeater>

                                    test by Nadeem

                                    test by Nadeem

                                    Pending

                                    Item
                                    Item1
                                    Item2
                                    Item3

                        No Record(s) found...

                                    <asp:LinkButton ID="lbFirst" Text="| < First" runat="server"
                                        OnClick="lbFirst_Click"></asp:LinkButton>

                                    <asp:LinkButton ID="lbPrevious" runat="server"
                                        OnClick="lbPrevious_Click" Text="| << Previous"></asp:LinkButton>

                                    <asp:LinkButton ID="lbNext" runat="server"
                                        OnClick="lbNext_Click" Text="| Next >> |"></asp:LinkButton>

                                    <asp:LinkButton ID="lbLast" runat="server"
                                        OnClick="lbLast_Click" Text="Last > |"></asp:LinkButton>

                                    <asp:Label ID="lblpage" runat="server" Text=""></asp:Label>

                        <asp:Repeater ID="rptPaging" runat="server" OnItemCommand="rptPaging_ItemCommand">
                            <ItemTemplate>
                                <asp:LinkButton ID="btnPage"
                                    Style="padding: 8px; margin: 2px; background: gray; border: solid 1px #666; font: 8pt tahoma;"
                                    CommandName="Page" OnClientClick="ShowProgress();" CommandArgument="<%# Container.DataItem %>"
                                    runat="server" ForeColor="White" Font-Bold="True"><%# Container.DataItem %>
                                </asp:LinkButton>
                            </ItemTemplate>
                        </asp:Repeater>

My css classes are like below:
    .ey-dataTable
{
    background-color: rgb(219,221,221);
    width: 99.5%;
    margin-top: 5px;
    margin-bottom: 2px;
}
.ey-formlabel1
{
    font-family: Arial;
    font-size: 12px;
    text-align: left;
    padding-top: 3px;
    padding-bottom: 3px;
    padding-left: 1px;
    padding-right: 6px;
    vertical-align: top;
}
.AlignedRow
        {
            vertical-align: top;
            text-align: center;
        }

A: I can't say exactly what is wrong, but I can give you a few pointers:
First problem is with the header. You have a row span. But the rows you are spanning together have different width. You can't be sure how the browsers will react to that.
Second. It is best to not mix %  and px. The results will vary depending on screen width.
A tip: only set widths on your very first row. That is enough and makes your live alot easier for finding out where it goes wrong. You don't need the width definition on each row. 1 row will do just fine.
I hope this will nod you in the right direction


text:
Q: Is there a way to safely redeclare a symbol? I often find myself experimenting in the REPL and I will say something like:
subset Bar of Int where * %% 57;
Then I play around with checks on the Bar-ness for things for a bit.
Everything is happy, until I realize that I want to change the definition of Bar.
If I just redefine Bar, I get a Redeclaration of symbol exception.
I tried using MONKEY-TYPING and augment like this:
use MONKEY-TYPING;
augment subset Bar of Int where * %% 37;

But that netted me the same error.
Why do I want this?  So I can iterate on my subset (or class, or other symbol) definitions, while reusing the tests I've already typed that are in my history.

A: The REPL has its shortcomings.  It is an elaborate construction of EVAL statements that try to work together.  Sometimes that doesn't work out.
I guess the best we could do, is to introduce a REPL command that would make it forget everything it has done before.  Patches welcome! :-)

A: I think the REPL does part of its magic by EVAL-ing each new input in a new nested lexical scope. So, if you declare things with my then you can shadow them with declarations entered later:
my subset Bar of Int where * %% 57;
sub take-Bar(Bar $n) { say "$n is Bar" }
take-Bar 57;

my subset Bar of Int where * %% 42;
sub take-Bar(Bar $n) { say "$n is Bar" }
take-Bar 42;

If you omit my, then for subset and class declarations, our will be used, and since our is actually my + adding the symbol to the enclosing package...; turns out if you delete the symbol from the package, you can then shadow it again later:
subset Bar of Int where * %% 57;
GLOBAL::<Bar>:delete;
subset Bar of Int where * %% 42;
42 ~~ Bar;

NOTE: These results are just from my experiments in the REPL. I'm not sure if there are other unknown side effects.


text:
Q: Make div display on top of everything I'm using a countdowntimer on my website for shipping.
This my code I added in my header.tpl : http://jsfiddle.net/ALrnK/3/

           Leveransinformation

           ContentContentContentContentContentContentContentContent

           ContentContentContentContentContentContentContentContentContent

           ContentContentContentContentContentContentContentContentContentContentContent

I'f you take look att (link was removed due to canceled project) and hover the countdowntimer it extends the header.
I would like the information to show there but on top of everything else. So its displays over the menu and the imageslider.
I tried to use z-index but it does not matter how I do. Is there anything else I should use instead?

A: Without seeing the actual styles, here's one possibility - Make sure the element that you are changing the z-index of is either position: relative;, absolute, or fixed.


text:
Q: How do I connect the virtual ground as shown below This is a circuit for EEG. How do I make the connections labelled as Virtual Ground? Also, how do I connect the 1M trim pot in the top right?

A: That is really a horrible schematic. They should at least have used a different ground symbol for the virtual ground. It's actually a completely different net from ground. And it looks like they used a resistor symbol for the rheostat-connected trimpot.
Such a schematic will have no (useful) connectivity information and using it for board layout will be a bad idea.
So, connect all the virtual ground 'ground' modes together, and the other 'microcontroller ground' nodes together. If you are pouring a ground plane it should be virtual ground in the analog section and microcontroller ground in the digital section. Adding bypass capacitors, though typically a good idea, will probably cause problems with op-amp oscillation in this particular 'design'.
The pot can only adjust the output voltage lower than 2.5V, down to the saturation of the op-amp. Since the 3140 output will swing from a couple hundred mV up to Vcc - 2V or so, it is asymmetrical too.
They show the wiper on the trimpot connected to +5 through a 1M resistor, and one of the ends of the element goes to R5/C2/R2 etc. Either end will work, it will just reverse the effect of pot rotation. Tie the otherwise unused end of the element to the wiper, not as shown, for a bit better design.

A: Okay, I got a clear idea of how this works after some research. Here's help for those who need it in the future.
The Opamp in the bottom half of the image actually produces a voltage of 2.5V when connected with an Arduino.(5v) The output of the second Op-Amp, therefore, is the Virtual ground. All connections labelled as virtual ground must be connected to the pin 6 of this Op-Amp


text: Q: Inject multiple mock contexts in Jest Hello I was wondering is there a way to inject two mockContexts like in the solution here https://stackoverflow.com/a/55013256/8197395 but with two. Thanks I tried to add two with different names via useContext but unless it is called mockContext Jest doesn't recognise it.


text:
Q: AR sceneform activity crashes I am having an issue with AR using sceneform 1.5. The activity containing the AR sometimes crashes (white screen) and goes back to the activity that started it. Sometimes, I'm able to display the 3D model however when I move the camera, the activity crashes. I already tried to debug but the logs are being cleared and also no crashes registered on the play console. This issue is intermittent and I mostly encounter it in our Samsung A7,S9 and Huawei P20 test devices. I haven't encountered the issue on Note 9 and S21. What are the possible cause of the crash?

A: You are using a very old version of Sceneform. I would suggest to update to the latest community maintained version of Sceneform

*

*Sceneform update and alternatives


text:
Q: Summarizing across multiple search strings in R using grepl and dplyr I have a rather unorganized dataframe which has varying names for the same categories in one column. I want to summarize across those messy names using dplyr.
Here's a simplified dataset, of tree species and their traits:
df <- data.frame(species = c('sp1', 'sp1', 'sp1', 'sp2', 'sp2'), tr = c('leaf nitrogen per mass', 'wood den', 'nitrogen (per mass)', 'leaf carbon per area', 'wood dens'), val = sample(1:10, 5), stringsAsFactors=F)

So each species has a number of trait values of different categories in this dataset.
You can get summary statistics per species using dplyr and the code below.
library(dplyr)
by_sp<- df %>%
group_by(species, tr)

by_sp %>% summarize(avg = mean(val))

You can see that it treats the same traits as separate, since they don't match completely. I want to summarize across these using fuzzy matching for many different traits, but don't know how to implement this across many traits at the same time. So far I have tried using grepl to create a vector of 'required' strings to filter by. Ex.
lmass <- 'nitrogen|mass'
by_sp %>% filter(grepl(lmass, tr, ignore.case=T)) %>% summarize(ave = mean(val))

But this is using 'or', whereas I want 'and'- requiring both strings, so that the final dataframe is a single average across all rows containing both nitrogen and mass (in column tr).
Additionally I have many of these trait strings, and I want a dataframe at the end with averages for each of these traits per species. So far I have tried combining the different search strings, but this doesn't work.
wood <- 'wood den' #this could have other keywords required for this trait
alltr <- c(lmass, wood)
leaf_tr %>% filter(grepl(alltr, tr, ignore.case=T)) %>% summarize(ave = mean(val)) #gives an error, only takes first element in alltr

Any help would be much appreciated!

A: Here is a data.table solution.  I know you're asking for dplyr, but unfortunately some of the issues I ran into exceeded my dplyr skills (e.g. create multiple columns with mutate):
# setup regular expressions, etc.

library(data.table); library(reshape2)
traits <- c(nm="nitrogen.*mass", wd="wood den", ca="carbon.*area")
trait.nm <- names(traits)
DT <- data.table(df)  # make data table

DT[,  # Add a column for each trait, indicating whether row matches the trait
  c(trait.nm):=
    data.frame(sapply(trait.nm, function(x) grepl(traits[x], tr)))
]
melt(DT, id.vars=names(df))[           # transform to long format
  value == TRUE,                       # filter for trait-val combinations that match
  sum(val), by=.(species, variable)    # group by standardized trait
]

This produces:
   species variable V1
1:     sp1       nm 13
2:     sp1       wd  3
3:     sp2       wd  1
4:     sp2       ca  2

Note I added the "Carbon Area" category.  In order to solve your "OR" problem with nitrogen mass, I just changed the regular expression to "nitrogen.*mass".
One big caveat with this is you need to make sure that each trait can only match one regular expression, otherwise you will end up with the trait counted multiple times in different trait categories.


text:
Q: How to convert iqueryable to string in linq? i have the following code snippet.
in which i just want to return PartyName as a string.
but i get the error:"Cannot implicity convert type 'System.Linq.Iqueryable to string"
if i want to return only string then what to do?
please help me.
return objDatabase.FAPARs
                   .Where(f => (f.PARTY_CODE == "P003"))
                   .Select(f => f.PARTY_NAME);

A: An IQueryable<string> represents a query which could return any number of strings. You want one string - so you need to decide what to do in various situations:

*

*What do you want to happen if the query has no results?

*What do you want to happen if the query has one result? (I assume this is simple :)

*What do you want to happen if the query has more than one result?

The set of methods which allow you to determine all of this are:

*

*Single - fail if there isn't exactly one result

*SingleOrDefault - fail if there's more than one result, return null if there are no results

*First - fail if there are no results, return the first of many

*FirstOrDefault - return null if there are no results, or the first of many

*Last - fail if there are no results, return the last of many

*LastOrDefault - return null if there are no results, or the last of many

In each case, "fail" means "throw an exception". (IIRC it's always InvalidOperationException, at least in LINQ to Objects, but I could be wrong.)
So if you're querying by an ID which must exist (i.e. it's a bug if it doesn't) then Single is probably appropriate. If you're querying by an ID which may not exist, then use SingleOrDefault and check whether the return value is null. If you're not querying by an ID, you probably want to use FirstOrDefault or just iterate over the results.
(Note that the default value being null is due to this being a query returning strings, and string being a reference type. In general it's the default value of the element type - so if you had an IQueryable<int>, the default returned would be 0.)

A: Try
return objDatabase.FAPARs .Where(f => (f.PARTY_CODE == "P003")) .Select(f => f.PARTY_NAME).SingleOrDefault();

A: return objDatabase.FAPARs.FirstOrDefault(f => f.PARTY_CODE.Equals("P003")).PARTY_NAME

A: Try this:
return objDatabase.FAPARs.Where(f => (f.PARTY_CODE == "P003")).Single(f => f.PARTY_NAME);

A:  return objDatabase.FAPARs.OfType<FAPAR>()
                .Where(f => (f.PARTY_CODE == PartyCode && f.COMP_NO == ComCode))
                .Select(f => f.PARTY_NAME).SingleOrDefault();


text:
Q: Upside down text for report? For specific reasons, I need to be able to display some values on the bottom half of my report upside down(inverted). The intention of this report is to be printed and folded down the middle, so I would like for it to adhere to this specific format. I can't find anything that does this easily. Some ideas that I have considered but don't know how to implement:
'importing' an upside-down font and setting the control's font to that font?
somehow inverting the entire control 180 degrees
Does anyone have any experience accomplishing this?
Edit: installing an upside down font and setting the control source's font property to that font was the solution that I implemented. For some upside down fonts, it may be necessary to call str_reverse on the text, as the upside down font may reverse the order  Problem is-- This would only work on the computer with the font installed, right?

A: I think your options are:

*

*Lebans: http://www.lebans.com/

*Word mail merge

*An upside down font

*An image.

Access has a Vertical property, but that is only for 90°.


text:
Q: exporting multicolumn listbox to specific range background info: I have a userform, which contain a 2-column listbox and a command button
I want to export all items in listbox (from both column) into a sheet through the button. I am thinking of using loop to get all of the information from the listbox, but somehow it is not working. When run, it gives me only the first row from the listbox, but not the other rows.
Private Sub CommandButton1_Click()

Dim i, t As Double
Dim inputrow As Long
Dim sh As Worksheet
Dim lastrow As Long

Set sh = Sheets("sheet1")

lastrow = sh.Range("A" & Application.Rows.Count).End(xlUp).Row + 1

i = ListBox2.ListCount

For inputrow = lastrow To lastrow + i

    For t = 0 To i

        sh.Range("A" & inputrow).Value = ListBox2.List(t, 0)
        sh.Range("B" & inputrow).Value = ListBox2.List(t, 1)

    Exit For

    Next t

Exit For

Next inputrow

end sub

A: Try following sub.
Private Sub CommandButton1_Click()
Dim lRow As Long, i As Long
Dim sh As Worksheet
Dim Rng As Range

Set sh = Sheets("Sheet1")
lRow = sh.Cells(sh.Rows.Count, "A").End(xlUp).Row

    Set Rng = Range("A" & lRow)
    For i = 0 To Me.ListBox1.ListCount - 1
        Rng.Offset(i + 1, 0) = Me.ListBox1.List(i, 0)
        'sh.Range("A" & lRow + i + 1) = Me.ListBox1.List(i, 0)

        Rng.Offset(i + 1, 1) = Me.ListBox1.List(i, 1)
        'sh.Range("B" & lRow + i + 1) = Me.ListBox1.List(i, 0)
    Next i

Set Rng = Nothing
Set sh = Nothing
End Sub


text:
Q: Is it possible to use the Firebase Storage Emulator from Cypress within a GitLab pipeline? I am trying to test a Vue3 application using Cypress within a GitLab pipeline. I am using the Storage emulator.
The code to store the file looks like the following:
import { getStorage, uploadBytes, ref as StorageRef, listAll } from '@firebase/storage';

function storeFile() {
    const storage = getStorage();
    const storageRef = StorageRef(storage, "tests/some-child40"));
    const blob = new Blob(['foo'], {
        type: "text/plain",
    });

    uploadBytes(storageRef, blob).then((snapshot) => {
        console.log("Uploaded a blob or file!");
    }).catch((error) => {
        console.error("Upload failed", error);
    });
}

On my local machine, that works well.
However, within GitLab I get the following error message:

The file is not being stored. What is does the error code 501 mean?
I have inspected firestore-debug.log but it does not provide more information.
I have properly setup the storage emulator using connectStorageEmulator(storage, 'localhost', 9199);


text:
Q: setState inside useEffect doesnt update UI i am trying to fetch multiple endpoints in UseEffect and depending on it's result show data on the UI (avatar, username, etc.)
Problem is, that the data received in the fetch() calls inside useEffect do in fact return the correct data but when trying to access it in the UI-Code, it will not show up.
As you can see in my code, I have the isLoading state, but I feel like the then operation doesnt really wait until the response is there.. The loading screen will be shown for 0.5 sec but when the normal screen pops up, username, avatar, etc. are empty.
So how can I make the UI wait until useEffect has completely loaded the data and then display it?
UserProfile.tsx
  React.useEffect(() => {
    AsyncStorage.getItem(LOGGED_IN_USER).then((userSteamID) =>
      fetch(USER_PROFILE + userSteamID)
        .then((response) => response.json())
        .then((json) => json.steamId)
        .then((steamId) => {
          fetch(USER_INVENTORY + steamId)
            .then((response) => response.json())
            .then((json) => {
              console.log(json);
              setProfileInfo(json);
              setSteamID(json.steamId);
              setInventoryValue(json.value);
            })
            .catch((err) => alert(err))
            .finally(() => setLoading(false));
        })
    );
  }, []);

trying to use it afterwards:

  if (loading) {
    return (
      <View
        style={{
          height: "100%",
          justifyContent: "center",
          backgroundColor: Colors.dark.background,
        }}
      >
        <ActivityIndicator
          size="large"
          style={{ backgroundColor: Colors.dark.background }}
        />
        <Text
          style={{
            color: Colors.dark.text,
            marginTop: 10,
            alignSelf: "center",
          }}
        >
          retrieving userdata...
        </Text>
      </View>
    );
  } else {
    return (
      <Text>{inventoryValue}</Text> // avatar, etc. wont work as well
)

I Navigate from a LoginScreen.tsx to it like so:
  onPress={async () => {
          let result = await startAuth();
          if (result.type == "success") {
            setLoggedInUser(result.steamID);
            console.log("ID: " + result.steamID);
            navigation.navigate("UserProfile");
          }

A: Create promise chain
React.useEffect(() => {
  AsyncStorage.getItem(LOGGED_IN_USER).then((userSteamID) =>
    fetch(USER_PROFILE + userSteamID)
      .then((response) => response.json())
      .then((json) => json.steamId)
      .then((steamId) => fetch(USER_INVENTORY + steamId))
      .then((response) => response.json())
      .then((json) => {
        setProfileInfo(json);

        // This can be avoided, already available in profileInfo
        setSteamID(json.steamId);
        setInventoryValue(json.value);
      })
      .catch((err) => alert(err))
      .finally(() => setLoading(false))
  );
}, []);

With async/await
React.useEffect(() => {
  const init = async () => {
    try {
      const userSteamID = await AsyncStorage.getItem(LOGGED_IN_USER);
      const { steamId } = await fetch(USER_PROFILE + userSteamID).then((r) =>
        r.json()
      );
      const json = await fetch(USER_INVENTORY + steamId).then((r) => r.json());
      setProfileInfo(json);

      // This can be avoided, already available in profileInfo
      setSteamID(json.steamId);
      setInventoryValue(json.value);
    } catch (error) {
      alert(error);
    } finally {
      setLoading(false);
    }
  };
  init();
}, []);


text:
Q: file input to blob using canvas unable to insert blob to indexedDB please assint in inserting blob from file to indexedDB :)
CODE
    <html>
      <head>
        <title>file to BLOB</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      </head>
    <body>
      <div id="test">
        <input id="File" type="file" accept="image/*" capture="user">
      </div>
    </body>
    </html>
<script src="js/idbConn.js"></script>

Javascript
<script>
    $(document).ready(function(){
      $("#File").change(function(){
      const File = this.files[0];
      const cvs = document.createElement("canvas");
      const optBlob = cvs.toBlob(function(cvsBlob){
        let fileURL = URL.createObjectURL(File);
        let imgFile = new Image();
        let imgFile.src = fileURL;
        imgFile.onload = function(){
          cvs.width = imgFile.naturalWidth;
          cvs.height = imgFile.naturalHeight;
          let ctx = cvs.getContext("2d").drawImage(imgFile,0,0);
          URL.revokeObjectURL(fileURL);
        }
      },File.type,0.3);
      const data = new Object();
      data.blob = optBlob;
      let trx = db.transaction(["imgBlobs"],"readwrite").objectStore("imgBlobs").put(data,"test.jpeg");
      });
    });
</script>

trying to directly insert file into indexedDB but blob is as undefined

if kept cvsBlob in data.blob blank image is storing in indexedDB

A: There are a few problems.

*

*HTMLCanvasElement.toBlob does not return anything. You get the blob in the callback function.

*JavaScript is blocking, queued tasks (like the toBlob callback) events (like onload) will not run until the current execution has returned. This means that the line
const data = new Object(); is run before the toBlob callback has been called.

*You are calling toBlob before you have created, loaded and drawn the image to the canvas.

*let imgFile.src = fileURL; This line will throw a syntax error??

Fix

*

*First load the image.

*On image load create the canvas and draw the image on it.

*Revoke the image url.

*Convert the canvas to a blob.

*In the toBlob callback add the blob to the DB.

Example
Call the function with the file you get from the file input. Eg  $("#File").change(function() { saveImageToDB(this.files[0]) });
function saveImageToDB(file) {
    const fileURL = URL.createObjectURL(file);
    const img = new Image();
    img.src = fileURL;
    img.addEventListener("load", () => {
        URL.revokeObjectURL(fileURL);
        const cvs = document.createElement("canvas");
        cvs.width = img.naturalWidth;
        cvs.height = img.naturalHeight;
        cvs.getContext("2d").drawImage(img, 0, 0);
        cvs.toBlob(blob => {
            // Code to add blob to database. Put your db code in here
            db.transaction(["img"], "write").objectStore("imgs").put({blob}, file.name);
        }, File.type, 0.3);
    }, {once: true});
}


text:
Q: copy large 'ref byte' chunks to file i'm struggling in my head for what's the best way of copying large data that comes from DLL as ref byte to a file.
since it's a video stream (or hundreds) then i don't feel so comfortable using Marhal.Copy/ WriteByte in a loop, and etc.. but something more direct.
i'm pretty stucked with that ref byte and unfortunately don't really have so much to do about it.
anyways, i was thinking about P/Invoke WriteFile but it gets IntPtr where the closest i could get from ref byte is of course byte* (using fixed).
now, i'm going to have few hundreds of this kind of stream, and each one can get to ~2Mbps.
so at the bottom line - i'm searching for an efficient way of copying ref byte chunks to a file (with a given array size of course).

A: well in case someone would be interested, and thanks to Mr. Smith, i first changed the given DllImport from ref byte declarations to IntPtr.
then i imported WriteFile:
[DllImport("kernel32.dll")]
    private static extern bool WriteFile(IntPtr hFile, IntPtr lpBuffer, int NumberOfBytesToWrite, out int lpNumberOfBytesWritten, IntPtr lpOverlapped);

and used it as follows:
//somewhere in class:
tmpFileStream = new FileStream("tmp.bin", FileMode.Create, FileAccess.Write);

public void AddBuffer(IntPtr buffer, int size)
{
    int written;
    WriteFile(tmpFileStream.SafeFileHandle.DangerousGetHandle(), buffer, size, out written, IntPtr.Zero);
}


text:
Q: How to get pin intents from smart card or token? Does anyone know how to get the number of PIN attempts a smartcard or token. NET or C / C + +?

A: The only standardized way (ISO 7816-4) is, to send a VERIFY command. If the card responds 63Cx, then x is the number of retries. If it doesn't, a proprietary command may exist to find out. But there is no generic command and there is no other way than to look into the manual of the smartcard or token.


text:
Q: Postgis ST_Distance query returning inaccurate results I am using the following query to retrieve records from a postgresql DB
@services = Service.select("*, ST_Distance(services.lon_lat, ST_GeomFromText('POINT (lat lon)', 4326)) as st_distance").order("st_distance").limit(10)

services.lon_lat is a geography type.
After implementing a "get directions" aspect to my app I have noticed a inaccuracy in the distances returned from the above query and the directions in google maps.
It's important to note I did expect a slight discrepancy taking into account the roads to the destination may not be a straight line but it seems the inaccuracy is the other way, for example the 1st returned item in this query says its 216km away where google maps says 181km, the 10th says 247km compared to google maps 203km...the further the distance the larger the inaccuracy...the 46th item returned if I choose to return that many says 424km compared to 298km.

A: Unfortunately I have egg on my face with this one...although this was my first thought I ruled it out like an idiot due to passing in my parameters backwards...Thanks everybody
https://stackoverflow.com/questions/29669045/postgis-st-distance-query-returning-inaccurate-results


text:
Q: Is H a normal subgroup in G?
Let $G = S_5$ and let $H = \langle(1, 2, 3, 4, 5)\rangle$. Is $H$ a normal subgroup of $G$ ?

Having some trouble figuring out this problem, it would be great if someone can help to find it!

A: Consider $(12)(12345)(12)=(13452)\not\in\langle (12345)\rangle =\{e,(12345),(13524),(14253),(15432)\}$.

A: Chris Custer provides an answer by using definition but I hope the following is useful to you for finding normal subgroups in $S_n$

Hint:  A subgroup $H$ of $G$ is normal $\iff$ $H$ is the union of conjugacy classes
$$\&$$ Remember that, elements of $S_n$ are conjugate $\iff$ they have the same cycle type


text:
Q: Where does the member variable inside a class allocated? I have a class
class Sample
{
   string strName;
};

If i create an object for the Sample using Sample *obj = new Sample() where does the string strName created? is it in stack or in heap?

A: Nowhere, because Sample obj = new Sample() won't compile.
If you mean Sample* obj = new Sample(), then it's in dynamic storage (heap).
When you call delete obj, the string will be deleted automatically, even if it's on the heap.

A: The whole og obj is on "the heap", and so is its data member. However, you do not have to worry about managing the memory assigned to the data members. Deleting obj will take care of the string too.

A: Structs, arrays, pointers and the basic numeric types will be created with the class wherever the class is allocated.
Strings are more complex. They are a sort of a container. The members of string that define the container will be stored on class' memory block as a member inside your sample class. The String's text will probably be allocated somewhere else on the heap (depends on the string class implementation).
Now, if you do Sample* blah = new Sample(); then operator new will allocate memory in the heap (the pointer will be on the stack, or on the heap if it's originally a member of a class on the heap).
If you just use it as a variable, it will be stored on the stack: Sample blah;

A: strName will be placed where your Sample object is placed. However, class string may under the hood address whatever storage it likes, whether is uses normal variables (then again they are placed where the string is placed, pointers to something, memory maps, are all the time just queries an XML interface from the other side of the earth.
However, string has to somehow store the addresses, so e.g. its pointers or references or urls or whatever addressing scheme is used, are placed where the string is placed.

Related Rule of thumb: Pointers are in itself values (which is why the are hard to handle correctly in object copying situations).


text:
Q: Offline sync with Azure Cosmos DB I have a Xamarin.Forms app using Azure Cosmos DB (DocumentDB) and I'd like to implement offline synchronization.
Is it possible? Can we use Mobile App Services with DocDB?
Thanks!

A: For the Offline Data Synchronization feature of Azure Mobile Apps, you need to use the Easy Tables support of the service which requires a back-end database with either Azure SQL Database or Storage. It currently does not support using Cosmos DB as the back-end database for Azure Mobile Apps Easy Tables / Table API support.


text:
Q: Setting up a cross browser compatible div structure with the following layout I've been trying to get this right for the last couple of hours, and was unsuccessful, i am not a front-end developer and would appreciate it much if someone could guide me in the right direction. (this is for a hobby project of mine) and i am trying to achieve a cross browser compatible (IE10+/Chrome/FF) div layout (as depicted below)
so far my miserable attempt at trying to get it to work is here ->
http://jsfiddle.net/0oax4zxx/2/
.border {
    border: 1px solid black;
}
.left {
      display:inline-block;
    height:600px;
    width:50px
}
.top {
    display:inlne;
    height:100px;
}
.dynamic {
    width:100%;
    height:300px;
}
.inner-container{
    display:inline-block;

}

left

top

Other html content goes here...

Thanks in advance!

A: It looks like you want a fixed layout. We can do that with position:absolute and use of regular top/left, and widths that use calc(100% - ...px). Like so: http://jsbin.com/zihaniqexayi/1/

A: if you want to the scroll bar to be on the dynamic area only, you can use absolute positioning for this layout.. Your example is updated at http://jsfiddle.net/0oax4zxx/3/
The code below explains the process
html, body {height:100%;
    margin:0px;
    padding:0px;}

.border
{
    border: 1px solid black;
}
/* setting the top and bottom will put make the element the same height as parent */
.left
{
    position:absolute;
    top:0px;
    left:0px;
    bottom:0px;
    width:100px; /* fixed width */
    background:#cccccc;
}
/* setting the left and right will put make the element the same width as parent */
.top
{
    position:absolute;
    top:0px;
    right:0px;
    left:100px;
    height:100px; /* fixed height */
    background:#ff0000;
}
.dynamic
{
    position:absolute;
    top:100px; /* same as the fixed height */
    left:100px; /* same as the fixed width */
    right:0px;
    bottom:0px;
    overflow:auto; /* making content scroll if too long */
    background:#0000ff;
}


text:
Q: Trying to draw a checkerboard using Turtle in Python - how do I fill in every other square? I'm trying to draw a checkerboard.
I drew the board, but now I have to define a function (a loop) that fills in every other square with black. I've been trying to write a loop to do this for a while, can someone help?
Here's my code:
import turtle

def drawGrid():
turtle.penup()
turtle.goto(-300, 250)
turtle.pendown()
turtle.forward(300)
turtle.right(90)
turtle.forward(300)
turtle.right(90)
turtle.forward(300)
turtle.right(90)
turtle.forward(300)

def drawColumns():
for i in range(4):
    turtle.right(90)
    turtle.forward(37.5)
    turtle.right(90)
    turtle.forward(300)
    turtle.left(90)
    turtle.forward(37.5)
    turtle.left(90)
    turtle.forward(300)

def drawRows():
turtle.left(180)
rows = 0
while rows <= 3:
    rows += 1
    turtle.forward(37.5)
    turtle.right(90)
    turtle.forward(300)
    turtle.left(90)
    turtle.forward(37.5)
    turtle.left(90)
    turtle.forward(300)
    turtle.right(90)

def main():
drawGrid()
drawColumns()
drawRows()
if __name__ == "__main__":
main()

A: Turtles fill method works on shapes, i.e. a completely bounded area. So rather than drawing a grid you need to think in terms of drawing a series of squares.
So lets start by defining a simple function to draw a filled in square. It takes a turtle object and a size which is the length of the side.
import turtle

def draw_filled_square(this_turtle, size):
    """Draw a square by drawing a line and turning through 90 degrees 4 times"""
    this_turtle.pendown()
    this_turtle.fill(True)
    for _ in range(4):
        this_turtle.forward(size)
        this_turtle.right(90)
    this_turtle.fill(False)
    this_turtle.penup()

we can call it like this:
window = turtle.Screen()
myturtle = turtle.Turtle()
square_size = 90
myturtle.goto(-300, 200)

draw__filled_square(myturtle, square_size)

Which draws a single square. Note that it puts it back at the starting place, so we need to move it before drawing the next square.
Now, in practice, as long as we draw the outline of the box we only need to draw filled squares, unfilled squares can be represented negative space. But for the purposes of explanation I'm going to also draw them.
Defining a function for an unfilled square is easy -- just duplicate the existing function but set this_turtle.fill(False) at the beginning instead.
Anytime something needs to count in a repeating sequence (1, 2, 3, 4, 1, 2, 3, 4, ...) it calls for use of modulo (remainder). Modulo means remainder so if x modulo y is 0 it means x is exactly divisible by y. This translates into code as if x % y == 0:
Here's a simple  drum machine to demonstrate:
def drum_loop(x):
     # go bang on the fourth beat
     if x % 4 == 0:
         print("bang!")
     else:
         print("tish")

# prints tish, tish, tish, bang! tish, tish, tish, bang!
for i in range(1,9):
   drum_loop(i)

Alternating is just like counting 0, 1 , 0, 1 repeatedly.
So we can draw a row like this:
for i in range(8):
    if i % 2 == 0:
        draw_filled_square(myturtle, square_size)
    else:
        draw_unfilled_square(myturtle, square_size)
    # move to start of next square
    myturtle.forward(square_size)

Now just repeating this isn't going to do the trick, but it should be clear you can use modulo 2 again to make the rows alternate properly.
Do this by defining a row function that will alternate between starting with a black and starting with a white square, then calling this from within another loop. (Don't forget to go back to the beginning and move down every time you start a row).

A: Here's another example where drawing creates more work for the poor turtle than simply stamping.  Rather than thinking about drawing and filling boxes, think about the board itself as a filled square onto which other filled squares are stamped:
from turtle import Turtle, Screen

NUMBER_SQUARES = 8
SQUARE_SIZE = 40
BOARD_SIZE = SQUARE_SIZE * NUMBER_SQUARES
BORDER_FRACTION = 1.025  # add a slight edge to board

STAMP_SIZE = 20  # size of turtle square image

turtle = Turtle(shape='square', visible=False)
turtle.shapesize(BOARD_SIZE / STAMP_SIZE * BORDER_FRACTION)
turtle.color('black')
turtle.stamp()

turtle.shapesize(SQUARE_SIZE / STAMP_SIZE)
turtle.color('white')
turtle.penup()

for y in range(-NUMBER_SQUARES//2, NUMBER_SQUARES//2):
    parity = y % 2 == 0

    for x in range(-NUMBER_SQUARES//2, NUMBER_SQUARES//2):
        if parity:
            turtle.goto(x * SQUARE_SIZE + SQUARE_SIZE//2, y * SQUARE_SIZE + SQUARE_SIZE//2)
            turtle.stamp()

        parity = not parity

Screen().exitonclick()

This solution can print a board in any two colors (e.g. black and red), it doesn't assume a white background. Just another example of better living through stamping.

A: import turtle

turtle.pensize(2)
turtle.penup()
turtle.goto(-160,-160)
turtle.pendown()
turtle.color("black")

for i in range(4):
    turtle.forward(320)
    turtle.left(90)

for y in range(-160,160,80):
    for x in range(-160,160,80):
        turtle.begin_fill()
        turtle.penup()
        turtle.goto(x,y)
        turtle.pendown()

        for k in range(4):
            turtle.forward(40)
            turtle.left(90)

        turtle.end_fill()

for y in range(-120,160,80):
    for x in range(-120,160,80):
        turtle.begin_fill()
        turtle.penup()
        turtle.goto(x,y)
        turtle.pendown()
        for k in range(4):
            turtle.forward(40)
            turtle.left(90)
        turtle.end_fill()

turtle.done()

A: Let's have a look at the zig-zag approach (the explanation of the code is commented inside):
import turtle

def drawGrid(rows, cols, size):
    turtle.sety(turtle.ycor() + size * rows) # Draw the initial line
    f = size * 2
    turtle.begin_fill()
    for j in range(cols): # Make the columns
        if j % 2:
            turtle.backward(f) # Make room for the zig-zag up and zig-zag down
        for i in range(rows * 2): # rows * 2 because there will be both zig-zag down and a zig-zag up for each row
            turtle.forward(size)
            turtle.right(90)
            if i % 2:
                turtle.left, turtle.right = turtle.right, turtle.left # Switch the zig-zag direction
        turtle.left(180)
    turtle.end_fill()
    turtle.sety(turtle.ycor() - size * rows) # Draw the final line

turtle.penup()
turtle.goto(-300, -50) # Set the bottom-left position of the grid
turtle.pendown()
turtle.speed("fastest") # Because I have no patience
drawGrid(8, 8, 40)

Output:

Note that the number of rows and columns must be even for this to work.


text:
Q: How to get values of form in functional component with react bootstrap? I find plenty of resources for this problem for class components, but how do I get the values of bootstraps FormControls inside a functional component like this? I never used refs before, so I am not quite sure, how to approach this task inside of a functional component.
import React from "react";
import { Modal, Button, Form, Col, Row } from "react-bootstrap";
import Button from "../button/Button";

export default function NewEventModal(props) {

  const onSubmit = (e) => {
    e.preventDefault();
    console.log(e.target.elements) /*How to get name value?*/
  };

  return (
    <Modal
      {...props}
      size="lg"
      aria-labelledby="contained-modal-title-vcenter"
      centered
    >
      <Form onSubmit={(e) => onSubmit(e)}>
          <Modal.Header closeButton>
            <Modal.Title id="contained-modal-title-vcenter">
              Create Event
            </Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <Form.Group controlId="formGridName">
              <Form.Label>Eventname</Form.Label>
              <Form.Control type="text" placeholder="Input the eventname" inputRef={(ref) => { this.name = ref }}/>
            </Form.Group>
          </Modal.Body>
          <Modal.Footer>
            <Button type="submit" text="Erstellen" />
            <Button onClick={props.onHide} text="Close"/>
          </Modal.Footer>
          </Form>
      </Modal>

  );
}


text:
Q: Java Generic extends subclass Incompatible types First, I've looked at a lot of previous posts, including:
Java Generics and generic types
Java generics incompatible type
Java Generics Incompatible Types
Java generics: incompatible types
None of them address the issue I'm having. The following code is somewhat contrived, but illustrates the problem. I'm using Java 1.8.
import java.util.List;

/**
 * Created by aaron on 11/8/2017.
 */
public abstract class Selecter<STATE extends Selecter.State, ACTION> {
    public abstract class State {
        public abstract List<ACTION> getActions();
        public abstract ACTION selectAction(List<ACTION> list, int selector);
    }

    public ACTION searchAction(STATE state, int selector) {
        return state.selectAction(state.getActions(), selector);
    }
}

Now, since STATE must be a Selector.State, and getActions() returns a List<ACTION> and selectAction() returns an ACTION from a List<ACTION>, why is there an incompatible types error in searchAction()?
How can I fix it?
EDIT
I think I've fixed it:
import java.util.List;

/**
 * Created by aaron on 11/8/2017.
 */
public abstract class Selecter<ACTION> {
    public abstract class State<A> {
        public abstract List<A> getActions();
        public abstract A selectAction(List<A> list, int selector);
    }

    public ACTION searchAction(State<ACTION> state, int selector) {
        return state.selectAction(state.getActions(), selector);
    }
}

However, I don't know why this works and the other doesn't.

A: Your original attempt doesn't work because you're using raw types.
class Selecter<STATE extends Selecter.State, ACTION>
                              ^ Selecter is generic, missing type variables.

As such, if you try to use a STATE, the generics are erased. So in:
public ACTION searchAction(STATE state, int selector) {
    return state.selectAction(state.getActions(), selector);
}

the return value is of type Object, not ACTION, because that's the upper bound of ACTION.
You could add the type variables, as suggested by Sotirios:
class Selecter<STATE extends Selecter<STATE, ACTION>.State, ACTION>

but that is pretty messy.
State is an inner class of Selecter, so it inherits its type variables. As such:
public abstract class Selecter<ACTION> {
    public abstract class State {
        public abstract List<ACTION> getActions();
        public abstract ACTION selectAction(List<ACTION> list, int selector);
    }

    public ACTION searchAction(State state, int selector) {
        return state.selectAction(state.getActions(), selector);
    }
}

seems like the easiest solution. This compiles fine.


text:
Q: Plot columns from list of data frames I'm trying to subset some dates into season then combine monthly plots of 'date and amplitude' for each season.
head(dat)
    Date  Amplitude
1 2009-09-13 -2.6966667
2 2009-09-14 -0.7264583
3 2009-09-15 -2.1823333

Here's my code to create seasons and YearMonth for plot titles:
x <- as.Date(dat$Date, format="%Y/%m/%d")
x <- as.Date(x, origin="2009-09-13")
x <- cut(x, breaks="quarter")
labs <- paste(substr(levels(x),1,4),"/",1:4, sep="")
dat$DateQ <- factor(x, labels=labs)
dat$YearMonth <- format(dat$Date, "%Y/%m")
head(dat)
Date  Amplitude  DateQ YearMonth
1 2009-09-13 -2.6966667 2009/1   2009/09
2 2009-09-14 -0.7264583 2009/1   2009/09

I used a split to create data frames for each season and then named the data frames with a for loop
dat_split_season <- split(dat, dat$DateQ)
new_names <- c("Summer_2009", "Fall_2009", "Winter_2010", "Spring_2010",
          "Summer_2010", "Fall_2010", "Winter_2011",
          "Spring_2011", "Summer_2011", "Fall_2011",
          "Winter_2012", "Spring_2012", "Summer_2012")
for (i in 1:length(dat_split_season)) {
assign(new_names[i], dat_split_season[[i]])
}

I can create the desired monthly plots by season manually by changing df
df <- Winter_2012
graphs <- lapply(split(df,df$YearMonth),
   function(gg) ggplot(gg, aes(x=Date, y=Amplitude)) +
     geom_point() + geom_line() + ylim(-10, 10) +
     ggtitle(paste(gg$YearMonth)) + theme_bw())
do.call("grid.arrange", graphs)

I would like to use a for loop or the apply() family to sequence through the seasons list, selecting the Date and Amplitude columns for each data frame and plotting by 'YearMonth'.
The issue I'm having is probably syntax related; I'm new to R and programming in general. But I have spent the last few days scouring the forum and I would appreciate some direction at this point. Thanks!

A: Here's a minimal example which I believe recreates your desired output
df1<-data.frame(YearMonth=c(rep('Aug_2012',10),rep('Sep_2012',10),rep('Oct_2012',10)), value=rnorm(30),t=rep(1:10,3) )
df2<-data.frame(YearMonth=c(rep('Aug_2012',10),rep('Sep_2012',10),rep('Oct_2012',10)), value=rnorm(30),t=rep(1:10,3) )
df_list<-list(df1,df2)

myplots<-lapply(df_list,function(x)
p<-ggplot(x,aes(x=t,y=value,group=factor(YearMonth),color=factor(YearMonth))) + geom_line() + facet_wrap(~YearMonth)
)

The lapply is used to access the list of dataframes, and then facet_wrap is used to create the grid of plots for each dataframe.


text:
Q: how to transfer dataset from t2 to tarchive on a condtion and delete then from t2
I have 3 tables t1,t2 and tarchive, I want to transfer only records from t2 into tarchive that are not included in t1 and then delete from t2.
below is the solution I have but it doesn't work:
INSERT INTO tarchiv
WHERE (SELECT COUNT(t1.id) FROM t1 as a, t2 as b WHERE a.t1id = b.t2id) = 0;

DELETE FROM t2
WHERE (SELECT COUNT(idangeb0t) FROM t1 as a, t2 as b WHERE a.t1id = b.t2id) = 0;

can someone help me out with it?

A: We can use the syntax INSERT INTO ... SELECT using a left join onto t1 and a condition where t1.id is null. This means that we do not insert any values which are in t1.
NB This is in mySQL. Depending on your RDBMS there may be modifications of the syntax INSERT INTO ... SELECT
UPDATE FOLLOWING COMMENT
If we only want to delete the values not in t1 from t2 we can use
delete from t2 where id not in (select id from t1);

create table t1 (id int);
create table t2 (id int);
create table tarchive (id int);
insert into t1 values(1),(2),(3);
insert into t2 values(3),(4);

select * from t1;
select * from t2;
select * from tarchive;

insert into tarchive(id)
select t2.id
from t2
left join t1 on t2.id = t1.id
where t1.id is null;
delete from t2;

select * from t1;
select * from t2;
select * from tarchive;

| id |
| -: |
|  1 |
|  2 |
|  3 |

| id |
| -: |

| id |
| -: |
|  4 |

db<>fiddle here

A: INSERT INTO tarchive(id)
SELECT b.id
FROM t2 AS b
WHERE NOT EXISTS
(
SELECT *FROM t1 AS a
WHERE a.id =b.id

)
delete from t2 AS b
WHERE NOT EXISTS
(
SELECT *FROM t1 AS a
WHERE a.id =b.id

)
we have found a solution :)


text:
Q: Can i afford to add win forms resource files in class library project I had a fairly big project and has lot of logic in form of classes in a folder.
Now i need to make a separate project that contains those classes.
All those classes are referring resource files for language..
Like
Localization.MyStringVariable

Copying the resource files too in a separate project make it build but throws error at runtime.
The error is resource files no loaded for neutral culture...
Any help is highly appreciated.
Exact Error:
{"Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure \"Project.Localization.resources\" was correctly embedded or linked into assembly \"ProjectDAL\" at compile time, or that all the satellite assemblies required are loadable and fully signed."}


text:
Q: How do I select (get range or selection object) an element in a contenteditable div if I know the element ID? I have this contenteditable element:

     There is some text here.
     This is the target text.
     And some here.

I want to use Javascript to select (get range object) the contents of #selectThisText. How do I get the range of the content in that element?
Thanks in advance!

A: Create a range and use its selectNodeContents() method.
var span = document.getElementById("selectThisText");
var range = document.createRange();
range.selectNodeContents(span);

This doesn't work in IE <= 8, which doesn't support DOM Range. However, this is one case which is just as easy in old IE:
var span = document.getElementById("selectThisText");
var textRange = document.body.createTextRange();
textRange.moveToElementText(span);

A: //get Selection
var selection = window.getSelection();

//get Range
var range = selection.getRangeAt(0); //where the range selection happens.

A: var text = $('#selectThisText').text();

Demo: http://jsfiddle.net/5NBnP/


text:
Q: Django model React I'm trying some Django + React stuff and I'm a bit confused with the particular role of Django model in this scheme.
As I can understand Django model provide smooth way to create some typical forms by users of the site (please correct me). And I can't feel the edge of what should be hardcoded and what I need to store in model.
In case of React (I'm trying to connect react with django through api via djangorestframework) should I create a model for Header? And store bg image with it and my slogans. I feel it's should be purely in frontend. But next section with 3 typical screens (they will be listed horizontally and swap each other). They are just copy of each other with different data (title, bg, fg, text, link), for me it seems closer to model usage. But model initially empty and if I want to get this data from model I firstly need to somehow store this data to model.
So in general my question is what the right cases for using Django models and when it's no needed. And if it possible with applying to my example to better understanding for me )
ofc I searched this info widely but so far can't create clear understanding by myself.
   Thanks )

A: You might actually be in search of a headless CMS.
To combine React and Django and still use a CMS to allow administrating text blocks and images, Django Wagtail's StreamField is a good choice.
https://docs.wagtail.io/en/v2.0/topics/streamfield.html
See for example our company's homepage: https://www.blu-beyond.com. It runs on Django Wagtail, having JS animated text blocks that are administered in the CMS (just jQuery and other JS libs, no React, in this case).
Django Wagtail offers a JSON API, as well, that can be used in React:
https://docs.wagtail.io/en/v2.8/advanced_topics/api/v2/usage.html#fetching-content
It also offers a GraphQL API.


text:
Q: How to get all dates in the last X months I want to get all dates in the last three months, so I did the following:
protected void BindPermissions(int empNum)
        {
            var permPeriod = new Dictionary<int, int>();
            permPeriod.Add(DateTime.Now.Year, DateTime.Now.Month);
            permPeriod.Add(DateTime.Now.AddMonths(-1).Year, (DateTime.Now.AddMonths(-1).Month));
            permPeriod.Add(DateTime.Now.AddMonths(-2).Year, (DateTime.Now.AddMonths(-2).Month));
            var dt = payload_object.AttendancePermissionBO.permissionList
                .Where(x => x.empNum == empNum
                && ((x.permDate.Year == permPeriod.Keys.ElementAtOrDefault(0) && x.permDate.Month == permPeriod.Values.ElementAtOrDefault(0)) ||
                (x.permDate.Year == permPeriod.Keys.ElementAtOrDefault(1) && x.permDate.Month == permPeriod.Values.ElementAtOrDefault(1)) ||
                (x.permDate.Year == permPeriod.Keys.ElementAtOrDefault(2) && x.permDate.Month == permPeriod.Values.ElementAtOrDefault(2)))).ToList().OrderBy(x => x.permDate);
            GV_PermissionHistory.DataSource = dt;
            GV_PermissionHistory.DataBind();
        }

Is there a better way to do that or this method suits what i need?

A: *

*Get the date (boundary) three months ago from today.

DateTime threeMonthsAgoDate = DateTime.Now.AddMonths(-3);

*Filter the data for permDate that after (inclusive) the date from 3 months ago.

var dt = payload_object.AttendancePermissionBO.permissionList
    .Where(x => x.empNum == empNum
        && x.permDate >= threeMonthsAgoDate.Date)
    .OrderBy(x => x.permDate)
    .ToList();

Updated:
This answer is for querying records from the last 3 months ago until the current date.
Based on Post Owner's requirements and existing code, what he needs is from

Start Date: 2022-05-01

End Date: 2022-07-31 (inclusive)

Hence @Astrid's answer is most accurate.

A: You can use the below code for all the dates of last X- months. You can do some changes based on your requirements.
 public static void Main()
    {
        var list= new List<DateTime>();

        for(int i=0;i<3;i++){
            var month= DateTime.Now.AddMonths(-i);
            var monthDates= GetDates(month.Year, month.Month);

            list.AddRange(monthDates);
        }

        foreach(var item in list){
        Console.WriteLine(item.ToString());
        }
    }

public static List<DateTime> GetDates(int year, int month)
{
   return Enumerable.Range(1, DateTime.DaysInMonth(year, month))
                    .Select(day => new DateTime(year, month, day))
                    .ToList();
}

A: It seems like you do not really want all dates in the last three months, but you want all items in your collection where permDate is a date within some date range.
Given your own approach, that some date range seems to be the two previous months plus the entire current month. I.e. for 5th of July 2022, the date range is all of May, June and July 2022.
I think you can simplify your approach by defining a start date and an end date, and compare the permDate values with those two values. A straight-forward way of doing that could be:
var today = DateTime.Today;

var startMonth = today.AddMonths(-2);
var endMonth = today.AddMonths(1);

var startDate = new DateTime(startMonth.Year, startMonth.Month, 1);
var endDate = new DateTime(endMonth.Year, endMonth.Month, 1);

Then, you can use startDate and endDate in your filtering:
var dt = payload_object.AttendancePermissionBO.permissionList
    .Where(x =>
        x.empNum == empNum &&
        x.permDate >= startDate &&
        x.permDate < endDate)
    .OrderBy(x => x.permDate)
    .ToList();


text:
Q: Which preposition to be used for the below statements? Of, From, or By? I'm confused with which preposition to be used for the following sentences. A friend of mine told me that is should be "from".
1.Those opening songs are FROM Lady Gaga.
2. Those songs are FROM Beatles."
I believe it should have been of or by because the above sentences are pertaining to songs sung by the said artists. It shows possession.
Many thanks!


text:
Q: free() function in c on a struct generates a breakpoint without any error code I'm trying to create a linked list of users in a social network in c. I have 2 modules:

*

*User - a struct which contains a username (char), number of friends(int) and a linked list of friends (each block in the list contains a name and a pointer to next friend of the User).the User module has methods to add a friend to the list and to remove.
2.Social network - general module to organize users. it contains a linked list of Users.the methods here control the users. It adds friends as part of add relationship function. it calls to the user methods and manages the users as part of the encapsulation rules.
I use malloc for the structs and chars. I eventually use free on those mallocs at the end of the program using functions such as Network_delete() and UserDelete(..)
I encounter an error while calling to free in Network_delete() function (breakpoint with no error code - not even heap related) and I can't figure out the issue. I use well-defined rules of the use of malloc but maybe I'm wrong in the assignment.
comment: def.h contains the Result enum used in the modules.
the modules:
User.h
#ifndef _USER_H_
#define _USER_H_
#include "defs.h"
typedef struct LINKED_LIST* L_list;
typedef struct user_t *PUser;
PUser User_Create(char* name);
void User_Delete(PUser pUser);
Result User_addFriend(PUser pUser, char* name);
Result User_removeFriend(PUser pUser, char* name);
char* User_getName(PUser pUser);
L_list User_getFriendsList(PUser pUser);
int User_getFriendsNum(PUser pUser);
#endif /* _USER_H_ */

User.c
    #include "User.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// linked list
typedef struct LINKED_LIST {
    char* name;
    struct LINKED_LIST* pNext;
}L_L;
// user struct- include the user name,number of his friends and a list of his friends
typedef struct user_t
{
    char* name;
    L_list friends_list;
    int friends_num;
}USER;
// user creator
PUser User_Create(char* name)
{
    if (!name) return NULL;
    PUser pUser;
    pUser = (PUser)malloc(sizeof(USER));
    if (pUser == NULL) return NULL;
    if(!(pUser->name = (char*)malloc(1 +strlen(name)))) {
        free(pUser);
        return NULL;
    }
    pUser->friends_list = NULL;
    pUser->friends_num = 0;
    strcpy(pUser->name, name);
    return pUser;
}
// user destructor-delete the user and his friends list
void User_Delete(PUser pUser)
{
    if (!pUser) return;
    L_list current = pUser->friends_list;
    L_list to_delete = current;
    while (current)
    {
        current = current->pNext;
        free(to_delete->name);
        free(to_delete);
    }
    pUser->friends_list = NULL;
    free(pUser->name);
    free(pUser);
}
//add new friend to the friends list
Result User_addFriend(PUser pUser, char* name)
{
    if (!pUser||!name) return FAILURE;
    L_list current = pUser->friends_list;
    while (current)
    {
        if (strcmp(name, current->name)==0)
        {
            return FAILURE;
        }
        current = current->pNext;
    }
    L_list new_list_element = (L_list)malloc(sizeof(L_L));
    if (!new_list_element) return FAILURE;
    if (!(new_list_element->name = (char*)malloc(1 + strlen(name)))) {
        free(new_list_element);
        return FAILURE;
    }
    strcpy( new_list_element->name ,name);
    new_list_element->pNext = pUser->friends_list;
    pUser->friends_list = new_list_element;
    pUser->friends_num++;
    return SUCCESS;
}
//remove friends from the friends list
Result User_removeFriend(PUser pUser, char* name)
{
    if (!pUser || !name) return FAILURE;
    L_list current = pUser->friends_list;
    L_list before_current = pUser->friends_list;
    while (current)
    {
        if (strcmp(current->name, name) == 0)
        {
            before_current->pNext = current->pNext;
            free(current->name);
            free(current);
            pUser->friends_num--;
            return SUCCESS;
        }
        before_current = current;
        current = current->pNext;
    }
    return FAILURE;
}
//get the user name
char* User_getName(PUser pUser)
{
    if (!pUser) return NULL;
    return pUser->name;
}
//get the first friend on the list
L_list User_getFriendsList(PUser pUser)
{
    if (!pUser) return NULL;
    return pUser->friends_list;
}
//get the user number of frinds
int User_getFriendsNum(PUser pUser)
{
    if (!pUser) return 0;
    return pUser->friends_num;
}
}

Socialnetwork.h
    #ifndef _SOCIAL_NETWORK_H_
#define _SOCIAL_NETWORK_H_
#include "User.h"
typedef struct LINKED_LIST_SN* social_network_elem;// a list for social network
Result Network_addUser(char* member_invite, char* new_member);
Result Network_addRelationship(char* member1, char* member2);
Result Network_removeRelationship(char* member1, char* member2);
void Network_delete();
#endif /* _SOCIAL_NETWORK_H_ */

Socialnetwork.c
    #include "SocialNetwork.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "User.h"
typedef struct LINKED_LIST_SN {
    PUser pUser;
    struct LINKED_LIST_SN* pNext;
}S_N_L;

social_network_elem pSocial_network;
//adding new user to the network
Result Network_addUser(char* member_invite, char* new_member)
{
    if (!member_invite && !new_member) return FAILURE;//bad input
    if (!new_member&&(pSocial_network!=NULL)) return FAILURE;
    if (!member_invite&&new_member)//first member
    {
        pSocial_network = (social_network_elem)malloc(sizeof(S_N_L));
        if (!pSocial_network) return FAILURE;
        pSocial_network->pUser = User_Create(new_member);
        pSocial_network->pNext = NULL;
        return SUCCESS;
    }
    social_network_elem current = pSocial_network;
    PUser pMember_invite=NULL;
    while (current)
    {
        if (strcmp(new_member, User_getName(current->pUser)) == 0)//new_member already in social network
        {
            return FAILURE;
        }
        if (strcmp(member_invite, User_getName(current->pUser)) == 0)//apdating  pointer to the member who invited
        {
            pMember_invite = current->pUser;
        }
        current = current->pNext;
    }
    if (!pMember_invite) return FAILURE; //no inviting member found in network
    social_network_elem pNew_social_network_elem;
    pNew_social_network_elem = (social_network_elem)malloc(sizeof(S_N_L));
    if (!pNew_social_network_elem) return FAILURE;
    pNew_social_network_elem->pUser = User_Create(new_member);
    if (!pNew_social_network_elem->pUser) return FAILURE;
    pNew_social_network_elem->pNext = pSocial_network;
    pSocial_network = pNew_social_network_elem;
    if (!Network_addRelationship(new_member, member_invite))
    {
        pNew_social_network_elem = pSocial_network;
        pSocial_network = pSocial_network->pNext;
        User_Delete(pNew_social_network_elem->pUser);
        free(pNew_social_network_elem);
        return FAILURE;
    }
    return SUCCESS;
}
Result Network_addRelationship(char* member1, char* member2)
{
    if (!member1 || !member2) return FAILURE;
    PUser pMember1 = NULL;
    PUser pMember2 = NULL;
    social_network_elem current = pSocial_network;
    while (current)
    {
        if (strcmp(member1, User_getName(current->pUser)) == 0)//we found member 1
        {
            pMember1 = current->pUser;
        }
        if (strcmp(member2, User_getName(current->pUser)) == 0)//we found member 2
        {
            pMember2 = current->pUser;
        }
        current = current->pNext;
    }
    if (!pMember1 || !pMember2) return FAILURE;//one of the mambers not in the list
    if (!User_addFriend(pMember1, member2)) return FAILURE;//create relationship failed
    if (!User_addFriend(pMember2, member1))
    {
        User_removeFriend(pMember1, member2);
        return FAILURE;
    }
    return SUCCESS;
}
Result Network_removeRelationship(char* member1, char* member2)
{
    if (!member1 || !member2) return FAILURE;
    PUser pMember1 = NULL;
    PUser pMember2 = NULL;
    social_network_elem current = pSocial_network;
    while (current)
    {
        if (strcmp(member1, User_getName(current->pUser)) == 0)//we found member 1
        {
            pMember1 = current->pUser;
        }
        if (strcmp(member2, User_getName(current->pUser)) == 0)//we found member 2
        {
            pMember2 = current->pUser;
        }
        current = current->pNext;
    }
    if (!pMember1 || !pMember2) return FAILURE;//one of the mambers not in the list
    if (User_getFriendsNum(pMember1) <= 1 || User_getFriendsNum(pMember2) <= 1) return FAILURE;//num of friends is less than 2
    if (!User_removeFriend(pMember1, member2) || !User_removeFriend(pMember2, member1)) return FAILURE;//remove relationship failed
    return SUCCESS;
}
void Network_delete()
{
    social_network_elem current = pSocial_network;
    social_network_elem tmp= NULL;

    while (current)
    {
        tmp = current->pNext;
        User_Delete(current->pUser);
        free(current);
        current = tmp;
    }
}

I have errors in the call to free in the following functions:
Network_delete()
the other calls for free give no error.
furthermore, I use Valgrind in Unix environment for memory violation and debug and it seems like the mallocs create blocks in a different size to the types it contains.


text:
Q: How to output to S-Video on Windows XP in single-monitor mode (clone display)? I am using an IBM ThinkPad T30 running Windows XP. It is connected to a TV system via S-Video output.
Windows is currently set up in multi-monitor mode with monitor 2 being output to S-Video. However, since there is no preview monitor, I can't interact with anything I drag to monitor 2 as I can't see it.
I would rather have the system set up so that there is only one monitor and the output is cloned to the laptop display and S-Video. This allows me to see what I'm doing on the TV system. Is this possible?

A: If I am reading the specs for this right, you are using the "ATI RADEON 7500 Mobility video chipset". You'll need to make sure you have the latest drivers. If that doesn't include the "Catalyst Control Center" (ATI driver utility) you'll need to use windows to manage the desktop mirror.

*

*Right click on the desktop and go to properties.

*Click the settings tab.

*You should see two screens.

*Make sure that neither one has "Extend my Windows desktop onto this monitor" checked.

If you only have one screen on the settings tab, and you don't have the ATI driver utility. Either IBM has their own utility to do this, or you'll have to go to ATI (now AMD) and dig through the driver archives until you find a package that has the driver utility. That one should give you the option to clone screens onto the S-video port.
As a final thing, you might be able to access the Utility from the Advanced button on the settings tab. There may be a tab for ATI in there.
Hope that helps

A: On most laptops with an external display jack, you can use a keyboard shortcut to toggle between the built-in display, the external display, cloned display, or extended display (e.g., both displays side-by-side).  The key for switching display modes on PC laptops is usually either two bulging rectangles (usually one is only an outline and the other is filled in), or a bulging rectangle with two vertical lines (one on each side).
Judging from a few pictures I found online, it looks like your key combination is Fn+F7.  Fn is located in the lower left corner of the keyboard, and F7 is located in the row of F-keys just above your number row.
View the image below at full size to see the keys more clearly.


text:
Q: Unable to invoke "btoa" and "item.slice" method in my script for retrieving the playlist Whenever I am trying to invoke the "btoa" method, I am not able to use this within my script. I created a variable to store the client id: client_secret in base64. The id and secrets are being retrieved from the ".env" file.
I have also tried to use the Buffer method, but unable to use this as well. I am getting the error "invalid from" in Buffer.
can someone help me?
Please look at the full code,
const client_id = process.env.SPOTIFY_CLIENT_ID;
const client_secret = process.env.SPOTIFY_CLIENT_SECRET;
const refresh_token = process.env.SPOTIFY_REFRESH_TOKEN;

const basic = btoa(`${client_id}:${client_secret}`);
const NOW_PLAYING_ENDPOINT = `https://api.spotify.com/v1/me/player/currently-playing`;
const TOP_TRACKS_ENDPOINT = `https://api.spotify.com/v1/me/top/tracks`;
const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`;

const getAccessToken = async () => {
  const response = await fetch(TOKEN_ENDPOINT, {
    method: 'POST',
    headers: {
      Authorization: `Basic ${basic}`,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: new URLSearchParams({
      grant_type: 'refresh_token',
      refresh_token
    })
  });

  return response.json();
};

export const getNowPlaying = async () => {
  const { access_token } = await getAccessToken();

  return fetch(NOW_PLAYING_ENDPOINT, {
    headers: {
      Authorization: `Bearer ${access_token}`
    }
  });
};

export const getTopTracks = async () => {
  const { access_token } = await getAccessToken();

  return fetch(TOP_TRACKS_ENDPOINT, {
    headers: {
      Authorization: `Bearer ${access_token}`
    }
  });
};

Using the above script I am trying to embed the customized Spotify play on my site. This wrapper is intended to display the top track as well.
Also, whenever I am trying to run the wrapper used to display the top tracks, it displays the following error,

Full code for displaying the top tracks:

import { type NextRequest } from 'next/server';
import { getTopTracks } from 'lib/spotify';

export const config = {
  runtime: 'experimental-edge'
};

export default async function handler(req: NextRequest) {
  const response = await getTopTracks();
  const { items } = await response.json();

  const tracks = items.slice(0, 10).map((track) => ({
    artist: track.artists.map((_artist) => _artist.name).join(', '),
    songUrl: track.external_urls.spotify,
    title: track.name
  }));

  return new Response(JSON.stringify({ tracks }), {
    status: 200,
    headers: {
      'content-type': 'application/json',
      'cache-control': 'public, s-maxage=86400, stale-while-revalidate=43200'
    }
  });
}

A: The problem is that you misspelled the Bytes to ASCII function, it is btoa, not btao.
If you are looking to do it the other way around, spell it atob.


text:
Q: Is the '&' character safe against xss attacks? I wonder if the character & is safe to be output to a browser. In case '<' '>' '\'' '\"' '=' are all encoded,

is there a possibility to get damaged by an attack if '&'isn't
  encoded?

A: It is not safe, you should escape it. You can see an example of exploiting XSS using & here: http://erlend.oftedal.no/blog/?blogid=124


text:
Q: Installed Linux Mint18.3 using Oracle Virtual Box 5.2.6 r120293 on HP 8560W 3D acceleration does not work in Ver 5.2.6 R12093.Remove 3D acceleration the Linux Mint works normally. How to fix this ?

A: I installed the NEW patch VboxGuestAddition_5.2.7-120226.iso, shut down the machine , and then selected the 3D acceleration in the Settings in Oracle Box.
The system works well but there still seems to be some resolution problem , the LM (linux mint logo) does not come clearly and there seems to be some resolution problem. In full screen mode the Logo disappears, re-scale it to smaller window the logo appears but not as clear and sharp as Originally it used to come prior to installing the patch. The patch works but seems there is still some issue.
Any one has experienced the same and has a solution, please let me know.


text:
Q: Trying to find a simple example of pstool that compiles There have been many posts on this site either requesting simple examples illustrating the pstool package, or providing (often not-simple) ones. I've tried all of them and none of them compile for me. I've also tried to read pstools.sty, which came with my installation, but unfortunately it contained no simple examples. It seems that the following MWE is about as simple as one could possibly get.
\documentclass{article}
\usepackage{pstool}
\EndPreamble
\begin{document}
\psfragfig{trial}{%
  \psfrag{[Mp]}{$M_a$}%
}
\end{document}

Yet it throws all sorts of inexplicable errors, and fails to compile.
I'm running the pdflatex that comes with texlive 2016, installed in the recommended way, on a Linux 64 bit machine, Ubuntu 16.04.
To compile I'm using the command

pdflatex -shell-escape

There's talk on the web about a file called pstool-statusfile.txt, which I don't understand, but I've touch'ed it, just in case, it's zero size before and after compilation. The file trial.eps was downloaded from
the CTAN example site for pstools
I'd love to hear if anybody can get this code to run, if so, how? if not, why not?
Here's the relevant portion of the .log file:
Preview: Fontsize 10pt
(.//trial.tex) <trial.eps>
! Missing { inserted.
<to be read again>
                   \begingroup
l.21  \includegraphics [] {trial}

LaTeX Warning: Command \b invalid in math mode on input line 21.

! Missing $ inserted.
<inserted text>
                $
l.21  \includegraphics [] {trial}

! Missing $ inserted.
<inserted text>
                $
l.21  \includegraphics [] {trial}

! Missing } inserted.
<inserted text>
                }
l.21  \includegraphics [] {trial}

Preview: Tightpage -32891 -32891 32891 32891
[1] (.//trial-pstool.aux) )
(see the transcript file for additional information)
Output written on .//trial-pstool.dvi (1 page, 2232 bytes).
Transcript written on .//trial-pstool.log.

(./pstool-statusfile.txt)

Package pstool Warning: Execution failed during process:
  latex -shell-escape -output-format=dvi -output-directory="./" -interaction=no
nstopmode  "trial-pstool.tex"
This warning occurred on input line 9.

=== pstool: end processing ===

[1
Non-PDF special ignored!{/usr/local/texlive/2016/texmf-var/fonts/map/pdftex/upd
map/pdftex.map}] (./myExample.aux)

A: note that you need pdflatex --shell-escape to enable the psfrag processing.
When running your MWE the log complained of missing packages so I added tikz and its calc library then it worked as expected. trial.eps here is a copy of example-image.eps that is in tex distributions (if I left it as example-image ot ran without error but found the png file rather than eps so coukd not do the replacement
\documentclass{article}
\usepackage{pstool}
\usepackage{tikz}
\usetikzlibrary{calc}
\addtolength\textwidth{1in}
\addtolength\oddsidemargin{-.5in}
\EndPreamble
\begin{document}

\includegraphics{trial}

\psfragfig{trial}{%
  \psfrag{Image}{$M_a$}%
}
\end{document}

here I show the image included directly and with the psfrag replacement.


text:
Q: ansible nested jinja expression I'm trying to generate a file using a template with Ansible and Jinja2 but I can't seem to get a variable to be recognized.
I have numerous datacenters (dc) and this is declared as "dc" in my hosts_vars file for the host I am running this playbook against. I can call "dc" within the template and it works. My problem lies when I need to call a group of that "dc",
i.e. my datacenter is 'tucson' and I have a group within 'tucson' that is called 'tucson-linux'. I need to be able to dynamically get the list of hosts from 'tucson-linux'. I can do this statically with the following code, In this case, I am grabbing 'gui_addr' from each host in that group.
My template:
{
 "cluster": {
  "name": "{{ dc|upper }}-Cluster",
  "config": {
   "ip-address": [ {% for host in groups['tucson-linux'] %}"{{ hostvars[host].gui_addr + '",' }}{% endfor %} ]
 }
}

I've tried different variations of substituting 'tucson' with the "dc" var but no luck, I have read that you can't nest jinja expressions which appears to be what I am trying to do
{
 "cluster": {
  "name": "{{ dc|upper }}-Cluster",
  "config": {
   "ip-address": [ {% for host in groups['{{dc}}-linux'] %}"{{ hostvars[host].gui_addr + '",' }}{% endfor %} ]
 }
}

The error,
 fatal: [tucson-server-01]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'dict object' has no attribute '{{dc}}-linux'"}

Can someone help me understand why this doesn't work?

A: Once you've gotten into Jinja template land, you don't need to use more curly braces; you can use the Jinja template language (which bears a strong resemblance to Python in many cases).
In particular, where you write:
{% for host in groups['{{dc}}-linux'] %}

If you were in, say, Python, you'd concatenate the variable dc and the string -linux.  Jinja has a specific string concatenation operator and I think this should work
{% for host in groups[dc ~ '-linux'] %}


text:
Q: select on a bit vector in C++ complexity and implementation I'm implementing a matrix reduction algorithm, I'm a math student.
Obviously I've searched and read around internet but didn't find exactly what I was looking for (I list at the end what I've found and the papers that I've read.)
Quick overview of the problem:

*

*The bitvector b has FIXED LENGTH N.

*b changes at every step (could be only at a couple of indexes (most of the times) or at considerably more indexes (from 1/10 to 1/3), this only in ~10% of the cases).

*I already have a sparse implementation, now I'd like to code it using some smart implementation of the bitvector.
//initialize to 0
b=bitvector(0, n=N)

for i in 1 to N
    {some operations on the bitvector b}
    get I= { j | b[j] == 1 }
    {save I}

What I need is:

*

*quickly set b[i]=1 or =0 (possibly O(1))

*quickly get the set of indexes I at each step (definitely not more than O(logN), ideally O(1))

*a C++ library that allows it

*papers/documentation

What would be nice to have:

*

*a fast way to get the "lowest one" (the last index set to 1, namely select(rank(b)), if both operations are fast (O(1)))

What I do not need is:

*

*save space

*compress the data

I have been using the library Sdsl 2.0 of Simon Gog et al. (https://github.com/simongog/sdsl-lite) but the select structure
bit_vector::select_1_type

costs O(n) to be initialized, O(1) for every query but does not "follow" the changes in b (right?? I haven't found anything very specific about it), meaning that it needs to be initialized at every step after the modifications.
Papers that I've read are:
"Fast, Small, Simple Rank/Select on Bitmaps" (G. Navarro and E. Providel) and "Practical Entropy-Compressed Rank/Select Dictionary" (D. Okanohara
K. Sadakane) and I would appreciate any link to solid implementations in C++ (if the structure fulfills my requirements)
Things that I've found here on stackexchange about similar topics that didn't help:

*

*Dynamic bit vector in C/C++

*Bit vector and bitset
Sorry for the lengthy question, I hope I explained what I need and my determination to finding it. I'm still very confused about various things related with bitvectors, it's definitely not my field of expertise, so any clarification is appreciated.
Thanks in advance.

A: The structure described here is the closest thing I am aware of to the properties you want.
Specifically:

*

*initialisation is constant time

*setting/clearing entries is constant time

*testing for membership is constant time

*retrieving the set of entries is O(N) in the number of entries (assuming you don't need them sorted - you actually end up walking them in order of insertion; you're not going to do better than O(N) overall if you need to walk all of them for whatever happens next, of course)