text:
Q: How to position multiple decorations on a path while keeping their separation constant? The at position=<value> syntax for decorations obviously makes the positioning of the decorations dependent on the path length:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{decorations.markings}

\begin{document}

\begin{tikzpicture}[decoration={
  markings,
  mark=at position 0.4
  with {\node[draw=blue,fill=blue,inner sep=2pt] {};},
  mark=at position 0.6
  with {\node[circle,draw=green,fill=green,inner sep=2pt] {};}
}
]
\node (A) {A};
\node at (1,0) (B) {B};
\draw[magenta,postaction=decorate] (A) .. controls(0.25,2) and (0.75,-2) .. (B);
\begin{scope}[xshift=3cm]
\node (A) {A};
\node at (1,0) (B) {B};
\draw[magenta,postaction=decorate] (A) .. controls(0.25,4) and (0.75,-4) .. (B);
\end{scope}
\begin{scope}[xshift=6cm]
\node (A) {A};
\node at (1,0) (B) {B};
\draw[magenta,postaction=decorate] (A) .. controls(0.25,7) and (0.75,-7) .. (B);
\end{scope}
\end{tikzpicture}

\end{document}

Since the three magenta paths have increasing length, the markings will be farther apart from each other. Is there a way to place both decorations such that the distance along the path between them remains constant (i.e., placing both decorations at, let's say, half the path but guaranteeing that they will always be 50pt away from each other along the path)?

A: Steps:

*

*Get the total length of the path with the help of the /pgf/decoration/mark info/distance from start key

*

*Save this in \@totallength and make it global

*at position 1 works not every time (as previously found out on TeX.sx), so a very short distance from the end is used; here -.01pt worked, -.001pt didn't for the first path

*Use .5*\@totallength-25pt for the first node and

*use .5*\@totallength+25pt for the second

Code
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{decorations.markings}
\makeatletter
\tikzset{%
    decorate me/.style={
    decoration={
        markings,
        mark=at position -.01pt with {%
            \pgfkeysgetvalue{/pgf/decoration/mark info/distance from start}\@totallength
            \global\let\@totallength\@totallength
        },
        mark=at position .5*\@totallength-25pt with {\node[draw=blue,fill=blue,inner sep=2pt] {};},
        mark=at position .5*\@totallength+25pt with {\node[circle,draw=green,fill=green,inner sep=2pt] {};}
    },
    postaction=decorate
}
}
\makeatother
\begin{document}

\begin{tikzpicture}
\node (A) {A}; \node at (1,0) (B) {B};
\draw[magenta, decorate me] (A) .. controls(0.25,2) and (0.75,-2) .. (B);
\begin{scope}[xshift=3cm]
\node (A) {A}; \node at (1,0) (B) {B};
\draw[magenta, decorate me] (A) .. controls(0.25,4) and (0.75,-4) .. (B);
\end{scope}
\begin{scope}[xshift=6cm]
\node (A) {A}; \node at (1,0) (B) {B};
\draw[magenta, decorate me] (A) .. controls(0.25,7) and (0.75,-7) .. (B);
\end{scope}
\end{tikzpicture}
\end{document}

Output

A: Use \pgfdecoratedpathlength to calculate exact, absolute distances:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{decorations.markings}

\begin{document}

\begin{tikzpicture}[decoration={
  markings,
  mark=at position 0.5*\pgfdecoratedpathlength-25pt
  with {\node[draw=blue,fill=blue,inner sep=2pt] {};},
  mark=at position 0.5*\pgfdecoratedpathlength+25pt
  with {\node[circle,draw=green,fill=green,inner sep=2pt] {};}
}
]
\node (A) {A};
\node at (1,0) (B) {B};
\draw[magenta,postaction=decorate] (A) .. controls(0.25,2) and (0.75,-2) .. (B);
\begin{scope}[xshift=3cm]
\node (A) {A};
\node at (1,0) (B) {B};
\draw[magenta,postaction=decorate] (A) .. controls(0.25,4) and (0.75,-4) .. (B);
\end{scope}
\begin{scope}[xshift=6cm]
\node (A) {A};
\node at (1,0) (B) {B};
\draw[magenta,postaction=decorate] (A) .. controls(0.25,7) and (0.75,-7) .. (B);
\end{scope}
\end{tikzpicture}

\end{document}


text:
Q: get rid of padding in cells (set image to size of cell)
I have a table that presents images, the image is pinned to all four sides of the cell. The cell is of height 200, But there seems to be black paddings inside the cell for each image. I don't know where the padding is coming from since I figured if I pin the image to the cell it shouldn't have any padding?
Note: I subclass UITableViewCell so "self" is the cell itself
[self.thumbnail autoPinEdge:ALEdgeRight toEdge:ALEdgeRight ofView:self];
[self.thumbnail autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self];
[self.thumbnail autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:self];
[self.thumbnail autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:self];
[self.thumbnail autoSetDimension:ALDimensionHeight toSize:200];

And then inside the UITableController I have
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
  return 200;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Turn off Compatibility Mode inside of Page Viewer Web Part (SharePoint 2010) We have web site that we created that uses java in it for sorting tables. When I go directly to the page it works find (I had to turn of compatibility mode for the site). But when I take this site and try to put it in a Page Viewer Web Part it breaks and does not show all the java. How do I turn off compatibility mode inside of the Page Viewer Web Part?
P.S. It works fine in Chrome. I just have this issue in IE.


text:
Q: Pokemon defending gyms I have been looking through the Pokemon Go questions and keep noticing questions about the coins you get for having a Pokemon in a gym. I recently had a Pokemon in a gym for 3+ days and I only got 50 coins.
Have they capped the coins at 50?
Am I missing something?
Have they changed how it works now?

A: Maximum coins you can obtain by day is 50. So your pokemon will never gave you after defending gym more then 50 coins because it is your daily limit.


text:
Q: Angular test multiple calls via $inject with deferred Well I've spent a day or so looking for solutions to this and I don't know that I'm any the wiser, so I've broken down and decided to ask. Also, I'm fairly new to angular, so patience is appreciated.
I have a service that is periodically called from a controller to retrieve updated judge scores from a remote server. Fairly standard stuff. Only the relevant code is shown - without error handlers and interval cancelling, etc.
 $app.service('ResultService', function($http) {
        var self = this;
        self.results = {};

        self.getResults = function() {

            return $http.get('/results').then(function(response) {
                return $q.when(response.data).then(function(data) {
                    angular.copy(self.results, response.data);
                };
            };

        };
    });

    $app.controller('ResultController', function($interval, resultService) {
        var vm = this;

        $interval(function() {
            resultService.getResults().then(function(data) {
                vm.results = data;
            });
        }, 1000);
    });

All good so far, and everything works as desired in the browser.
Now to testing. I'd like to verify that updates are received and processed by the getResults function, however I'm struggling to perform the necessary chicken sacrifices to cause a deferment to be used more than once. I thought I could do something like this:
var deferred;
beforeEach(inject(function($q, httpBackend) {
    deferred = $q.defer();
    httpBackend.whenGET('/results').respond(deferred.promise);
});

it('updates results', inject(function($interval) {
    deferred.resolve({some: 'data'});
    scope.$digest();
    httpBackend.flush();
    $interval.flush(1200);
    // This works fine
    expect(resultsService.results).toEqual({some: 'data'});

    deferred.resolve({other: 'data'});
    scope.$digest();
    httpBackend.flush();
    $interval.flush(1200);
    // But this of course does not.
    expect(resultsService.results).toEqual({other: 'data'}); // fails
});

Now it appears that a deferred's promise can only be resolved once. So my question is, how do I provide fresh data to the service's $http.get() call with each tested iteration? I've tried various things, all without success:

*

*Created a deferred that itself returned a deferred promise. This way madness lies.

*Attempted to re-set the httpBackend.whenGET() with a new response. This had no effect.

*Created a new deferred inside the test between the interval iterations. Needless to say this failed, since the original deferred's promise had already been set up.

*Returned a static value from whenGET(), and manipulated that value directly. Unfortunately, while this "works", it seems rather hackish, and caused another test (one that expects a rejection) to fail.

So what am I missing? What's the trick here? I'm open to alternate solutions (not using deferreds) as well as anything that will clear the scales from my eyes with the code as-is.

A: Not too sure about this but nobody else has replied yet.
Strategy :

*

*define a data array with one mock data-set per array element.

*exploit a data.reduce() pattern to test each mock data-set in async sequence.

*accumulate results in an array as the sequence progresses.

*execute a single expect() asynchronously when all results are gathered - should equal the original data array.

it('updates results', inject(function($interval) {
    var dataArray = [
        {some: 'data'},
        {other: 'data'}
    ]
    data.reduce(function(promise, data) {
        return promise.then(function(resultsArray) {
            // *** not sure about this section - I just copied and pasted ***
            deferred.resolve(data);
            scope.$digest();
            httpBackend.flush();
            $interval.flush(1200);
            // *** ****************************************************** ***
            return resultsArray.concat(resultsService.results);
        });
    }, deferred.resolve([])) // starter promise resolved with an empty results array.
    .then(function(results) {
        expect(results).toEqual(dataArray);
    });
});

Quite likely not 100% correct but may stimulate further ideas.


text:
Q: Expect Scripting Issue Reading From File I am trying to change the password for a user on a bunch of linux based routers pulling IPs from a list. The iplist.txt is just a list of ips (one per line). This is the code I am trying to use:
#!/usr/bin/expect
set timeout 20
#Edit for User
set user username
#Edit for Old Password
set old oldpassword
#Edit for New Password
set new newpassword
#get IP List from iplist.txt
set f [open "/iplist.txt"]
set hosts [split [read $f] "\n"]
close $f

foreach host $hosts {
        spawn -noecho ssh -q -o "StrictHostKeyChecking=no" $user@$host
        expect "assword:"
        send "$old\r"
        expect ">"
        send "user set $user password=$new\r"
        expect ">"
        send "quit\r"
        expect eof
        close
}

Which works for the first ip on the list but send this error on the second:
spawn_id: spawn id exp4 not open

I got it to work this way as I wanted:
    #!/usr/bin/expect
    set timeout 30
    #Edit for User
    set user user
    #Edit for Old Password
    set old oldpassword
    #Edit for New Password
    set new newpassword
    #get IP List from iplist.txt
    set f [open "/iplist.txt"]
    set data [read $f]
    close $f

    foreach line [split $data \n] {
            if {$line eq {}} continue
            spawn -noecho ssh -q -o "StrictHostKeyChecking=no" $user@$line
            expect "assword:"
            send "$old\r"
            expect ">"
            send "user set $user password=$new\r"
            expect ">"
            send "\r"
            expect ">"
            send "quit\r"
            send "\r"
            expect eof
    }

The next issue I run into is if the device doesn't have the old password or if the linux box cannot reach the device via ssh, it will error out with the same spawn id exp* not open when it gets to that IP and will not continue onto the next IP in the list. Is there anyway I can a statement that says if "assword:" comes up a second time to move onto next IP and if ">" comes up like its supposed to keep going with the script, then add a line after the spawn command that will move to the next IP in list if it doesn't receive the first expect "assword:"?
Any help would be appreciated. I am new to expect, but seems to be a really good tool for mass ssh processes in a script. Just having trouble tweaking it to not error out on 1 job instead of moving to next job upon error.

A:     #!/usr/bin/expect
    set timeout 30
    #Edit for User
    set user user
    #Edit for Old Password
    set old oldpassword
    #Edit for New Password
    set new newpassword
    #get IP List from iplist.txt
    set f [open "/iplist.txt"]
    set data [read $f]
    close $f

    foreach line [split $data \n] {
            if {$line eq {}} continue
            spawn -noecho ssh -q -o "StrictHostKeyChecking=no" $user@$line
            expect {
                    "assword:" {
                            send "$old\r"
                            expect {
                                    "assword:" {
                                                    close
                                                    continue
                                                    }}
                            expect {
                                    "*" {
                                            send "user set $user password=$new\r"
                                            expect ">"
                                            send "quit\r"
                                            close
                                            continue
                                            }}}}
            expect {
                    "*" {
                            close
                            continue
                            }}
            expect eof
    }

Probably a bit dirty scripting, but it works. Now if I can figure out how to export successful, wrong password, and timeout logs so I know if any error-ed out.


text:
Q: How to install e(fx)clipse 3.4.1 in Eclipse with Java 11? I am using the 4.9.0 Version of the Eclipse IDE with a JDK 11 and was trying to install the e(fx)clipse 3.4.1 Plugin. Somehow it could not find all resources, to install it properly and I got the following message:
Error Message
Are the components with those versions not compatible?
Thanks in advance

A: Try installing version (3.4.1) release from this Update site.
Also check this issue on GitHub.


text:
Q: How will I stop Ajax request service from anonymous user in Tikiwiki? I found an Ajax service running as I called my Event tracker calendar.
[myserver]/tiki-tracker_calendar-list?trackerId=30&beginField=startDate&endField=endDate&resourceField=title&coloringField=null&filters=%0D%0A%7Bfilter%20field%3D%22tracker_field_eventCategory%22%20content%3D%22%22%7D%0D%0A&start=1488085200&end=1491710400&_=1490626987241
If the attacker leverage this and enter:
tiki-tracker_calendar-list?trackerId=30&beginField=startDate&endField=endDate&start=0&end=9999999999
The system will return all the events in tracker 30.
I tried to enter:
`if (! isset($user))
{
header('Location: index.php');
die;
}`
in File: /var/www/html/tikisvn15/tiki-ajax_services.php
At line 35
It works. Is there any other way? Would my modification stop the Ajax service from other components?

A: You can set which groups can see what using the Tiki permissions system. See the documentation here
Note that once you have set your tracker not to be visible for anonymous (not logged in) users you will need to rebuild your search index (on Control Panels -> Search) because TrackerCalendar uses the search index extensively.
I would advise against putting arbitrary user checks like this in the tiki code as things will stop working and it will be very hard to work out why, i think.


text:
Q: Difference between audio encoding/decoding and format conversion Recently i have been trying to convert an audio file from one format to another through ffmpeg. i was trying to do some google but results made me a little confused about the difference between encoding and decoding an audio file and converting from one format to another.

A: Let me describe it this way: There are several different file formats for video files (sometimes also called "wrappers"). There are also several different codecs which can be used to encode (or compress) the audio and video. Audio and video use different codecs - and the encoded formats can be sorted in different file types/formats.
So when you talk about "encoding" vs. "converting" a couple of things come into play.
"Encoding" would be the act of taking audio/video and encoding them into a given codec(s). "Converting" implies having stuff in one format, but wanting it in another. There are two ways of looking at this:

*

*Often called "repackaging" - this is when the video (for example) has been encoded correctly (let's say h264, with a bunch of parameters), but you want it in a different file-type - maybe it's an .AVI and you wanted it in an .MP4. This doesn't involve changing the actual video - just re-wraping the h264 stream in a new "wrapper", and is thus a fast operation.

*Re-encoding. Let's say your audio was in a MP3 format, and you wanted it in an AAC format. This would require decoding the entire MP3 stream, and re-encoding it into AAC.
Obviously you can also do "1" and "2" together.
Refer Formats and Codecs   for detailed information.
Hope it helps!


text:
Q: is it right to use "the" before " variety" as bellow? and why? It is undeniable that only by visiting isolated natural places do people comprehend more deeply about how the variety of strange creatures survive and grow in the scope of their own environments.

A: It is proposed that only by visiting isolated natural places do people comprehend more deeply the variety of strange creatures that survive and grow within the scope of an environment.

A: It sounds like you're talking about various different types of environments, or an unspecified number of environments, each of which has its own set of strange creatures, so you should say "a variety of strange creatures".
The reason you should avoid using "the" in this case is because you're not referring to "variety" as a particular thing, but only as a generic modifier of the word "creatures". For example, you would say "I like the variety of animals in this zoo" but "There is a variety of animals in this zoo." In the first case, you are focusing specifically on the variety, whereas in the second case, you're focusing on the animals.
Here are your two options:
"how a variety of strange creatures survive and grow in their own environments": the creatures are the subject, and they're not a specific entity, thus "a variety".
"how the variety of strange creatures survives and grows in its own environment": the variety is the subject, and it's a specific variety in a specific environment, thus "the variety".
Also FYI, you don't need to use "about" with the verb "comprehend". So your sentence should say "people comprehend more deeply how ..."


text:
Q: setting asp:CheckBox as checked in code behind in asp:FormView I don't know if this is even possible, but I am trying to set a asp:CheckBox, in a FormView, to Checked=True if a value in a database = yes|no|pending etc...
here is the code behind (in a PreRender Sub):
    Dim rowHiredStatus As DataRowView = CType(fvRecruitInterviewed.DataItem, DataRowView)

    Dim lblTestHiredStatus As Label = CType(fvRecruitInterviewed.FindControl("lblTestHiredStatus"), Label)

    Dim chkHiredPending As CheckBox = CType(fvRecruitInterviewed.FindControl("chkHiredPending"), CheckBox)
    Dim chkHiredNo As CheckBox = CType(fvRecruitInterviewed.FindControl("chkHiredNo"), CheckBox)
    Dim chkHiredYes As CheckBox = CType(fvRecruitInterviewed.FindControl("chkHiredYes"), CheckBox)

    If Not IsNothing(rowHiredStatus) Then

        Dim strHiredStatus As String
        strHiredStatus = rowHiredStatus("HiredStatus").ToString()
        lblTestHiredStatus.Text = strHiredStatus

        If strHiredStatus = "yes" Then
            chkHiredYes.Checked = True
            lblTestHiredStatus.Text = strHiredStatus
        ElseIf (strHiredStatus = "no") Then
            chkHiredNo.Checked = True
            lblTestHiredStatus.Text = strHiredStatus
        Else
            chkHiredPending.Checked = True
            lblTestHiredStatus.Text = strHiredStatus
        End If

    End If

and in design view:
    <asp:CheckBox ID="chkHiredPending" runat="server" Text="Pending" />

    <asp:CheckBox ID="chkHiredNo" runat="server" Text="Not Hired"/>

    <asp:CheckBox ID="chkHiredYes" runat="server" Text="Hired" />

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

the frustrating thing is that the test label displays the correct data, but the checkbox will not change.  It just defaults to the pending checkbox.
Using a RadioButton group orRadioButtonList would be fine, if that is easier/possible

A: Based on the description of the problem and the code, I am willing to go out on a limb and say the problem is the value of strHiredStatus.
Since Pending is getting checked, we know that the code is getting fired and in the code, pending is the default clause in the If statement, which means that the issue must be with the test of strHiredStatus.
When you test a string with equals, it is a case-sensitive test. This means that "Yes" is not the same as "yes".
There are different ways to solve this problem, but my preferred way is to use the String.Equals method with case and culture insensitivity:
If strHiredStatus.Equals("yes", StringComparison.InvariantCultureIgnoreCase) Then
    chkHiredYes.Checked = True
    lblTestHiredStatus.Text = strHiredStatus
ElseIf strHiredStatus.Equals("no", StringComparison.InvariantCultureIgnoreCase) Then

The reason for the culture insensitivity (which I have been burned by previously), is that if you have a string constant and just convert the constant string to lower case, you will get unexpected results when running internationally.
For example, when running in a Turkish environment, an upper case I will not be converted to an English lower-case i, it will be converted to a Turkish i (not sure what the correct name for the character is, but is a different character).

A: I found an question/answer on the ASP.Net forums that helped me answer my question:
Binding CheckBoxList in FormView
and I implemented it like so:
//Design View
<asp:CheckBoxList ID="cblHiredStatus" runat="server" DataTextField="hiredstatus" DataValueField="hiredstatus">
    <asp:ListItem Value="pending">Pending</asp:ListItem>
    <asp:ListItem Value="no">Not Hired</asp:ListItem>
    <asp:ListItem Value="yes">Hired</asp:ListItem>
</asp:CheckBoxList>

//Code Behind
 Dim cblHiredStatus As CheckBoxList = CType(fvRecruitInterviewed.FindControl("cblHiredStatus"), CheckBoxList)

 If cblHiredStatus IsNot Nothing Then
      Dim csv As String = DataBinder.Eval(fvRecruitInterviewed.DataItem, "HiredStatus").ToString()
      If Not String.IsNullOrEmpty(csv) Then
           Dim hiredstatus As String() = csv.Split()
           For Each str As String In hiredstatus
                If cblHiredStatus.Items.FindByValue(str) IsNot Nothing Then
                     cblHiredStatus.Items.FindByValue(str).Selected = True
                End If
           Next
      End If
 End If


text: Q: libtiff 4.0.10 is blocked by the antivirus that i cannot disable on my company laptop I have installed miniconda and trying to install dask. This installs libtiff 4.0.10 and this is blocked by my antivirus. I cannot disable my antivirus. What can be a possible workaround.


text:
Q: What are the reasons an HttpWebRequest might take half a minute to get a response? I'm developing an app for a school project which uses data from CoinGecko's free public API. The way I'm getting the data is with the HttpWebRequest class. At first, I was able to use the API fast, without any problems, but recently the requests have been getting stuck at the GetResponse() function for a long time. Even pinging the API takes about 30 seconds to complete. I've read a lot of posts regarding this problem, and none of the suggestions worked.
try
{
    string uri = "https://api.coingecko.com/api/v3/ping";

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

    request.Method = "GET";
    request.Accept =
        "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng," +
        "*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
    request.ContentType = "application/json";
    request.Headers.Add("accept-encoding", "gzip, deflate, br");
    request.Headers.Add("accept-language", "en-US,en;q=0.9");

    request.Headers.Add("cache-control", "max-age=0");
    request.Headers.Add("if-none-match", "W/\"c1f074e1bdf979ac5dc291f2c0acf9e4\"");

    request.Headers.Add("sec-ch-ua", "\" Not A;Brand\"; v = \"99\", \"Chromium\"; v = \"96\", \"Google Chrome\"; v = \"96\"");
    request.Headers.Add("sec-ch-ua-mobile", "?0");
    request.Headers.Add("sec-ch-ua-platform", "\"Windows\"");
    request.Headers.Add("sec-fetch-dest", "document");
    request.Headers.Add("sec-fetch-mode", "navigate");
    request.Headers.Add("sec-fetch-site", "none");
    request.Headers.Add("sec-fetch-user", "?1");
    request.Headers.Add("upgrade-insecure-requests", "1");
    request.UserAgent =
       "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)" +
       " Chrome/97.0.4692.71 Safari/537.36 Edg/97.0.1072.55";
    request.Proxy = null;

    using HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
    {
        throw new ApplicationException("REST client error code: "
            + response.StatusCode.ToString());
    }

    using Stream stream = response.GetResponseStream();
    if (stream == null)
    {
        throw new ApplicationException("Error: Null response");
    }

    using StreamReader reader = new StreamReader(stream);
    return reader.ReadToEnd();
}
catch (Exception ex)
{
    return ex.ToString();
}

It works with the browser so I copied all the browser request headers and added them to the code but they didn't help. I have also tried: Increasing the number of connections, playing around with all the security protocol types, disabling my firewall. Could it be that the API is detecting and slowing down my requests since they're not "human"?

A: Set Windows to prioritise IPv4 by typing the following in the command line:
netsh interface ipv6 set prefixpolicy ::ffff:0:0/96 46 4

Source


text:
Q: Proving expressions mod 13 Bob thinks of integer pairs $(a,b)$ such that $a^2+b^2\equiv 0\pmod {13}$
He notices that, curiously, for every pair, at least one of $2a+3b$ or $3b+2a$ is divisible by $13$.
I did a similar problem to prove that $13|2a+3b\iff 13|3a-2b$ using a special algebra trick.
I cannot find a trick here though to manipulate the expressions.
I can solve it by looking at all possible values of $a^2\pmod {13}$ and then verifying that these work.
But I want to know if there is a more elegant solution using an algebra trick.

A: Hint: If $a\equiv 0\pmod{13}$ then $b\equiv 0\bmod 13$ as well. Now, assume this is not the case. Then
$$a^2+b^2\equiv 0\bmod 13 \implies \left(\frac{a}{b}\right)^2+1\equiv 0\bmod 13.$$
See that the square roots of $-1\bmod 13$ are $5$ and $8$, or, if you prefer, $-2/3$ and $-3/2$...
Can you finish from here?

A: From $13|2a+3b\iff 13|3a-2b$, we can write
\begin{align*}
(3a-2b)(3a+2b) = 9a^2 - 4b^2 = -4(a^2+b^2) \mod 13 = 0 \mod 13
\end{align*}
Hence either $3a-2b$ or $3a+2b$ is a multiple of 13. It follows that either $2a+3b$ or $3a+2b$ is a multiple of 13.


text:
Q: Bloodskal Barrow won't appear I am on the dawnguard quest 'rings of blood magic' i have obtained the ring that quadriples khajit claw attacks and gives +100 health, but Bloodskal Barrow won't appear on my map, i have tried repeatedly activating and deactivating the quest but there is still no marker.

A: Bloodskal Barrow is on Soltsheim (Dragonborn DLC). You'll have to travel there to see a quest marker.


text:
Q: Automapper ProjectTo not working with ForPath Members I'm trying to implement a more elegant call in my repository by using .ProjectTo<> in Automapper instead of getting an IEnumerable and then mapping those results to the Dto. When I switched to this method my mapping no longer works for anything mapped using .ForPath().
Mapping:
//Context.Account -> Account
configuration.CreateMap<Context.Account, Account>()
    .ForPath(dest => dest.BillingAddress, opt => opt.MapFrom(source => new Address(source.BillingStreet, source.BillingCity, source.BillingState, source.BillingPostalCode, source.BillingCountry)))
    .ForPath(dest => dest.ShippingAddress, opt => opt.MapFrom(source => new Address(source.ShippingStreet, source.ShippingCity, source.ShippingState, source.ShippingPostalCode, source.ShippingCountry)))
    .ForMember(dest => dest.Events, opt => opt.Ignore())
    .ReverseMap()
    .ForMember(dest => dest.BillingStreet, opt => opt.MapFrom(source => source.BillingAddress.Street))
    .ForMember(dest => dest.BillingCity, opt => opt.MapFrom(source => source.BillingAddress.City))
    .ForMember(dest => dest.BillingState, opt => opt.MapFrom(source => source.BillingAddress.State))
    .ForMember(dest => dest.BillingPostalCode, opt => opt.MapFrom(source => source.BillingAddress.PostalCode))
    .ForMember(dest => dest.BillingCountry, opt => opt.MapFrom(source => source.BillingAddress.Country))
    .ForMember(dest => dest.ShippingStreet, opt => opt.MapFrom(source => source.ShippingAddress.Street))
    .ForMember(dest => dest.ShippingCity, opt => opt.MapFrom(source => source.ShippingAddress.City))
    .ForMember(dest => dest.ShippingState, opt => opt.MapFrom(source => source.ShippingAddress.State))
    .ForMember(dest => dest.ShippingPostalCode, opt => opt.MapFrom(source => source.ShippingAddress.PostalCode))
    .ForMember(dest => dest.ShippingCountry, opt => opt.MapFrom(source => source.ShippingAddress.Country));

Here is the code in my repository:
BEFORE (Address being populated):
List<Account> accounts;

IQueryable<Context.Account> iqueryable = _dbContext.Set<Context.Account>();

if (spec != null)
{
    var filter = Mapper.Map<Expression<Func<Context.Account, bool>>>(spec.FilterCriteria);
    iqueryable = iqueryable.Where(filter);

    if (spec is Paging<Account> paging)
    {
        var orderByExpression = Mapper.Map<Expression<Func<Context.Account, object>>>(paging.OrderBy);
        iqueryable = iqueryable.OrderBy(orderByExpression).Take(paging.Take).Skip(paging.Skip);
    }
}

accounts = iqueryable
   .ToList()
   .Select(x => Mapper.Map<Account>(x))
   .ToList();

return accounts;

AFTER (Address not being populated):
IQueryable<Account> iqueryable = _dbContext.Set<Context.Account>()
                .ProjectTo<Account>();

if (spec != null)
{
   if (spec is Paging<Account> paging)
   {
      iqueryable = paging.Prepare(iqueryable);
   }
   else
   {
      iqueryable = iqueryable.Where(spec.FilterCriteria);
   }
}
return iqueryable.ToList();


text:
Q: Selecting column based on greater values between two other columns I have table where I store results from soccer games.
I store each team score as well as it's id, and I want to get the id of the winning teams.
Here is the table
team1_id   team2_id   team1_score   team2_score
    1          2          1             0
    1          3          0             1
    3          4          1             0

And here is what I want as result
1
3

(teams 1 and 3 won at least one game)

A: Try this:
SELECT DISTINCT IF(team1_score > team2_score, team1_id, team2_id) AS winner
FROM mytable

Demo here


text:
Q: Why is there such low current produced when discharging a Van de Graaff Generator, even though voltage is very high? E.g. putting your finger close to the Generator and seeing a spark between it and your finger. Obviously this does not kill you, but why is there such low current produced when the potential difference is so great?

A: The statement "Obviously this does not kill you" is not true in all cases and certainly not true for larger Van de Graaff machines.
The charge on a VdG is stored on the dome whose capacitance is approximately given by $C = 4 \pi \epsilon_o R$ where $R$ is the radius of the dome which for a dome of radius 20 cm is approximately 20 pF.
The charge stored is $Q= CV$ where $Q$ is the charge on the dome and $V$ the potential difference between the dome and earth so for a potential difference of 100 kV this represents a charge of 2 $\mu$C. The charge transferred by a current of 2 $\mu$A in one second.
Increasing the voltage brings problems of leakage of charge down the supports which hold up the dome and the air around the dome where there will be corona discharge.  You can often hear this above the noise of the motor driving the belt. Large VdG machines are usually housed in a vessel which contains gas under high pressure to reduce corona discharge or even spark loss.  You will also have noted that high voltage devices tend not to have any sharp edges.
Then you have the belt having a limited capacity as to the amount of charge it can transfer from the bottom of the VdG machine to the top. It also will suffer leakage.  You may have noticed that on a small VdG the motor slows down as the charge (and hence potential difference) builds up because the motor has to do more work lifting the charges against a potential gradient.

A: Current and voltage are different things. Any source of voltage be it a battery, solar cell, wall-wart power supply, your wall outlet, some overhead transmission lines or lightening has a limit on how much current it can supply.This is obvious when you think about it, if there was no limit you could do spot welding of heavy steel plates with a few AAA cells. Why is there a limit ? Because the number of electrons stored (or available) in the power source has a finite limit based upon how many have been "stuffed" in there AND the current is also limited by the resistance of the circuit.
In the case of the Vann De Graaff we are stuffing electrons up into the top dome as we wind the handle. It is really a capacitor you are charging up and the more electrons on the top plate the higher the voltage. The capacitance is low though (maybe a few pF ?) so there is a low (relative, still millions) limit to how many electrons are up there before the voltage breaks down.
Wind the V de G up to the max, just before breakdown, and you have it fully charged and can make a nice spark, it will last for a tiny tiny fraction of a second and the current will be low because there are just not enough electrons flowing to make it higher because there are not enough electrons there in the first place.Current is a measure of flow rate of electrons.
If you could find, or make, a more substantial capacitor with a voltage rating higher than the V de G you could (if your arm doesn't tire) charge that too and get a higher current when it is discharged. From this we can see that the higher the voltage on a capacitor and the higher the capacitance the more dangerous it might be if you discharge it through a low resistance (or yourself). People have been killed & injured from capacitor discharges on so called "dead" i.e. disconnected/isolated electrical equipment.
W=1/2 CV^2 Try googling some more capacitor equations to understand the relationships between Capacitance, Voltage, Energy Stored, Discharge Times, Etc.

A: Ohm's Law sets the intensity of current (I) directly proportional to potential difference (V) and indirectly proportional to resistance (R).  Current is expressed in amperes, potential difference in volts, and resistance in ohms:
I = V / R
Current will be higher as resistance is lower.  While Van de Graaf generators can produce a large potential difference (high voltage), they do this in an environment of high resistance, which is necessary to allow charge to accumulate in the generator.
Smaller Van de Graaf generators with limited storage capacity generally discharge before accumulating a potential difference great enough to kill you.  Just as static electricity builds up in your clothing as you shuffle across a carpet and discharges with an impressive spark when a sharp edge of your body comes near a ground, but doesn't seriously injure you, a small Van de Graaf generator doesn't have great enough storage capacity to do more than produce an impressive spark.
Also, as Farcher points out in his answer, power demand of the moving belt mechanism used in small Van de Graaf generators to deposit charge in the storage dome, becomes greater as charge accumulates, which limits the ability of the mechanism to deposit charge in the dome.  Van de Graaf generators are dependent on high R to operate, and run into diminishing returns when building up high V.  So it's difficult to raise V/R to achieve a high current relative to the power consumption of the mechanism.


text:
Q: Animated circle with easings on canvas based on dropdown list So I have this fiddle made, and the objective is to point-out areas of the human body by selecting their respective areas in a dropdown list.
This is, currently, what I've made:

let coords = {
    maleFirst: {
        hands: {
            left: {
                x: 100,
                y: 360
            },
            right: {
                x: 280,
                y: 360
            }
        },
        foot: {
            left: {
                x: 180,
                y: 590
            },
            right:{
                x: 210,
                y: 590
            }
        }
    },
    maleSecond: {
        hands: {
            left: {
                x: 365,
                y: 360
            },
            right: {
                x: 545,
                y: 360
            }
        },
        foot: {
            left: {
                x: 430,
                y: 590
            },
            right:{
                x: 480,
                y: 590
            }
        }
    }
}

let draw = (option) => {
    let canvas = document.getElementById('canvas');

    if (canvas.getContext) {
        let ctx = canvas.getContext('2d');

      ctx.clearRect(0, 0, canvas.width, canvas.height);

      if (option === 'hands') {

        coordsDraw(ctx, coords.maleFirst.hands.left.x, coords.maleFirst.hands.left.y);
        coordsDraw(ctx, coords.maleFirst.hands.right.x, coords.maleFirst.hands.right.y);
        coordsDraw(ctx, coords.maleSecond.hands.left.x, coords.maleSecond.hands.left.y);
        coordsDraw(ctx, coords.maleSecond.hands.right.x, coords.maleSecond.hands.right.y);

      }

      if (option === 'foot') {
        coordsDraw(ctx, coords.maleFirst.foot.left.x, coords.maleFirst.foot.left.y);
        coordsDraw(ctx, coords.maleFirst.foot.right.x, coords.maleFirst.foot.right.y);
        coordsDraw(ctx, coords.maleSecond.foot.left.x, coords.maleSecond.foot.left.y);
        coordsDraw(ctx, coords.maleSecond.foot.right.x, coords.maleSecond.foot.right.y);
      }

    }
}

let coordsDraw = (ctx, x, y) => {

    ctx.beginPath();
    ctx.fillStyle = '#01567f'; // color of fill

    ctx.arc(x, y, 5, 0, 2 * Math.PI);
    ctx.fill();
    ctx.closePath();
}

document.getElementById('options').addEventListener('change', function ()  {
  draw(this.value)

});

#canvas {
   background-image:url('http://www.coloringsky.com/wp-content/uploads/2015/11/How-to-Draw-Human-Body-Coloring-Pages.jpg');
   background-repeat:no-repeat;
   background-size:contain;
   background-position:center;
   width: 100%;
}
<select name="options" id="options">
  <option value="#">Select option</option>
  <option value="hands">hands</option>
  <option value="foot">foot</option>
</select>

<canvas id="canvas" width="650" height="650"></canvas>

The idea that I'm aiming for is to have a more "stand-out" pointer, something among these lines:

// canvas related variables
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();

// set the context styles
ctx.lineWidth = 1;
ctx.strokeStyle = "gold";
ctx.fillStyle = "#888";

// variables used to draw & animate the ring
var PI2 = Math.PI * 2;
var ringX, ringY, ringRadius, ingCounter, ringCounterVelocity;
var cancelAnimationId;

// fill the canvas with a background color
ctx.fillRect(0, 0, canvas.width, canvas.height);

// tell handleMouseDown to handle all mousedown events
$("#canvas").mousedown(function (e) {
    handleMouseDown(e);
});

// set the ring variables and start the animation
function ring(x, y) {
    ringX = x;
    ringY = y;
    ringRadius = 0;
    ringCounter = 0;
    ringCounterVelocity = 4;

    cancelAnimationId = requestAnimationFrame(animate);
}

// the animation loop
function animate() {

    // return if the animation is complete
    if (ringCounter > 200) {
        ringCounter = 0;
    }

    // otherwise request another animation loop
    cancelAnimationId = requestAnimationFrame(animate);

    // ringCounter<100 means the ring is expanding
    // ringCounter>=100 means the ring is shrinking
    if (ringCounter < 100) {
        // expand the ring using easeInCubic easing
        ringRadius = easeInCubic(ringCounter, 0, 15, 100);
    } else {
        // shrink the ring using easeOutCubic easing
        ringRadius = easeOutCubic(ringCounter - 100, 15, -15, 100);
    }

    // draw the ring at the radius set using the easing functions
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.arc(ringX, ringY, ringRadius, 0, PI2);
    ctx.closePath();
    ctx.stroke();

    // increment the ringCounter for the next loop
    ringCounter += ringCounterVelocity;
}

//  Robert Penner's easing functions
//
//  https://github.com/danro/jquery-easing/blob/master/jquery.easing.js
//
//  now=elapsed time,
//  startValue=value at start of easing,
//  deltaValue=amount the value will change during the easing,
//  duration=total time for easing

function easeInCubic(now, startValue, deltaValue, duration) {
    return deltaValue * (now /= duration) * now * now + startValue;
}

function easeOutCubic(now, startValue, deltaValue, duration) {
    return deltaValue * ((now = now / duration - 1) * now * now + 1) + startValue;
}

// handle mousedown events
function handleMouseDown(e) {

    // tell the browser we'll handle this event
    e.preventDefault();
    e.stopPropagation();

    // calc the mouse position
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);

    // animate a ring at the mouse position
    cancelAnimationFrame(cancelAnimationId);
    ring(mouseX, mouseY);

}
#canvas{border:1px solid red;}

Click in the canvas to draw animated circle with easings.

<canvas id="canvas" width=300 height=300></canvas>

I'm having trouble in adapting the animation to what I'm looking for, as I end up having errors like these:

let coords = {
    maleFirst: {
        hands: {
            left: {
                x: 100,
                y: 360
            },
            right: {
                x: 280,
                y: 360
            }
        },
        foot: {
            left: {
                x: 180,
                y: 590
            },
            right:{
                x: 210,
                y: 590
            }
        }
    },
    maleSecond: {
        hands: {
            left: {
                x: 365,
                y: 360
            },
            right: {
                x: 545,
                y: 360
            }
        },
        foot: {
            left: {
                x: 430,
                y: 590
            },
            right:{
                x: 480,
                y: 590
            }
        }
    }
}

let draw = (option) => {
    let canvas = document.getElementById('canvas');

    if (canvas.getContext) {
        let ctx = canvas.getContext('2d');

      ctx.clearRect(0, 0, canvas.width, canvas.height);

      if (option === 'hands') {

        coordsDraw(ctx, coords.maleFirst.hands.left.x, coords.maleFirst.hands.left.y);
        coordsDraw(ctx, coords.maleFirst.hands.right.x, coords.maleFirst.hands.right.y);
        coordsDraw(ctx, coords.maleSecond.hands.left.x, coords.maleSecond.hands.left.y);
        coordsDraw(ctx, coords.maleSecond.hands.right.x, coords.maleSecond.hands.right.y);

      }

      if (option === 'foot') {
        coordsDraw(ctx, coords.maleFirst.foot.left.x, coords.maleFirst.foot.left.y);
        coordsDraw(ctx, coords.maleFirst.foot.right.x, coords.maleFirst.foot.right.y);
        coordsDraw(ctx, coords.maleSecond.foot.left.x, coords.maleSecond.foot.left.y);
        coordsDraw(ctx, coords.maleSecond.foot.right.x, coords.maleSecond.foot.right.y);
      }

    }
}

var ringRadius = 0, ringCounter = 0, ringCounterVelocity = 4;
let coordsDraw = (ctx, x, y) => {

    if (ringCounter > 200) {
        ringCounter = 0;
    }

    // otherwise request another animation loop
    cancelAnimationId = requestAnimationFrame(coordsDraw(ctx, x, y));

    // ringCounter<100 means the ring is expanding
    // ringCounter>=100 means the ring is shrinking
    if (ringCounter < 100) {
        // expand the ring using easeInCubic easing
        ringRadius = easeInCubic(ringCounter, 0, 15, 100);
    } else {
        // shrink the ring using easeOutCubic easing
        ringRadius = easeOutCubic(ringCounter - 100, 15, -15, 100);
    }

    ctx.beginPath();
    ctx.fillStyle = '#01567f'; // color of fill

    ctx.arc(x, y, ringRadius, 0, 2 * Math.PI);
    ctx.fill();
    ctx.closePath();

    ringCounter += ringCounterVelocity;
}

function easeInCubic(now, startValue, deltaValue, duration) {
    return deltaValue * (now /= duration) * now * now + startValue;
}

function easeOutCubic(now, startValue, deltaValue, duration) {
    return deltaValue * ((now = now / duration - 1) * now * now + 1) + startValue;
}

document.getElementById('options').addEventListener('change', function ()  {
  draw(this.value)

});

#canvas {
   background-image:url('http://www.coloringsky.com/wp-content/uploads/2015/11/How-to-Draw-Human-Body-Coloring-Pages.jpg');
   background-repeat:no-repeat;
   background-size:contain;
   background-position:center;
   width: 100%;
}
<select name="options" id="options">
  <option value="#">Select option</option>
  <option value="hands">hands</option>
  <option value="foot">foot</option>
</select>

<canvas id="canvas" width="650" height="650"></canvas>

Uncaught RangeError: Maximum call stack size exceeded
    at coordsDraw (select.js:299)

Any help would be trully appreciated

A: I would do it something like this (this example doesn't have animated rings but I show where you would place that code.
<!doctype html>

<select name="options" id="options">
    <option value="#">Select option</option>
    <option value="hands">hands</option>
    <option value="feet">feet</option>
</select>

<canvas width="650" height="650">

UPDATE
Now with animated rings"
<!doctype html>

<select name="options" id="options">
    <option value="#">Select option</option>
    <option value="hands">hands</option>
    <option value="feet">feet</option>
</select>

<canvas width="650" height="650">

<!doctype html>

 <meta charset = 'utf-8'>

 <select name="options" id="options">
  <option value="#">Select option</option>
  <option value="hands">hands</option>
  <option value="feet">feet</option>
 </select>

 <canvas width="650" height="650">


text:
Q: Помогите переделать jQuery скрипт на vue js + js? Мне надо сделать чтобы textarea автоматически увеличивал высоту в зависимости от кол-ва символов.
У меня есть такой скрипт на jquery
 $('textarea[data-auto-resize-height]').each(function () {
this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
})

$(document).on('input', 'textarea[data-auto-resize-height]', function () {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
});

Мне надо переделать это на vue js с помощью ref
Мне подсказали что надо в mounted() задать this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;'); а в methods:
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';

Но я никак не могу это до кучи собрать. Помогите плз. Ещей и на ecmascript 6 надо

A: Что-то типа такого:
<div id="app">
  <textarea @input="handler">
  </textarea>
</div>

new Vue({
  el: '#app',
  methods: {
    handler(e) {
        e.target.style.height = "5px";
        e.target.style.height = e.target.scrollHeight + 'px';
    }
  }
})

textarea {
  height: auto;
  padding: 10px;
  font-size: 12px;
  resize: none;
  overflow: hidden;
}


text:
Q: How to update Microsoft Access database to Visual Basic dataset after adding new items I've just started making my first program that uses a database with Visual Basic and I've come across a small glitch with my code. This program takes names of people and a few other fields of information and puts them onto a database file called AddressBook.mdb. I have a few buttons that do various things including moving between each record and updating changes to the current record. My issue though is with adding a new entry.
The button itself works when I use it, the only issue is that after saving I cannot view the new entry in the application until I've restarted it.
Here is the code for the commit button that saves the current data as a new entry:
Private Sub btnCommit_Click(sender As Object, e As EventArgs) Handles btnCommit.Click
    If inc <> -1 Then

        Dim cb As New OleDb.OleDbCommandBuilder(da)
        Dim dsNewRow As DataRow

        dsNewRow = ds.Tables("AddressBook").NewRow()

        dsNewRow.Item("FirstName") = txtFirstName.Text
        dsNewRow.Item("Surname") = txtSurname.Text
        dsNewRow.Item("SSN") = ssn.Text
        dsNewRow.Item("DOB") = dob.Text
        dsNewRow.Item("Weight") = weight.Text
        dsNewRow.Item("Height") = tall.Text
        dsNewRow.Item("Phone") = phone.Text
        dsNewRow.Item("Address1") = address.Text
        dsNewRow.Item("City") = city.Text
        dsNewRow.Item("Postcode") = zip.Text
        dsNewRow.Item("Hair") = hair.Text
        dsNewRow.Item("Eye") = eye.Text
        dsNewRow.Item("Gender") = gender.Text

        ds.Tables("AddressBook").Rows.Add(dsNewRow)

        da.Update(ds, "AddressBook")

        MsgBox("New Record added to the Database")

        btnCommit.Enabled = False
        btnAddNew.Enabled = True
        btnUpdate.Enabled = True
        btnDelete.Enabled = True

    End If
End Sub

Is there something I can do to update the dataset after the button is clicked so that I might view the new entry right after making it?

A: If i remember, there is a Refresh method available.
Worst case scenario, do a manual refresh by destroying the object and recreating.
I think its personally just easier to just recreate the object, cause refreshing (manually or automated) requires you to compare values and do an update on the DataSet.
Based on your notation, it looks like this is a desktop app, so refreshing with a new DataSet will have very little effect on the application.


text:
Q: Drawing sin(x) graph in java I am currently trying to draw the graph of sin(x) in java. I am required by the instructions of my assignment to only use drawLine() as the method of drawing the graph. I can't seem to figure out how to properly set my y value though. Right now what I have is a while loop used in order to draw the line pixel by pixel, but cannot manage to get the y value to be correct. Here is what I have so far.
public class GraphJComponent extends JComponent {
public void paintComponent (Graphics g){
    Color axis = new Color(128, 128, 128);
    g.setColor(axis);

    int xShift = getWidth() / 50;
    int xShift2 = getWidth() / 100;
    int yShift = getHeight() / 10;
    int yShift2 = getHeight() / 17;

    g.drawLine(xShift,yShift,xShift,getHeight() - yShift);
    g.drawLine(xShift, getHeight() / 2, getWidth() - xShift, getHeight() / 2);

    g.drawString("0", xShift + xShift2, getHeight() / 2 + yShift2);
    g.drawString("1", xShift + xShift2, yShift - (yShift2 / 4));
    g.drawString("-1", xShift + xShift2, getHeight() - yShift + yShift2);
    g.drawString("\u03c0", getWidth() / 2, getHeight() / 2 + yShift2);
    g.drawString("2" + "\u03c0", getWidth() - (2 * xShift), getHeight() / 2 + yShift2);

    Color line = new Color (255, 0, 0);
    g.setColor(line);

    int x1 = xShift;
    int y1 = getHeight() / 2;
    int x2 = xShift;
    int y2;
    int yScale = getHeight() / 2;
    int sinInput = 0;

    while (sinInput <= 360){
        x2 += (getWidth() / 360);

        y2 = (yScale - ((int)(Math.sin(sinInput) * yScale)));

        sinInput += 1;
        g.drawLine(x1, y1, x2, y2);

        x1 = x2;
        y1 = y2;

    }

}

}
Yes I know there are numerous things that I could tidy up or simplify, this is just a rough draft, per-se, that I will clean up once I have everything working.
I have tried multiple methods of getting the y value to properly be set, the closest I got ended up drawing a straight diagonal lines, it wasn't curved like it was supposed to be. What can I do to properly set the y value so that the sin graph from [0, 2pi] will be properly drawn?
To try to clarify the issue:
The problem lies in changing the y value of my drawLine function. Basically, what I had working wouldn't draw the sin function properly because I only could figure out to lineraly increment it. It looked something like this:
 /\
/  \  /
    \/

The ultimate question I have is: How can I make it so my y coordinate will scale with the proper y coordinate of the sin(x) graph? In other words, how can I make it "not-straight" and properly curved like the sin(x) graph should.
Thank you for your time I appreciate any help.
The latest thing I've been playing with is something that's sort of like this: The value of the y coordinate is calculated by scaling the value of the sin of the degree and manipulating it with certain factors to get the right pixel coordinate. I think this is the proper way to do it, any thoughts?
At the bottom of this page you can see what the end result should look like:
http://nameless.cis.udel.edu/class_wiki/index.php/CISC181_S2015_Lab3

A: Try y= Math.sin(x)*100;
And take a scale of
1 =100 divisions
That way you can take on the decimals.

A: Like immibis pointed out, Math.sin takes an angle in radians. Just convert your degrees to radians while passing it to Math.sin, that should solve your problem.
Math.sin((sinInput * 2 * Math.PI) / 360)


text:
Q: Geometric Series in Polar Form I'm stuck on a complex number problem relating to the geometric series in polar form. By considering that:
$$1+\operatorname{cis}{\theta}+\operatorname{cis}{2\theta}+\operatorname{cis}{3\theta}+....+\operatorname{cis}{n\theta}$$
as a geometric series, find:
$$\sum_{r=0}^n \operatorname{cos}{r\theta}$$
I was thinking along the lines of finding the sum of the polar form series, and that I was assuming that the sum of the series would be:
$$\operatorname{cis}{\frac{n(n+1)}{2}}{\theta}$$
Thus, if that is the answer then finding the sum of $\operatorname{cos}{r\theta}$ becomes very easy. But I doubt that that is the answer, so any help would be much appreciated!!


text:
Q: Best approach for collision detection with HTML5 and JavaScript? I'm trying to make a little platform game with pure HTML5 and JavaScript. No frameworks.
So in order to make my character jump on top of enemies and floors/walls etc., it needs some proper collision detection algorithms.
Since I'm not usually into doing this. I really have no clue on how to approach the problem.
Should I do a re-check in every frame (it runs in 30 FPS) for all obstacles in the Canvas and see if it collides with my player, or is there a better and faster way to do so?
I even thought of making dynamic maps. So the width, height, x- and y coordinates of the obstacle are stored in an object. Would that make it faster to check if it's colliding with the player?

A: 1. Should I re-check in every frame (it runs on 30 FPS)?
Who says it runs in 30 FPS? I found no such thing in the HTML5 specification. Closest you'll get to have anything to say about the framerate at all is to programmatically call setInterval or the newish, more preferred, requestAnimationFrame function.
However, back to the story. You should always look for collisions as much as you can. Usually, writing games on other platforms where one have a greater ability to measure CPU load, this could be one of those things you might find favorable to scale back some if the CPU has a hard time to follow suit. In JavaScript though, you're out of luck trying to implement advanced solutions like this one.
I don't think there's a shortcut here. The computer has no way of knowing what collided, how, when- and where, if you don't make that computation yourself. And yes, this is usually, if not at all times even, done just before each new frame is painted.
2. A dynamic map?
If by "map" you mean an array-like object or multidimensional array that maps coordinates to objects, then the short answer has to be no. But please do have an array of all objects on the scene. The width, height and coordinates of the object should be stored in variables in the object. Leaking these things would quickly become a burden; rendering the code complex and introduce bugs (please see separation of concerns and cohesion).
Do note that I just said "array of all objects on the scene" =) There is a subtle but most important point in this quote:
Whenever you walk through objects to determine their position and whether they have collided with someone or not. Also have a look at your viewport boundaries and determine whether the object are still "on the scene" or not. For instance, if you have a space craft simulator of some kind and a star just passed the player's viewport from one side to the other and then of the screen, and there is no way for the star to return and become visible again, then there is no reason for the star to be left behind in the system any more. He should be deleted and removed. He should definitely not be stored in an array and become part of a future collision detection with the player's avatar! Such things could dramatically slow down your game.
Bonus: Collision quick tips

*

*Divide the screen into parts. There is no reason for you to look for a collision between two objects if one of them are on left side of the screen, and the other one is on the right side. You could split up the screen into more logical units than just left and right too.

*Always strive to have a cheap computation made first. We kind of already did that in the last tip. But even if you now know that two objects just might be in collision with each other, draw two logical squares around your objects. For instance, say you have two 2D airplanes, then there is no reason for you to first look if some part of their wings collide. Draw a square around each airplane, effectively capturing their largest width and their largest height. If these two squares do not overlap, then just like in the last tip, you know they cannot be in collision with each other. But, if your first-phase cheap computation hinted that they might be in collision, pass those two airplanes to another more expensive computation to really look into the matter a bit more.

A: I am still working on something i wanted to make lots of divs and make them act on physics. I will share somethings that weren't obvious to me at first.

*

*Detect collisions in data first. I was reading the x and y of boxes on screen then checking against other divs. After a week it occurred to me how stupid this was. I mean first i would assign a new value to div, then read it from div. Accessing divs is expensive. Think dom as a rendering stage.

*Use webworkers if possible easy.

*Use canvas if possible.

*And if possible make elements carry a list of elements they should be checked against for collision.(this would be helpful in only certain cases).

I learned that interactive collisions are way more expensive. Because you have to check for changes in environment while in normal interaction you simulate what is going to happen in future, and therefore your animation would be more fluid and more cpu available.
i made something very very early stage just for fun: http://www.lastnoob.com/


text:
Q: How to create local network in virtualbox between Ubuntu server I created a Ubuntu server on virtualbox that Ubuntu server install with minimal virtual machine.
I created the three linked clone and I have internal network between them. I removed 70-persistent-net.rules.
I see this output when I run  ifconfig:
eth0 Link encap:Ethernet HWaddr 08:00:27:e6:72:8a
     inet6 addr:fe80::a00:27ff:fee6:728a/64 Scop:Link
     .
     .
     .

I cannot see IPv4 address. I need an IPv4 address. How do I get this?

A: In VirtualBox goto  >  in that check "Attached to" and select Bridged Adapter. It will work. like this.


text:
Q: hibernate - сохранение объекта, имеющего OneToMany Есть две таблицы А и Б.
У Б есть поле a_id внешний ключ на А
Класс А имеет список элементов Б.
Сохраняю А:
session.save(a);
В консоль выходит следующее:
insert to A
insert to B
insert to B
insert to B
....
update B....
update B....
update B....
update B....
.....

Не понимаю, почему происходят апдейты, смотрю что апдейтит... те же самые значения :(
Если список элементов Б большой, скажем N, то кол-во запросов при сохранении А: 1+N+N
Кто-нибудь знает в чем проблема?
Код:
класс А содержит:
@OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name="a_fk", nullable = false)
    private List<B> list;

класс Б содержит только
@Id
    @GeneratedValue
    @Column(name = "id")
private Integer id;

A: Ну а чего вы хотели то? Это же каскадные обновления: плата за лень. Вы определили foreign key как cascade, что означает что система будет сама обеспечивать целостность данных, а делает она это туповато.
Почитайте мануалы к SQL по-поводу каскадных обновлений/удалений и referential integrity.
P.S. Надеюсь, вы понимаете что Hibernate к этому отношения не имеет.


text:
Q: VS 2012 Open Design and Code on separate tab When I open HTML file on VS2012, I have the option to view code/split/design.
Is it possible to open design and code on the separate tab/window ? I want to have a better view of the design when I edit the code.
Thanks

A: Does split view not enough? Did you tried using it in vertical split mode?
Change the split view display setting to "vertical" explained here.


text:
Q: Outlook - Search for attatchments from a specific sender Continuation of this program Reference list index to enumerate value
This program will search a dictionary of senders against various criteria in outlook (msg.sender msg.subject msg.SenderEmailAddress etc), then download attachments from ALL senders matching the dictionary and criteria. This works fine and I've been using it for a while.
#Code before this allows me to select a date range to search

senderDict = {sender email : sender name}
listSender = list(senderDict.values())
listSender.insert(0, "Search Any")

########### Choose option from listSender
while True:
        try:
            senderNum = int(input("Choose a sender: "))
            senderChoice = listSender[senderNum] #refer senderNum to list index

            #Search all
            if senderNum == 0:
                    print("Searching for any sender")
                    break

            elif senderNum <= len(listSender) and senderNum > 0:
                    print("you chose", senderChoice)
                    break

            elif senderNum < 0:
                    print("Cannot choose a negative number.")
                    continue

############# CODE TO CHECK SENDER ATTACHMENTS
for msg in reversed(itcontents): #reversed() will go from most recent to oldest email based on date

########## Search for ANY sender
    if msg.Class == 43: #only search mail items (class 43)
            try:
                    if ( senderNum == 0 and
                            (str(msg.SenderEmailAddress) or str(msg.Subject) or str(msg.Sender) or str(msg.SentOnBehalfOfName)) in senderDict
                            and
                             #msg.SentOn date is not older than searchDate or newer than startDate
                            (msg.SentOn.date() >= searchDate and msg.SentOn.date() <= startDate.date())
                        ):
                            check += 1
                            print(check, "messages from", msg.SenderEmailAddress, "on", msg.SentOn.date()) #keep count of checked messages

                            #Check attachment file format string, invoices are usually PDFs.
                            #x refers to the attachment. Not every message from a listed sender has an attachment.
                            for x in msg.Attachments:
                                    if str(".pdf").casefold() in str(x): #casfold() checks possible upper or lower case combinations e.g PdF or pDf
                                            x.SaveAsFile(r"C:\Users\camerona\Desktop\Invoices from Outlook\\" + str(msg.SentOn.date()) + str(msg.SenderEmailAddress) + x.FileName)
                                            print("Saved attachment", x, "from", str(msg.Sender()), "on", str(msg.SentOn.date()))

It works fine up to here.
Now I am trying to add functionality to only save attachments from a SPECIFIC sender chosen from an enumerated list, created from the dictionary. The process as I understand it: I want to check if the chosen sender string matches the criteria and is in the dictionary.   I've tried using the same code for searching ANY.
########## Search for SPECIFIC sender
               elif ( str(senderChoice) in ( str(msg.SenderEmailAddress) or str(msg.Subject) or str(msg.Sender) or str(msg.SentOnBehalfOfName)) in senderDict
                        and
                        (msg.SentOn.date() >= searchDate and msg.SentOn.date() <= startDate.date())
                              ):
                                check += 1
                                print(check, "messages from", msg.SenderEmailAddress, "on", msg.SentOn.date()) #keep count of checked messages

                                #Check attachment file format, invoices are usually PDFs
                                #x refers to the attachment. Not every message from a listed sender has an attachment.
                                for x in msg.Attachments:
                                        if str(".pdf").casefold() in str(x): #casfold() cheks upper or lower case format
                                                x.SaveAsFile(r"C:\Users\camerona\Desktop\Invoices from Outlook\\" + str(msg.SentOn.date()) + str(msg.SenderEmailAddress) + x.FileName)
                                                print("Saved attachment", x, "from", str(msg.Sender()), "on", str(msg.SentOn.date()))

Output (redacted) looks like this for each attachment:
Choose a sender: 0
Searching for any sender
1 messages from xxxxxxx.com on 2019-12-16
Saved attachment Invoice INV-001172.pdf from xxxxxxxxx on 2019-12-16

Then choosing that sender specifically does nothing:
Choose a sender: 1
you chose xxxxxx
(attachment sumamry should appear like above)

I'm not sure why this isn't working. I feel like it must be something to do with the first line of the elif statement for str(senderChoice).

A: Try this in your second block instead mate:
########## Search for SPECIFIC sender
               elif ( senderNum != 0 and
                            (str(msg.SenderEmailAddress) or str(msg.Subject) or str(msg.Sender) or str(msg.SentOnBehalfOfName)) in senderDict
                            and
                             #msg.SentOn date is not older than searchDate or newer than startDate
                            (msg.SentOn.date() >= searchDate and msg.SentOn.date() <= startDate.date())
                            and
                             #NEW CODE TO CHECK IF THIS IS THE CHOSEN SPECIFIC USER
                            any([field for field in [str(msg.SenderEmailAddress), str(msg.Subject), str(msg.Sender), str(msg.SentOnBehalfOfName)] if str(senderChoice) in field])
                        ):
                                check += 1
                                print(check, "messages from", msg.SenderEmailAddress, "on", msg.SentOn.date()) #keep count of checked messages

                                #Check attachment file format, invoices are usually PDFs
                                #x refers to the attachment. Not every message from a listed sender has an attachment.
                                for x in msg.Attachments:
                                        if str(".pdf").casefold() in str(x): #casfold() cheks upper or lower case format
                                                x.SaveAsFile(r"C:\Users\camerona\Desktop\Invoices from Outlook\\" + str(msg.SentOn.date()) + str(msg.SenderEmailAddress) + x.FileName)
                                                print("Saved attachment", x, "from", str(msg.Sender()), "on", str(msg.SentOn.date()))


text:
Q: Parsing 3 parameters from view (update form) to controller laravel I have a simple code. Now I want to make update form and using 3 parameters. But it getting strange error.. Here's my code
view: moreDetails.blade.php
<form  method="POST" accept-charset="UTF-8" enctype="multipart/form-data" class="form-horizontal" action="{{ url('/moredetails/update', $new->proyek_id, $new->laporan_id, $new->id_fisik_rencana) }} " >
  <input type="hidden" name="_method" value="PUT">
  <input type="hidden" name="_token" value="{{ csrf_token() }}">

     Omzet Kontrak Awal Porsi Rencana

         <input type="text" class="span6 " value="{{ $new->omzet_kontrak_awal_porsi_rencana }}" name="omzet_kontrak_awal_porsi_rencana" />

 and many more........

      <button type="submit" class="btn btn-success">Update</button>
      <button type="button" class="btn">Cancel</button>

 </form>

controller: ProjectController.php
public function moredetails1(Request $request, $pr_id, $id_laporan, $id_fisik_rencana) {
  $project = FisikRencana::find($id_fisik_rencana);
  // dd($project);
  FisikRencana::find($laporan_id)->update($request->all());
}

and in my route
Route::put('/moredetails/update/{pr_id}/{id_laporan}/{id_fisik_rencana}','ProjectController@moredetails1');

When I clicked button "Update", screenshoot error like this
How can I solved it? Plase help me.
Thankyou!

A: You should pass an array of parameters:
{{ url('/moredetails/update', [$new->proyek_id, $new->laporan_id, $new->id_fisik_rencana]) }}

A: change your form tag like this :
<form  method="POST" accept-charset="UTF-8" enctype="multipart/form-data" class="form-horizontal" action="{{ url('/moredetails/update/'.$new->proyek_id.'/'. $new->laporan_id.'/'.$new->id_fisik_rencana) }} " >


text:
Q: Testing and mocking private/protected methods. Many posts but still cannot make one example work I have seen many posts and questions about "Mocking a private method" but still cannot make it work and not found a real answer.
Lets forget the code smell and you should not do it etc....
From what I understand I have done the following:
1) Created a class Library "MyMoqSamples"
2) Added a ref to Moq and NUnit
3) Edited the AssemblyInfo file and added
      [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
      [assembly: InternalsVisibleTo("MyMoqSamples")]
4) Now need to test a private method.Since it's a private method it's not part of an interface.
5) added the following code
[TestFixture]
public class Can_test_my_private_method
{
    [Test]
    public void Should_be_able_to_test_my_private_method()
    {
        // TODO how do I test my DoSomthing method?
    }
}

public class CustomerInfo
{
    public string Name { get; set; }
    public string Surname { get; set; }
}

public interface ICustomerService
{
    List<CustomerInfo> GetCustomers();
}

public class CustomerService : ICustomerService
{
    public List<CustomerInfo> GetCustomers()
    {
        return new List<CustomerInfo> { new CustomerInfo { Surname = "Bloggs", Name = "Jo" } };
    }

    protected virtual void DoSomething()
    {
    }
}

Could you provide me an example on how you would test my private method?
Thanks a lot

A: The steps you're describing set Moq up to test internal classes and members so have nothing really to do with testing a protected or private method
Testing private methods is a bit of a smell, you should really test just the public API. If you feel that the method is really important and needs to be tested in isolation perhaps it deserves to be in its own class where it can then be tested on its own?
If your heart is set on testing the protected method above you can roll your own Mock in your test assembly:
public class CustomerServiceMock : CustomerService {
    public void DoSomethingTester() {
         // Set up state or whatever you need
         DoSomething();
    }

}

[TestMethod]
public void DoSomething_WhenCalled_DoesSomething() {
    CustomerServiceMock serviceMock = new CustomerServiceMock(...);
    serviceMock.DoSomethingTester();
 }

If it was private you could probably do something dodgy with reflection but going that route is the way to testing hell.

Update
While you've given sample code in your question I don't really see how you want to "test" the protected method so I'll come up with something contrived...
Lets say your customer service looks like this:-
 public CustomerService : ICustomerService {

      private readonly ICustomerRepository _repository;

      public CustomerService(ICustomerRepository repository) {
           _repository = repository;
      }

      public void MakeCustomerPreferred(Customer preferred) {
           MakePreferred(customer);
           _repository.Save(customer);
      }

      protected virtual void MakePreferred(Customer customer) {
          // Or more than likely some grungy logic
          customer.IsPreferred = true;
      }
 }

If you wanted to test the protected method you can just do something like:-
[TestClass]
public class CustomerServiceTests {

     CustomerServiceTester customerService;
     Mock<ICustomerRepository> customerRepositoryMock;

     [TestInitialize]
     public void Setup() {
          customerRepoMock = new Mock<ICustomerRepository>();
          customerService = new CustomerServiceTester(customerRepoMock.Object);
     }

     public class CustomerServiceTester : CustomerService {
          public void MakePreferredTest(Customer customer) {
              MakePreferred(customer);
          }

          // You could also add in test specific instrumentation
          // by overriding MakePreferred here like so...

          protected override void MakePreferred(Customer customer) {
              CustomerArgument = customer;
              WasCalled = true;
              base.MakePreferred(customer);
          }

          public Customer CustomerArgument { get; set; }
          public bool WasCalled { get; set; }
     }

     [TestMethod]
     public void MakePreferred_WithValidCustomer_MakesCustomerPreferred() {
         Customer customer = new Customer();
         customerService.MakePreferredTest(customer);
         Assert.AreEqual(true, customer.IsPreferred);
     }

     // Rest of your tests
}

The name of this "pattern" is Test specific subclass (based on xUnit test patterns terminology) for more info you might want to see here:-
http://xunitpatterns.com/Test-Specific%20Subclass.html
Based on your comments and previous question it seems like you've been tasked with implementing unit tests on some legacy code (or made the decision yourself). In which case the bible of all things legacy code is the book by Michael Feathers. It covers techniques like this as well as refactorings and techniques to deal with breaking down "untestable" classes and methods into something more manageable and I highly recommend it.

A: There are appear to be two parts to your question.

*

*How do I mock a protected method:
http://blogs.clariusconsulting.net/kzu/mocking-protected-members-with-moq/

*how do I trigger the invocation of this protected/private behavior in my test
The answer here is that you trigger it via something public. If you want to force it to happen directly (i.e., actually invoke something protected directly without an intermediate helper, you'll need to use reflection. This is by design - the languages are providing the protection mechanisms as a way of enforcing encapsulation.
I suggest you think about what you're trying to demonstrate/prove in your test though. If you find yourself writing a test that's complicated, you're Doing It Wrong. Perhaps what you want to do can be broken down into independent tests? Perhaps you are writing an integration test, not a unit test? But there are lots of articles out there on bad tests, and more an more will make sense to you as you learn to write good tests. Two of my favourites are http://www.codethinked.com/post/2009/06/30/What-is-Unit-Testing.aspx and http://www.codethinked.com/post/2009/11/05/Ite28099s-Okay-To-Write-Unit-Tests.aspx


text:
Q: Maximum current draw from a step-up regulated output I have a LiPo battery pack with 5V, 2.1A output. Now, let's say I boosted that with a step-up regulator like this Pololu module.
At 12V output from the regulator, what is the maximum current I can draw?
By conservation of energy, I'm assuming it cannot be more than 5 V * 2.1 A / 12 V = 0.875 A, but I'm wondering if there are any other factors at play.

A: Yes, you can't convert all the power at the input to the output. There are always some energy loss in the conversion.
By your Pololu module's specification, it has a typical efficiency between 80% to 90%. You can refer to their Typical Efficiency and Output Current section to find the maximum current you can get.

But, this module has input current limit (typically between 1.4 and 2A),

The maximum achievable output current is approximately proportional to
  the ratio of the input voltage to the output voltage. If the input
  current exceeds the switch current limit (typically somewhere between
  1.4 and 2 A), the output voltage will begin to drop.

So, with 5V input voltage, the input current can't be more then 1.4A. From the graph, we note the efficiency drop as output current increase. At 500mA, the efficiency drop to nearly 80%, then your input current now is
$$
\frac{12V \times 500mA}{0.8 \times 5V} = 1.5A > 1.4A
$$
So, your output current can't be more than 500mA, should be about 450mA or so.


text:
Q: Can't Install Windows 7 on a second disk along side Ubuntu When trying to install Windows 7 after install Ubuntu, I get to the screen where I can see all the disks.
After clicking my second empty disk, formatting it from Windows, when I click next Windows returns:
Setup was unable to create a new system partition

How does one proceed installing Windows 7 in this situation?

A: Windows 7 is a Prima Donna and refuses to get on the stage if Linux is there. The simplest solution is to open up the computer and unplug the disk with Linux. After this, windows has no issues installing. You can then reconnect the disk with Linux after the install (when the machine is powered down of course).


text:
Q: When I am trying to change the code to an access token, I get this error I am using dirkgroenen pinterest api, so it was perfectly fine for 1 month but now when changing code to an access token I am getting this error
Notice: Array to string conversion in /home/socialwe/public_html/SWT/SMs/pinterestApi/vendor/dirkgroenen/pinterest-api-php/src/Pinterest/Transport/Request.php on line 227
Fatal error: Uncaught exception 'DirkGroenen\Pinterest\Exceptions\PinterestException' with message 'Pinterest error (code: 403) with message: Forbidden' in /home/socialwe/public_html/SWT/SMs/pinterestApi/vendor/dirkgroenen/pinterest-api-php/src/Pinterest/Transport/Request.php:227 Stack trace: #0 /home/socialwe/public_html/SWT/SMs/pinterestApi/vendor/dirkgroenen/pinterest-api-php/src/Pinterest/Transport/Request.php(98): DirkGroenen\Pinterest\Transport\Request->execute('POST', 'https://api.pin...', Array) #1 /home/socialwe/public_html/SWT/SMs/pinterestApi/vendor/dirkgroenen/pinterest-api-php/src/Pinterest/Auth/PinterestOAuth.php(143): DirkGroenen\Pinterest\Transport\Request->post('oauth/token', Array) #2 /home/socialwe/public_html/SWT/SMs/pinterestApi/index.php(18): DirkGroenen\Pinterest\Auth\PinterestOAuth->getOAuthToken('dfb587ef87beaaa...') #3 {main} thrown in /home/socialwe/public_html/SWT/SMs/pinterestApi/vendor/dirkgroenen/pinterest-api-php/src/Pinterest/Transport/Request.php on line 227

A: Its because my server IP have blocked by pinterest.
Now I have checked it on another server and its working fine there


text:
Q: How to get post id using ShareDialog? How to get the post id of the post created by native ShareDialog using FacebookBroadcastReceiver.onSuccessfulAppCall?
NOTE : FacebookCallback<Sharer.Result>.onSuccess invoked with result.getPostId() as null