Convert asp.net C# to vb

Question: I am trying to convert this code, but getting some error this is the main link of the code.
I am getting these 2 errors:

Type "domainroute is not defined

and

'optional' is not a member of 'system.web.UI.webControls.routeParameter'

Code:
public class HttpDomainRoute
  : DomainRoute
{
  public HttpDomainRoute(string domain, string url, RouteValueDictionary defaults)
      : base(domain, url, defaults, HttpControllerRouteHandler.Instance)
  {
  }

  public HttpDomainRoute(string domain, string url, object defaults)
     : base(domain, url, new RouteValueDictionary(defaults), HttpControllerRouteHandler.Instance)
 {
 }
}

to this asp.net vb 4
Public Class HttpDomainRoute

     Inherits DomainRoute

    Public Sub New(domain As String, url As String, defaults As RouteValueDictionary)
      MyBase.New(domain, url, defaults, HttpControllerRouteHandler.Instance)
    End Sub

    Public Sub New(domain As String, url As String, defaults As Object)
        MyBase.New(domain, url, New RouteValueDictionary(defaults), HttpControllerRouteHandler.Instance)
    End Sub
End Class

Answer: This class seems to inherit from a class called DomainRoute. This is not a standard class that is part of the MVC framework so make sure you also have this class defined. Or at least reference the assembly where it resides. I guess you've taken it from here. So go ahead and include that class as well.
Comment: I am new in asp.net. can you please give me steps to do so... and it is asp.net 4 webform. and im trying to use routing in global.asax page.
Comment: What kind of guidance do you need more specifically? What difficulties did you encounter when you attempted to convert the `DomainRoute` class to VB.NET once you downloaded the C# version? I am not quite sure how I can help.
Comment: I am trying to implement this [link](http://blog.maartenballiauw.be/post/2012/06/18/Domain-based-routing-with-ASPNET-Web-API.aspx) to my project. i do not have full code of it. it is in C# so i used online telerik code converter service and convert it but as i mentioned i am getting error now..
Comment: There's a link on the bottom of the article where you could download the full C# version: http://blog.maartenballiauw.be/file.axd?file=2012%2f6%2fWebApiSubdomainRouting.zip Inside you will find everything that is necessary for this to work. Look inside the `WebApiSubdomainRouting\WebApiSubdomainRouting\Code` folder. There you have the `DomainData.cs`, `DomainRoute.cs`, `HttpDomainRoute.cs` and `LinkExtensions.cs` classes. All that's left now for you is to translate them to VB.NET. Don't hesitate to ask for help if you encounter some specific problems with this task.
Comment: I found a free SharpDevelop4.3 software to convert full project C# to vb. after converting full project then i ll give you update...
Answer: There is a download link at the bottom. Try to download it and convert the whole code using this free converter. If you download you can find it in the code folder the DomainRoute class. Try to include that class it in your project
Comment: i do not have the full code. i am implementing this website method of capturing subdomain and route [link](http://blog.maartenballiauw.be/post/2012/06/18/Domain-based-routing-with-ASPNET-Web-API.aspx)
Comment: There is a download option in the link you provided with full source code.

Convert asp.net C# to vb


Show that the area of a trapezoid is given in function of one of its angles by $f(x)=4\sin(x)(1-\cos(x))$

Question:

The picture represents an isosceles trapezoid [ABCD]. The sides [AD]
  and [BC] are parallell. It is also known that:

$\overline{AB}=\overline{BC}=\overline{CD}=2$
$\alpha$ is the angle of $ABC$ and $\alpha \in ]\pi/3;\pi/2]$

Consider the function f defined by:
$$f(x) = 4\sin(x)(1-\cos(x))$$
Show that for each $\alpha \in ]\pi/3;\pi/2]$, the area of the
  trapezoid is $f(\alpha)$.

I messed with the picture a bit and did this:

So the area of [ABCD] is given by
$$2 \cdot A_{\text{smaller trapezoid}}$$
The area of the smaller trapezoid is given by:
$$\frac{1+b}{2}\cdot 2\tan(\alpha)$$
To find b I did:

$$2^2 = a^2+(2\tan(\alpha))^2 \Leftrightarrow \\
4 = a^2+4\tan(\alpha)^2 \Leftrightarrow \\
a = \sqrt{4-4\tan(\alpha)^2}$$
$b = 1- \sqrt{4-4\tan(\alpha)^2}$
So the formula becomes:
$$A_{[ABCD]} = 2\cdot (\frac{1+1- \sqrt{4-4\tan(\alpha)^2}}{2} \cdot 2\tan(\alpha)) = \\
2\cdot ((2-\sqrt{4-4\tan(\alpha)^2})\tan(\alpha)) = \\
2\cdot (2\tan(\alpha)-\tan(\alpha)\sqrt{4-4\tan(\alpha)^2}) = \\
4\tan(\alpha)-2\tan(\alpha)\sqrt{4-4\tan(\alpha)^2} = \\
4\tan(\alpha)-\sqrt{4\tan(\alpha)^2(4-4\tan(\alpha)^2)} = \\
4\tan(\alpha)-\sqrt{16\tan^2(\alpha)-16\tan^4(\alpha)}$$
I put this expression and the one given by my book in the calculator to see if they would coincide but they don't. What did I do wrong?
Answer: i would compute $$A=\frac{2+a}{2}h$$ with $$a=AD$$ and $$\sin(\alpha)=\frac{h}{x}$$ with $$2x+a=2$$ can you finish?
Comment: What did I do wrong though? Isn't $h = 2\tan(\alpha)$?
Answer: The vertical in these figures:

Should be $2 \sin \alpha.$
$a =  2 \cos\alpha\\
b = 1-a\\
\frac 12 (B+b) = \frac 12(1+1-2\cos \alpha) = 1-\cos \alpha\\
A = 2(\frac 12 (B+b))(2 \sin \alpha) = 4\sin\alpha(1-\cos\alpha)$
Comment: Why isn't the height $2\tan(\alpha)$?
Comment: I think the question should be, "why would it be?"  I think the simplest explanation is: Opposite / Hypotenuse = $\sin x,$  Opposite / Adjacent = $\tan x.$  Which data do you have?
Comment: Right, I get it now. Thanks.


Algebraic multiplicity of the eigenvalue $1$ in a positive Markov matrix is equal to $1$

Question: I want to show that the following linear system has only one non-trivial positive solution,
\begin{equation}
\begin{bmatrix}
\mu_{1,1}^* & \mu_{2,1}^* &\dots &\mu_{N,1}^* \\
\mu_{1,2}^* & \mu_{2,2}^* &\dots &\mu_{N,2}^*\\
\dots &\dots &\dots &\dots\\
\mu_{1,N}^* & \mu_{2,N}^* &\dots &\mu_{N,N}^*\\
1 & 1 &\dots &1
\end{bmatrix}
\cdot
\begin{bmatrix}
L_1  \\
L_2\\
\dots\\
L_N
\end{bmatrix}
=
\begin{bmatrix}
L_1  \\
L_2\\
\dots\\
L_N\\
\bar{L}
\end{bmatrix}.
\end{equation}
The only assumptions I have are that the entries are positive and the sums of each column in the first matrix are all equal to 2. In other words, the matrix consisting of $\mu^*$s is a positive Markov matrix. Can anyone provide some theorems related to this question? Thanks.
Comment: If the matrix on the LHS, omitting its last row, is the identity matrix, then your system is equivalent to the single equation$$L_1+L_2+\cdots+L_N=\bar L\ .$$As long as $\bar L$ is positive, this will have many positive solutions, not just one.
Comment: You need some extra assumptions on your matrix. Check my answer.
Answer: Your conditions are not sufficient. Here are some properties you need. Firstly, forget about the positiveness of the solution and just assume that $\overline L\ne0$. Break down the condition into two:
Let $M$ be the $N\times N$ matrix consisting of $\mu^*_{i,j}$s. We know that sum of every column on $M$ is equal to $1$. First of all, you want $1$ to be an eigenvalue of your matrix, which already is true by the fact every column adds up to $1$, (think of the vector $(1,1,\ldots,1)$ as the eigenvector for $M^t$, and use the fact that $M^t$ and $M$ has the same eigenvalues.)
Let $V$ be the set of vectors satisfying $Mv=v$. Then, for a given non-zero $\overline L$, you want a unique $v$ in $V$ satisfying $L_1+L_2+\ldots+L_n=\overline L$. Observe that if $\dim V=1$ and the basis $\{v_0\}$ for $V$ is not satisfying $[1,1,\ldots,1]v_0=0$, you have what you want, as any vector in $V$ is of the form $cv_0$, for scalar $c$ and you can choose $c$ as appropriately.
However, if $\dim V>1$ you can show that the uniqueness is not longer valid. For example, let $v_1,v_2$ be two linearly independent vectors in $V$ such that $[1,1,\ldots,1]v_1\ne0$, (if such $v_1$ does not exists, there is no solution to your equation). Then, one can choose a scalar $c_!$ such that $c_1v_1$ is a solution. If $$[1,1,\ldots,1]v_2\ne0$$ then one cn choose a $c_2$ similarly and we would have two solutions $c_2v_1,c_2v_2$. So, suppose $$[1,1,\ldots,1]v_2=0$$
then, $c_1v_1+v_2\ne c_1v_1$ is also a solution. Contradiction.
About positiveness, I believe some extra conditions, maybe positiveness etc, on $\mu^*_{i,j}$s are necessary to achieve it.
Comment: Thanks a lot for the ideas. In fact, positiveness on $\mu$ is satisfied. So the positiveness of solutions holds?
Comment: With that condition, $\dim V=1$ is satisfied, as $M$ is a positive Markov matrix. Look at the pages 89-90-91 of this pdf: http://www.numbertheory.org/courses/MP274/markov.pdf It has all you need.
Comment: Thanks. I did look at the pdf document but still a little confused. How the eigenvalues are related to the dimension of vector space?
Comment: $V$ is the vector space of eigenvectors associated to the eigenvalue $1$. 4.10 in page 910 is exactly what you are looking for.


ERROR: Invalid syntax. Default option is not allowed more than '2' time(s)

Question: I'm trying to run the powershell script below to identify the USB or SCSI interfacetype connected to the computer, the script works just fine if I don't use the IF and -Or operators
if(($diskdrive = (gwmi win32_diskdrive | ?{$_.interfacetype -eq 'USB'})) -Or ($diskdrive =(gwmi win32_diskdrive | ?{$_.interfacetype -eq 'SCSI'}))){
$letters = $diskdrive | %{gwmi -Query "ASSOCIATORS OF
{Win32_DiskDrive.DeviceID=`"$($_.DeviceID.replace('\','\\'))`"} WHERE

AssocClass = Win32_DiskDriveToDiskPartition"} |  %{gwmi -Query "ASSOCIATORS

OF {Win32_DiskPartition.DeviceID=`"$($_.DeviceID)`"} WHERE AssocClass =

Win32_LogicalDiskToPartition"} | %{$_.Deviceid}
setx OSDUSBDrive $letters /M
Write-Output $diskdrive, $letters}
Start-Sleep -s 5

    if (-not ("Win32.NativeMethods" -as [Type]))
    {
        # import sendmessagetimeout from win32
    Add-Type -Namespace Win32 -Name NativeMethods -MemberDefinition @"
    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessageTimeout(
        IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam,
        uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);
"@
    }

    $HWND_BROADCAST = [IntPtr] 0xffff;
    $WM_SETTINGCHANGE = 0x1a;
    $result = [UIntPtr]::Zero

    # notify all windows of environment block change
    [Win32.Nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [UIntPtr]::Zero, "Environment", 2, 5000, [ref] $result);

Start-Sleep -s 5

ERROR: Invalid syntax. Default option is not allowed more than '2'
  time(s). C:\temp\AddOSDUSBDrive_NEW.ps1:10 : 1
  + setx OSDUSBDrive $letters /M
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (Erreurÿ: Syntax...plus de 2 fois.:String) [], RemoteException
      + FullyQualifiedErrorId : NativeCommandError   Entrez "SETX /?" pour afficher la syntaxe.

Any idea?
Answer: Use setx OSDUSBDrive "$letters" /M
Applied SETX.exe syntax pattern

SETX [/s Computer [Credentials]] Variable Value [/m]
                                          ↑↑↑↑↑

could be wrong if $letters contains more letters e.g. F:, G:, H:
 setx OSDUSBDrive $letters /M
 #                ↑↑↑↑↑↑↑↑        this evaluates to
 setx OSDUSBDrive F: G: H: /M
 #                ↑↑ ↑↑ ↑↑        three space-separated values (WRONG)

Adjusted (see Syntax : Escape Characters, Delimiters and Quotes):
 setx OSDUSBDrive "$letters" /M
 #                ↑↑↑↑↑↑↑↑↑↑       this evaluates to
 setx OSDUSBDrive "F: G: H:" /M
 #                 ↑↑↑↑↑↑↑↑        one string value (quotes = escape characters)

Moreover, I'd adjust the first IF as follows:
if ( $diskdrive = ( Get-WmiObject win32_diskdrive |
        Where-Object { $_.interfacetype -in ('USB','SCSI') } ) ) {

Explanation: -or operator means logical OR: TRUE when either i.e. if first operand evaluates to TRUE, then other operands are never evaluated.
For instance, run
Remove-Variable a, b -ErrorAction SilentlyContinue
if ( ($a = 1) -or ($b = 3) ) { Write-host "a=$a b=$b" }

The variable '$b' cannot be retrieved because it has not been set.

if ( ($a = $null) -or ($b = 3) ) { Write-host "a=$a b=$b" }

a= b=3
Comment: That works when I run it manually, however I get this error when it's called from SCCM
The argument 'AddOSDUSBDrive _NEW.ps1' to the -File parameter does not exist. Provide the path to an existing '.ps1' file as an argument to the -File parameter.
Answer: I actually added  this as you suggested :

if ( $diskdrive = ( Get-WmiObject win32_diskdrive |
          Where-Object { $_.interfacetype -in ('USB','SCSI') } ) ) {

the script works fine when I run it manually, however I get the error below when it's called from SCCM

You must provide a value expression on the right-hand side of the '-'
  operator. TaskSequencePSHost  3/6/2018 4:36:37 PM 0 (0x0000) At
  D:\SMS\PKG\SE1001B5\AddOSDUSBDrive_NEW.ps1:2 char:42
  +         Where-Object { $_.interfacetype - <<<< in ('USB','SCSI') } ) ){ TaskSequencePSHost  3/6/2018 4:36:37 PM 0 (0x0000) ParserError: (:)
  [], ParseException    TaskSequencePSHost  3/6/2018 4:36:37 PM 0 (0x0000)
  TSHOST: Script completed with return code
  0 TaskSequencePSHost  3/6/2018 4:36:37 PM 0 (0x0000)


HttpMessageNotWritableException: No converter for [class java.util.zip.ZipOutputStream] with preset Content-Type 'application/octet-stream'

Question: I'm writing a REST GET service to download a zip of photos from an event. Using Spring boot 2.7.8
I've tried different recommendations from stackoverflow, but cannot seem to get past this.
<code>@RequestMapping(value = "/api/event/{eventId}/photos/zip", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
   public ResponseEntity<?> downloadEventPhotosZipAPI(@PathVariable
   long eventId,
      HttpServletResponse response) throws Exception
   {
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

      final ZipOutputStream zos = new ZipOutputStream(
         response.getOutputStream());

      List<Attachment attachmentList = //~~~ {read a list of photo binary blobs from DB for this event ...}

      int i = 1;
      for (Attachment photo : attachmentList)
      {
         String filename = "event_photo"
            + i
            + ".jpg";
         ZipEntry entry = new ZipEntry(
            filename);
         zos.putNextEntry(entry);
         zos.write(photo.getBytes());
         zos.closeEntry();
         i++;
      }

      zos.close();

      return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
         "attachment;filename=event-"
            + eventId
            + "-photos.zip")
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(zos);
   }
</code>
Answer: 1.Changed the return type to void:
Since you are directly writing to the response output stream, the method can be set to return void. Removed the unnecessary HttpHeaders object creation:
The HttpHeaders object is not needed in this modified code, as the headers are directly set on the response object.

Use try-with-resources for ZipOutputStream:
Enclose the ZipOutputStream creation within a try-with-resources block. This ensures that the output stream is automatically closed after the ZIP file is created, avoiding potential resource leaks.

Simplified the attachment list retrieval:
The code assumes that you have a working mechanism to retrieve the list of Attachment objects from the database. Adjust the code accordingly to populate the attachmentList variable.

<code>public void downloadEventPhotosZipAPI(@PathVariable long eventId, HttpServletResponse response) throws Exception {
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=event-" + eventId + "-photos.zip");

    try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
        List<Attachment> attachmentList = //~~~ {read a list of photo binary blobs from DB for this event ...}

        int i = 1;
        for (Attachment photo : attachmentList) {
            String filename = "event_photo" + i + ".jpg";
            ZipEntry entry = new ZipEntry(filename);
            zos.putNextEntry(entry);
            zos.write(photo.getBytes());
            zos.closeEntry();
            i++;
        }
    }
}
</code>
Comment: I am getting a file and download panel in the browser now, but after saving the file and trying to open/extract it, the error says:

"Truncated ZIP file header".

If I run  zip -T event-114-photos.zip      on the command line, the error output is:

zip -Tv event-114-photos.zip
 zip warning: unexpected signature on disk 0 at 778976

 zip warning: archive not in correct format: event-114-photos.zip
 zip warning: (try -F to attempt recovery)

zip error: Zip file structure invalid (event-114-photos.zip)

Anything else needed on the Spring side for ZIP correct format?
Comment: Hi @jn4 try modified code try {
            List attachmentList = //~~~ {read a list of photo binary blobs from DB for this event ...}
   //add above try with resource block here
        } catch (IOException e) {
        } finally {
            // Important: Do NOT close the response output stream here, as it is managed by the servlet container.
        }
Comment: The servlet container will handle closing the output stream after the response is sent.Closing the output stream here would cause issues with the ZIP download.
Comment: I am not closing the zos as requested.  I added a catch (IOException) after the try block which only logs a warning, and included a finally { } that does nothing.  Still having the error on the client after download.


Fixed-point-free permutations

Question: An $i \in [n]$ is called a fixed point of a permutation $\sigma \in S_n$ if $\sigma(i) = i$.
Let $D(n)$ be the number of permutations $\sigma \in S_n$ without any fixed point.

Prove that

i) $D(n) = n \cdot D(n-1) + (-1)^n$ for $n \geq 2$
ii) $D(n) = (n-1)(D(n-1) + D(n-2))$ for $n \geq 3$

First I tried to write down all fixed point-less permutations (in one-line notation):
$n \leq 1 \rightarrow$: none
$n = 2$: (2 1)
$n = 3$: (2 3 1) (3 1 2)
$n = 4$ (2 1 4 3) (2 3 4 1) (2 4 1 3) (3 1 4 2) (3 4 1 2) (3 4 2 1) (4 1 2 3) (4 3 1 2) (4 3 2 1)
Unfortunately I didn't find any way of constructing these permutations by using the ones from $(n-1)$.
Could you please help me a little bit?
Thank you in advance!
Comment: The same problem as in http://math.stackexchange.com/questions/14666
Answer: These are called derangements.  For a discussion, please see for example
http://en.wikipedia.org/wiki/Derangement
Answer: Part (ii) is explained in the Wikipedia article that user6312 mentioned. Part (i) can be derived from part (ii) by induction.
You could also derive all of these "brute force" using the inclusion-exclusion principle. Using the principle, you write an explicit formula for $D(n)$. Then you do some algebra and you should get both parts. But Wikipedia's proof is better, since it explains why the formula is true.
Edit: More on deriving (i) from (ii):
$$
\begin{align*}
D(n) &= (n-1)(D(n-1)+D(n-2)) \\ &= (n-1)((n-1)D(n-2)+(-1)^{n-1} + D(n-2)) \\ &=
(n-1)(nD(n-2) + (-1)^{n-1}) \\ &=
n(n-1)D(n-2) + (n-1)(-1)^{n-1} \\ &=
n((n-1)D(n-2) + (-1)^{n-1}) - (-1)^{n-1} \\ &=
nD(n-1) + (-1)^n.
\end{align*}
$$
Comment: @user6312 @Yuval-Filmus the part (ii) is completely clear now, thank you both! @Yuval-Filmus What do you mean with " [..] can be drived from part (ii) by induction"?. If using the identity of (ii) I get $$D(n+1) = n \cdot D(n) + D(n-1)$$ but how do I transform that into something similar like the identity of (i)?
Comment: @muffel: Do a proof by induction.
Comment: @Yuval-Filmus induction of what exactly? Thank you for your addition. Could you please tell me what you did to get from the first  to the second line? (how you introducted the $(-1)^{(n-1)}$)?
Comment: @muffel: I used a proof by induction. Assuming the formula for $n-1$, I prove it for $n$ using (ii). You also have to check the base case $D(2) = 2D(1) + 1$.
Comment: @Yuval-Filmus thank you!

Fixed-point-free permutations


compactenss on function spaces of the form $\mathbb{R}^X$

Question: Let $X\subset \mathbb{R}_+$ a countable set. We consider the space of functions
$\mathbb{R}^X$, i.e. $g:X\to \mathbb{R}$ with the topology of pointwise convergence. Let $A_C\subset X$ all functions such that $\frac{|g(x)|}{(1+x)^p}\le C, \forall x\in X$. My notes say, since $X$ is countable the space $A_C\subset X$ is compact. Why is this true? Is there a general result from topology, which guarantees compactness in this case? Note, by the definition of the space $A_C$, we can define a norm $\|g\|:=\sup_{x\in X} \frac{|g(x)|}{(1+x)^p}$ and then we have $g\in A_C\iff \|g\|\le C$. I'm not sure if this is also used for compactness. A reference or explanation would be appreciated.
Comment: What is $p$? $\,$
Comment: @BrianM.Scott $p$ is a constant $p>2$
Answer: For each $x\in X$ let $I_x$ be the closed interval in $\Bbb R$ given by
$$I_x=\left[-C(1+x)^p,C(1+x)^p\right]\;.$$
Then $$\frac{|g(x)|}{(1+x)^p}\le C$$ if and only if $g(x)\in I_x$, so
$$A_C=\prod_{x\in X}I_x\;.$$
Closed intervals in $\Bbb R$ are compact, so $A$ is a product of compact sets and is therefore compact in the product topology on $\Bbb R^X$. And the topology of pointwise convergence on $\Bbb R^X$ is just the ordinary Tikhonov product topology on the product $\Bbb R^X$, so $A_C$ is compact in it.
Comment: Just one small question: Where do we use that $X$ is countable? For Tikhonov we don't need a countable product.
Comment: @hulik: So far as I can see, the countability of $X$ doesn't make any difference here. It does ensure that $\Bbb R^X$ is metrizable in the product topology, which might be used later.


Is this $x \mapsto k^{k^{\frac{-1}{x}}}$ a contraction?

Question: Given that $k,x \in \mathbb{R}^+$ and $k > 1$, the function $f$ defined by $$f(x) = k^{k^{\frac{-1}{x}}}$$, generates a sequence $x_0,f(x_0), f(f(x_0)), \cdots$ is observed to converge to a fixed point independent of $x_0$. (Proof)
I was wondering if $f$ is a contraction on the metric space of $\mathbb{R}^+$ equipped with absolute distance.
Comment: Yes, given you exclude $0$ from the domain.
Comment: @fawningflagellum Can you help me prove it?
Answer: If
$f(x)
= k^{k^{\frac{-1}{x}}}
= e^{\ln(k)k^{\frac{-1}{x}}}
$,
so that
$\begin{array}\\
f'(x)
&=f(x)(\ln(k)k^{\frac{-1}{x}})'\\
&=f(x)(\ln(k)e^{\ln(k)\frac{-1}{x}})'\\
&=f(x)\ln(k)((\ln(k)\frac{-1}{x})'e^{\ln(k)\frac{-1}{x}})\\
&=f(x)\ln^2(k)\frac{1}{x^2}k^{\frac{-1}{x}}\\
&=\dfrac{k^{k^{\frac{-1}{x}}}\ln^2(k)k^{\frac{-1}{x}}}{x^2}\\
\end{array}
$
The condition
for a contraction mapping
is
$|f'(x)| < 1
$.
In this case,
The set of $x$
for which this is true
depends on numerical computation,
since it appears
highly unlikely
that an analytic solution
if possible.


Undefined Reference to 'main' when code is compiled

Question: I created a C program which would create a directory and file.
I have tried to debug the error, but it didn't work
<code>#include <dirent.h>
#include <errno.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>

create_dir(char* outputdir,char* str_outpath,char* value){

DIR* dir = opendir(outputdir);
FILE *f;

if (dir) {
    /* Directory exists. */
    closedir(dir);
} else if (ENOENT == errno) {
    /* Directory does not exist. */
    mkdir(outputdir, 0700);
    closedir(dir);
    printf("Successfully created the directory %s ", outputdir);

} else {
    printf("Creation of the directory %s failed",outputdir);
    /* opendir() failed for some other reason. */

}

f = fopen(str_outpath, "a");
fprintf(f,"%s",value);
fclose(f);

}
</code>
I want it to create a file and a directory successfully
Comment: So... where is your `main` then?
Comment: So far you haven't created a C program -- you've created a single C function.  Every C program that's going to actually run needs a `main()` function, which is where everything starts.  That's why you're getting a complaint that `main` is undefined.
Comment: Main is entry point of your app. You need main function.
Comment: Aside from the problem you're asking about, your `create_dir` function needs a return type. If it doesn't return a value, declare it as `void create_dir(char* outputdir,char* str_outpath,char* value) { /* ... */ }`. (Omitting the return type for a function is an obsolete language feature, removed in the 1999 standard.)
Answer: As others have mentioned. You do not have a main function.
Also your create_dir function is missing a type. I'll assume it's void since you are not returning anything. This should compile.
<code>#include <dirent.h>
#include <errno.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>

void create_dir(char* outputdir,char* str_outpath,char* value){

    DIR* dir = opendir(outputdir);
    FILE *f;

    if (dir) {
        /* Directory exists. */
        closedir(dir);
    } else if (ENOENT == errno) {
        /* Directory does not exist. */
        mkdir(outputdir, 0700);
        closedir(dir);
        printf("Successfully created the directory %s ", outputdir);

    } else {
        printf("Creation of the directory %s failed",outputdir);
        /* opendir() failed for some other reason. */

    }

    f = fopen(str_outpath, "a");
    fprintf(f,"%s",value);
    fclose(f);
}

int main(){
    char directory[] = "/users/me/documents/testdir";
    char filepath[] = "testfile";
    char data[] = "hello world";
    create_dir(directory,filepath,data);
    return 0;
}

</code>
I did not execute the code to check whether it works. I merely copied and pasted yours and called the function.
Answer: In C under most cases you need to have a main function. So in order to run your code you'll need to have something like this (assuming that you want to pass in the parameters from the command-line) underneath that function:
<code>int main(int argc, char *argv[]) {

    if (argc < 4) {
        printf("Proper Usage is ./program otputdir str_outpath value\n");
        return -1;
    }

    char *outputdir = argv[1];
    char *str_outpath = argv[2];
    char *value = argv[3];

    create_dir(outputdir, str_outpath, value);
    return 0;
}
</code>
EDIT: fixed an issue with not checking argc
Comment: Except this should check if `argc==4`, and if not complain in some way instead of trying to use possibly invalid `argv` elements.


Sorting rows then sorting columns preserves the sorting of rows

Question: From Peter Winkler's book:

Given a matrix, prove that after first sorting each row, then sorting each column, each row remains sorted.

For example: starting with
$$\begin{bmatrix}
1 & -3 & 2 \\
0 & 1 & -5 \\
4 & -1 & 1
\end{bmatrix}$$
Sorting each row individually and in ascending order gives
$$\begin{bmatrix}
-3 & 1 & 2 \\
-5 & 0 & 1 \\
-1 & 1 & 4
\end{bmatrix}$$
Then sorting each column individually in ascending order gives
$$\begin{bmatrix}
-5 & 0 & 1 \\
-3 & 1 & 2 \\
-1 & 1 & 4
\end{bmatrix}$$
And notice the rows are still individually sorted, in ascending order.
I was trying to find a 'nice'  proof that does not involve messy index comparisons... but I cannot find one!
Comment: I don't understand what the rows will remain sorted means.  When you rearrange the columns you aren't doing anything to the cells in terms of their row positions so of course the rows remain sorted.
Comment: Given a row, say you sort it in ascending order. Repeat for each row. Now take the resulting matrix, and do the same for each individual column. Then each row of the resulting matrix still  has its entries in ascending order.
Comment: I will add an example to my question
Comment: How are you sorting?
Comment: Oh, I get it.  You are sorting lexigraphically.  The rows will remain lexigraphic.  That is true and not trivial.
Comment: Oh you sort the *cells* in each row not  the entire rows as whole rows.
Comment: You need messy index.  But messy index shouldn't be that bad.
Comment: Hopefully the example clarifies my statement now
Comment: @fleablood: Do you consider my answer to be a counter-example to "needing messy index"? =)
Comment: Well... no, I assume  the OP would have considered your answer to be messy indexing.  But apparently not..  I don't consider messy indexing to be a problem.
Answer: Notice that you can start from after the first step. Specifically, you only need to prove that, given an arbitrary matrix where each row is already in ascending order, sorting each column in ascending order keeps each row sorted. Here is a very neat trick to do this.
Let $m$ be the number of columns. For each $k$ from $1$ to $m$, sort the rows of the subarray from column $k$ to column $m$ in increasing order of the element in column $k$. (Each row of the subarray stays together.) We do this sorting by bubble sort. We maintain the invariant that the elements in each row stays sorted. This invariant is trivially true when $k = 1$. When $k > 1$, and we perform a swap involving rows $p$ and $(p+1)$, consider the elements in those rows and in the columns $(k-1)$ and $k$:

$\cdots \quad a \quad d \quad \cdots_1$
$\cdots \quad b \quad c \quad \cdots_2$

By the invariance we have $a \le b \le c$ and the swap is only done because $c \le d$. After the swap we have:

$\cdots \quad a \quad c \quad \cdots_2$
$\cdots \quad b \quad d \quad \cdots_1$

And the invariance is preserved since $a \le c$ and $b \le d$. Look! No index chasing!
Comment: Really neat many thanks !!!!
Comment: @user3203476: You're welcome! This trick of incrementally sorting is very useful, since in some sense preserving an invariant over a swap is the bare minimum that you need to preserve the invariant over sorting.
Comment: Not getting this. You show that when you bubblesort a column, it remains entrywise $\geq$ to the column to its left. Shouldn't you also show that it remains entrywise $\leq$ to the column to its right? This is probably analogous, but needs to be at least said.
Comment: @darijgrinberg: No, read the second sentence in my second paragraph again. It does not say we bubblesort a column. In fact, I explicitly emphasized that in the bracketed third sentence. Also, if you bubble-sort a single column at a time, it will fail, unlike what I describe.
Comment: What does "Each row of the subarray stays together" mean? And how does sorting columns $k$ to $m$ help?
Comment: @darijgrinberg: I'm not sure what you're reading. The second sentence says very clearly "**sort the rows of** the subarray from column k to column m".
Comment: I don't get it. Aren't the rows already increasing? If so, why sort them again?
Comment: @darijgrinberg: You should spend more time reading what I wrote carefully, as it is 100% clear already. If you don't get it, don't just assume there is something wrong (as you did from your first comment). There is only one way to parse the second sentence: "For each k from 1 to m { sort { the rows of { the subarray from column k to column m } } ( in increasing order of { the element in column k } ) }". Frankly, this is basic English, just like "sort these apples in increasing order of size".
Answer: Let's say after sorting, the new matrix is $A$ with m rows and n columns. We have to prove that
\begin{equation}
A_{ij}\leq A_{ik},\, \forall j  \leq k
\end{equation}
where  $A_{xy}$ is element at $x_{th}$ row and $y_{th}$ column.
Here we know that there are at least $i$ elements (including $A_{ik}$) in column $k$ which are less than or equal to $A_{ik}$ and corresponding to their initial positions we have $i$ elements in column $j$ which are at most those elements therefore at least $i$ elements exist in column $j$ which are less than or equal to $A_{ik}$, Hence when column j is sorted
\begin{equation}
A_{ij} \leq A_{ik}
\end{equation}
Comment: This solution is somewhat unclear; please distinguish between submatrices and elements.


Lightbox não cobre a tela inteira

Question: Quando abro a imagem no lightbox, e desço a página, fica assim:
Alguém pode me ajudar?
meu código é o seguinte:
html:

CSS:
.mtlsr-lightbox{display:none;position:absolute;width:100%;height:100%;z-index:99999999999999;top:0;}
.mtlsr-lightbox .image-in-lightbox{max-width:700px;width:100%;position:absolute;z-index:999;top:10%; margin-left: auto;margin-right: auto;left: 0;right: 0;}

.close, .next, .prev{position:absolute;z-index:9999;}
.close{position:absolute;right:20px;top:20px}
.next, .prev{top:50%}
.next{right:20px;}
.prev{left:20px;}

.mtlsr-images-for-lightbox{max-width:600px;margin:0 auto;overflow:hidden}
.mtlsr-images-for-lightbox ul li{float:left;display:inline;width:30%;margin:1%;padding:1%;background-color:#fff;border-top:2px solid #598dca}
.mtlsr-images-for-lightbox ul li a img{width:100%;height:auto;}
.mtlsr-lightbox{
/* IE9 SVG, needs conditional override of 'filter' to 'none' */
background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzAwMDAwMCIgc3RvcC1vcGFjaXR5PSIwLjciLz4KICAgIDxzdG9wIG9mZnNldD0iMTAwJSIgc3RvcC1jb2xvcj0iIzAwMDAwMCIgc3RvcC1vcGFjaXR5PSIwLjciLz4KICA8L2xpbmVhckdyYWRpZW50PgogIDxyZWN0IHg9IjAiIHk9IjAiIHdpZHRoPSIxIiBoZWlnaHQ9IjEiIGZpbGw9InVybCgjZ3JhZC11Y2dnLWdlbmVyYXRlZCkiIC8+Cjwvc3ZnPg==);
background: -moz-linear-gradient(left,  rgba(0,0,0,0.7) 0%, rgba(0,0,0,0.7) 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, right top, color-stop(0%,rgba(0,0,0,0.7)), color-stop(100%,rgba(0,0,0,0.7))); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(left,  rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.7) 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(left,  rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.7) 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(left,  rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.7) 100%); /* IE10+ */
background: linear-gradient(to right,  rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.7) 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#b3000000', endColorstr='#b3000000',GradientType=1 ); /* IE6-8 */
}
.mtlsr-lightbox .image-in-lightbox{
border-radius:5px
}
.close, .next, .prev{color:#666;font-size:30px;text-decoration:none;}
.next, .prev{color:#aaa;font-size:80px;}
.close:hover, .next:hover, .prev:hover{color:#fff;}

js:
$(document).ready(function() {
        var current = '.mtlsr-images-for-lightbox ul li.current';

        //Função para verificar a posição atual da imagem e remover as setas(prev e next) conforme necessário
        function check_image_position(){
            if ($(current).is(':last-child')) {
                $('.next').hide();
                $('.prev').show();
            }else if ($(current).is(':first-child')) {
                $('.next').show();
                $('.prev').hide();
            }else{
                $('.next, .prev').show();
            }
        }

        $('.mtlsr-images-for-lightbox ul li').on('click', 'a', function(event) {
            event.preventDefault();
            var big_image_href = $(this).attr('href');

            $(this).parent().addClass('current');
            $('.mtlsr-lightbox').fadeIn();
            $('.mtlsr-lightbox').append('
');

            check_image_position();
        });
        //Fechar
        $('.mtlsr-lightbox').on('click', '.close', function(event) {
            $('.mtlsr-lightbox').fadeOut();
            $('.mtlsr-lightbox .image-in-lightbox').remove();
            $(current).removeClass('current');
        });
        //Função Next e Prev
        $('.mtlsr-lightbox a').on('click', function(e){
            if($(this).attr('class')=='next'){
                var big_image_href = $(current).next().find('a').attr('href');

                $(current).next().addClass('current');
                $(current).prev().removeClass('current');

            }else if($(this).attr('class')=='prev'){
                var big_image_href = $(current).prev().find('a').attr('href');

                $(current).prev().addClass('current');
                $(current).next().removeClass('current');
            }
            check_image_position();

            $('.mtlsr-lightbox .image-in-lightbox').remove();
            $('.mtlsr-lightbox').append('
');
        });
    });

Comment: Coloca `overflow: hidden` em seu elemento Pai do **LightBox**.
Answer: Altere sua primeira linha para:
  .mtlsr-lightbox {
                    display: none;
                    position: absolute;
                    width: 100%;
                    min-height: 100%;
                    height: auto;
                    z-index: 999999;
                    top: 0;
                  }
E faça o teste. Mas antes defina o seu body com 100%.
html, body { height: 100% }
Você também pode passar a altura baseada na altura do navegador através de um método jquery:
 $(document).ready(function() {
            var altura = $(window).height();
            $('.mtlsr-lightbox').height(altura);
        });

Comment: Não deu certo! Me ajudeem
Comment: Você definiu seu elemento body com 100% ?
Comment: Em último caso, coloca um height: 9000000px;
Comment: Não, posso colocar em pixels, mas quando coloquei 99999px, ele funcionou, porém ficou muito maior que a altura da pagina, por isso não posso colocar em pixels, e por outro motivo também, é um site responsivo.
Comment: Para o height:100% do seu elemento funcionar, o html, body precisa estar com 100% também.
Comment: Como sugeriu o Paulo, o atributo "fixed" também resolve, pois ela não irá  alterar sua janela.
Answer: Em vez de position: absolute; coloque position: fixed;
.mtlsr-lightbox {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 99999999999999;
}

Comment: Deu certo, muito obrigado
Comment: É gambiarra isso aí meu, faz o negócio direito... se é loco cachorrera.

Lightbox não cobre a tela inteira


Homomorphism of two groups

Question: show that $f:G \ \times  H \rightarrow G$ Given by $f((x,y))=x$ is a surjective homomorphism.
I'm not really sure on how to tackle this homework problem.
So I tried with letting H = $f((c,d))=b$
Then $f((x,y),(c,d))=xb=f((x,y)),f((c,d))$ Hence it is a homomorphism?
To show it is onto I have to show that for every cartesian product of G and H there exists an element in G?
Comment: $f$ is a projective homomorphism, so it is surjective.
Answer: In fact, $f((a,b)(c,d))=f((ac,bd))=ac=f((a,b))f((c,d))$, so that it is a homomorphism. To prove it is surjective, only show that every element of $G$ can be represented as the result of this function. Suppose $x\in G$. Therefore, $x=f((x,y)).$ It is also good to note that this is not a isomorphism, once $f^{-1}$ is not well-defined.
Comment: A function being surjective depends on many things. If we defined, for example, $f$ as a function from $G\times H$ to a bigger group in which $G$ is included, we couldn't call it a surjection. I say it has no inverse because $f$ is not injective, once that, for example, $f((x,y))=f((x,z))=x$, but $(x,y)$ and $(x,z)$ are distinct elements of $G\times H$. Therefore, it can't be bijective- and, as a consequence, neither have an inverse.
Comment: Ok thanks that was a good explanation¨
Comment: so that it is surjective pretty much follows from the way the function is defined? And why would you say that it has no inverse

Homomorphism of two groups


Why do some Wireless Access Points cost so much more than others?

Question: Here are three different Wireless Access Points with similar specs:

$875 CISCO AIR-AP1252AG-A-K9 Wireless Access Point
$150 NETGEAR WNAP210-100NAS Prosafe Wireless Access Point
$49  TP-LINK TL-WA901ND IEEE 802.11b/g/n 300Mbps 3 antennas Wireless N Access Point

There's a 17-fold different in price between the cheapest and most expensive. All three support 802.11n and WPA2. The TP-LINK does not support PoE but the others do.
With networking equipment, I'm used to "getting what you pay for"... but I can't understand who is purchasing $875 WAPs and what they are using them for.
What am I missing?
Comment: Why do some cars cost more than others?
Answer: One of those gets rebooted weekly, another works perfectly fine for most people, and another has the capability to take part in huge wireless mesh topologies that work together to cover entire campuses, allowing seamless handoff, load balancing, etc etc etc.
Comment: +1 I run a wireless network on a medium sized campus that has about 150 Cisco LAP 1220/1131/1141s. You really do get what you pay for. I had an uptime of 231 days on my most RECENTLY rebooted AP when I had to take them down for a firmware upgrade.
Comment: right on.  even with OSS firmware that gives cheap routers the software capabilities of much more expensive units, you still have a cheap box with flaky components and lousy heathflow, making even the best software to hung up occasionally.
Answer:
VLAN trunking for multiple wireless SSIDs
AAA (including TAC-ACS) support [authentication, authorization and auditing]
Support, Features, Warranty (as mentioned by Chris S)
Reliability (as mentioned by Matt Simmons)
Answer: They're meant for different markets. The Cisco WAP is an enterprise class WAP and is undoubtedly engineered to much more exacting specifications then the other two. The other two I would consider SOHO market.
Why does a Cadillac cost more then a Cobalt? They both have similar specs. I can't understand who is purchasing a $42,000.00 car and what they are using it for.
Comment: Your comparison to cars is a bit off. You get luxury features in a Cadillac but the function (transportation) is the same. In this example, the Cisco gear is far superior in almost every way from signal strength to reliability to management. In my wireless network, I can update all 150 WAPs' firmware at once with one click of a button. In a wireless network of that size, something like this is not a luxury, but a necessity.
Comment: @MarkM: Your argument makes my point. The higher price point avails you of the luxury features you want. It's a neccessity for you, but not for everyone. The car analogy is the same: Cadillacs come with "run flat tires" and a host of other advanced features and luxuries which are a neccessity to the Cadillac buyer but not to the Cobalt buyer, hence the price difference.
Comment: @joe - I see now. Your last line about not understanding who buys a Caddy makes it sound like you don't understand who would buy the Cisco AP - which is why I tried to shed some light.
Comment: MarkM: I was trying to illustrate my point with a somewhat sarcastic analogy, which was probably not the best idea. Apologies if anyone took offense as none was intended.
Comment: @joe - I just assumed that you were the economical type that really loved your Cobalt haha. No offense taken.
Comment: My daughter has a Cobalt. I'm a Ford Explorer man myself. ;)
Comment: So if the Cisco is the $42,000 Cadillac, what are you suggesting is the $2,470 car (1/17th the price)? I understand that there is price variability, but I'm wondering what justifies a SEVENTEEN-FOLD increase from low-end to high-end.
Comment: @Portman - I think that has already been answered. The difference is manageability, advanced features that the average user doesn't need and upgradability. For example, you can buy radios for many Cisco APs, so that if you spend $875 on a B device and then G comes out (which happened to us) you can simply buy a G radio and upgrade the AP instead of buying a whole new AP. Also, the ability to use a WLC instead of managing each independently is desirable.
Comment: @Portman - a "SEVENTEEN-FOLD" increase isn't much when you're talking about a piece of crap on the low end that you probably wouldn't even want in your house and a workhorse that can easily sustain many dozens of simultaneous connections without ever needing a reboot.
Answer: The more of each, the higher the price. You get what you pay for.

Support
Warranty
Features
Brand Name (per Evan)
Comment: I'd beg to differ w/ the "Warranty" and "Support" when it comes to the Cisco AP, unless you mean to say "You get warranty and support with the higher priced one by paying even more, per year, after paying the initial high price."


Como escutar alterações de coordenadas em um canvas através de um dispositivo mobile?

Question: Criei este componente em Angular que possui um canvas e quando o usuário clica e arrasta nesse quadro, o canvas é preenchido com as posições das coordenadas.
Tentei reproduzir esse mesmo comportamento em um celular, porem quando eu clico e arrasto as coordenadas aparentemente não estão sendo pegas corretamente.
Como posso escutar alterações de coordenadas em um canvas através de um dispositivo mobile?
Meu template:

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

Meu componente:
@ViewChild('canvas') canvas: ElementRef<HTMLCanvasElement>;
  isDrawing = false;
  coordX = 0;
  coordY = 0;
  context;

  constructor(private elementRef: ElementRef, private renderer2: Renderer2) {}

  ngAfterViewInit() {
    this.context = this.getContext2d();
    this.listenToCursorDownChanges();
    this.listenToCursorMoveChanges();
    this.listenToCursorUpChanges();
  }

  getContext2d() {
    return this.elementRef.nativeElement
      .querySelector('#drawer')
      .getContext('2d');
  }

  listenToCursorDownChanges() {
    this.canvas.nativeElement.addEventListener('mousedown', (e) => {
      this.coordX = e.offsetX;
      this.coordY = e.offsetY;
      this.isDrawing = true;
    });
  }

  listenToCursorMoveChanges() {
    this.canvas.nativeElement.addEventListener('mousemove', (e) => {
      if (this.isDrawing === true) {
        this.drawLine(
          this.context,
          this.coordX,
          this.coordY,
          e.offsetX,
          e.offsetY
        );
        this.coordX = e.offsetX;
        this.coordY = e.offsetY;
      }
    });
  }

  listenToCursorUpChanges() {
    this.canvas.nativeElement.addEventListener('mouseup', (e) => {
      if (this.isDrawing) {
        this.drawLine(
          this.context,
          this.coordX,
          this.coordY,
          e.offsetX,
          e.offsetY
        );
        this.coordX = 0;
        this.coordY = 0;
        this.isDrawing = false;
      }
    });
  }

  listenToTouchEvents() {
    this.canvas.nativeElement.addEventListener(
      'touchmove',
      (e) => {
        const touch = e.touches[0];
        const mouseEvent = new MouseEvent('mousemove', {
          clientX: touch.clientX,
          clientY: touch.clientY,
        });
        this.drawLine(
          this.context,
          mouseEvent.clientX,
          mouseEvent.clientY,
          mouseEvent.offsetX,
          mouseEvent.offsetY
        );
      },
      false
    );
  }

  drawLine(context, x1, y1, x2, y2) {
    context.beginPath();
    context.strokeStyle = 'black';
    context.lineWidth = 1;
    context.moveTo(x1, y1);
    context.lineTo(x2, y2);
    context.stroke();
    context.closePath();
  }

Estou usando a função listenToTouchEvents() quando há toques na tela e aparentemente os valores the client x e offset estão corretos e passados para drawLine, mas aparentemente ainda tem algo errado e meu canvas não está sendo pintado.
Answer: Creio que tenha faltado escutar alguns outros eventos de touch. Você pode fazer uma leitura da seguinte referência MDN: Touch events.
Para entender melhor o problema eu apliquei seu código aqui e testei via devtools do Microsoft Edge. Realmente o touch não funciona. Então fiz a seguinte alteração:
listenToTouchEvents() {
  this.canvas.nativeElement.addEventListener('touchstart', (e) => {
    const touch = e.touches[0];
    if (touch) {
      this.coordX = touch.clientX;
      this.coordY = touch.clientY;
      this.isDrawing = true;
    }
  });

  this.canvas.nativeElement.addEventListener(
    'touchmove',
    (e) => {
      const touch = e.touches[0];
      // desenha desde a coordenada inicial/anterior
      // até o touch atual
      this.drawLine(
        this.context,
        this.coordX,
        this.coordY,
        touch.clientX,
        touch.clientY
        );

        // o ultimo local do touch atual para uso no proximo movimento
        this.coordX = touch.clientX;
        this.coordY = touch.clientY;

    },
    false
  );

  this.canvas.nativeElement.addEventListener('touchend', (e) => {
    if (this.isDrawing) {
      this.isDrawing = false;
    }
  });
}

Realmente o que falta é iniciar o touch com touchstart, efetuar pequena alteração no touchmove e também fazer o touchend.
Ah! Não esqueça de chamar o método listenToTouchEvents no ngAfterViewInit.
Na minha resposta não tratei o evento touchcancel, mas conforme o artigo que referenciei acima, é importante tratar esse evento para quando, por exemplo, o touch do usuário vai pra UI do navegador.
Após essas alterações, passei a conseguir desenhar via touch no devtools do Microsoft Edge.


Change markup of single form field

Question: I have constructed a form manually using the Form API. I have one field in particular that needs to have it's markup changed a tad.
The #prefix/#suffix output should come immediately before/after the input control. I think the output currently looks like:
Can I override the themeing for a single field using something like:
$form['control'] = array(
  '#theme' => 'control_field',
  '#title' => 'Some title',
  '#type' => 'textfield'
);

Do I then implement MYTHEME_custom_theme in the templates.php???
Do you know of any exmaples I might use?
I tried adding:
function theme_control_field($variables) {

}

This did not seem to work...also I need control over all the markup for this field not just the field control but I need to relocate the prefix/suffix output as well!?!
Regards,
Alex
Comment: Did you clear the cache first? I believe you need to do so when new functions are added to a module or theme.
Comment: I did yes...

I don't understand why only the  element is removed when I add the '#theme' element to $form array -- I assumed the whole thing would be blanked (prefix, suffixe, title, description, etc) but those seem to still render -- just without the
Answer: You can have a complete custom HTML for a particular field by defining a #theme and setting #theme_wrappers with an empty value.
$form['control'] = array(
  '#title' => 'Some title',
  '#type' => 'textfield'
  '#theme' => 'YOURMODULE_control_field',
  '#theme_wrappers => array(),
);

Then Drupal needs to know about this new theme by implementing the HOOK_theme. You can either work with a template file or generate the HTML within the theme callback function
function YOURMODULE_theme()
{
    return array(
        'YOURMODULE_control_field' => array(
            'template' => 'templates/control-field', // if you want to have a tpl file, templates/control-field.tpl.php using the $element variable for your textfield element
            'render element' => 'element',
        ),
    );
}

// If you dont want to use the template file
function theme_YOURMODULE_control_field($variables)
{
    $element = $variables['element'];
    // $element is here your form textfield element, this function return HTML to generate
}

Comment: Excellent...I managed to achieve my desired effect by hooking MYTHEME_form_element() changing the markup on that one field and using default rendering on others but I still wanted to know how the above was possible so much appreciated. :)

Change markup of single form field


Copy within multiple folders

Question: I currently have the following code on the command line for i in *.wav; do cp text.txt $i.txt; done which copies a text file for each wav file, but renames the text file so that it matches the wav file. Is there a way to do this for multiple folders within one directory at once?
Answer: You can use find for that:
find your_folder -name '*.wav -exec cp text.txt {}.txt \;

This will create text files for all WAVs in your_folder.
Comment: Thank you. Unfortunately, my backslash key isn't currently working, so I can't test this. I do have an additional question. Each of the text files is labeled for the folder name (which is a number between 0 and 51). Can I write a regex for the name of the text file? `/[0-9]?[0-9]/.txt`
Comment: You might try starting a bash subshell with readline editing disabled: `bash --noediting`. This will allow you to work with backslashes if there's a problematic keybinding.
Comment: Also, I'm not clear on the regex comment, but, e.g.  `touch {0..51}.txt` would create .txt files from 0 to 51.
Comment: The text files already exist. So, there is a directory called "WavFiles" and then there are subdirectories numbered 0 through 51, and within those folders, there are text files that have the same name as the folder. As such, I'm trying to write a command that will copy that text file (the name will change) within each folder for a given directory.
Comment: I can finally type a backslash! I tried this command with a regex and it doesn't seem to work.

Copy within multiple folders


How to clean a tuba thoroughly

Question: A tuba is quite large, and can be quite a challenge to clean thoroughly on both inside and outside. I need some good advice on how to do this properly without harming the mechanisms.
Comment: See also [How to disassemble a tuba for cleaning](http://music.stackexchange.com/q/12039/249).
Answer: This is for a piston-valve tuba, by the way, not a rotary valve. Also keep in mind to do this all very gently, tubas scratch easily.
You'll want to take it completely apart (valves out too, and remember how it goes together) and set in a bath tub full of warm/hot water. Then, add some soap (mild, non-abrasive) and rub it gently with a cloth to get off grime (If it was particularly dirty inside, you could try a toilet scrubber(new) and gently clean out the bell (or use a cloth preferably if your arm is small enough), and use the snake to clean out the finer tubing. Make sure to clean the snake often so you just don't spreak the grime). Once it has been scrubbed, drain the tub and then rotate it head-over-heel a few times to get all of the water out and set it on a bath towel to dry. While that is drying, place the slides in the soapy water and rub them gently with a paper towel / cloth, then dry them off and set them somewhere safe. To clean the valves,take off the felt and rubber bumpers and wash them in SOAP-FREE water, and don't use the snake to clean out the holes in the valves. When all parts are COMPLETELY dry, you can begin assembling your tuba. Reassemble the valves(IN THE SAME ORDER THEY CAME OUT), making sure to put on plenty of valve oil, and grease up the slides before you put them in also. (put on the grease with a paper towel, you're not supposed to contact the slide because it can deteriorate the metal)
Another tip, the valves should be cleaned about every month or two, but missing a cleaning here or there won't hurt too bad.
Comment: Warning: I totally screwed the lacquer of a trumpet with warm water! Surely the size of the instrument does not matter here.
Comment: Clarification of @Gauthier's comment: Lacquer is not water-soluble; it will however crack or peel in hot water, mostly because the metal underneath it expands with the temperature while the lacquer generally does not. So, when bathing a brass instrument, you should generally use lukewarm water for both the wash and rinse; that will generally avoid any problems with the metal swelling or shrinking rapidly.
Comment: I'm supposing this applies to all piston-valve instruments...
Answer: For a rotary-valve tuba, the process is slightly different because the rotary valves cannot be  removed from their housings (unlike piston valves). However, the basic idea is the same:

Draw a lukewarm bath of water into the tub. Add a mild hand soap to aid cleaning; DO NOT use dish detergent (you'll never get it back out of the rotaries no matter how much you rinse)
While the tub is filling, remove any felt, leather, cork or other not-waterproof pieces from the instrument and place them aside; also, remove all the tuning slides, to allow water to get into those pipes easier.
Immerse the tuba completely into the water, and let it soak for a few minutes.
Using a snake, brush out the lead pipe, the valve pipes, and the passages through the rotary valves (brush through the rotary valve from both sides of the valve tubing, with the key depressed); these are the places that get the most crud built up over time.
Make sure to soak and brush out the tuning slides themselves as well (but don't soak any tuning slide with a "water key"; you can degrade the cork).
With a washcloth (nothing too abrasive), scrub inside the bell.
Remove the tuba from the bath, and rotate it end over end several times to make sure all the water drains out of all the loops in the piping.
Towel-dry everything you can get to, and let it air-dry for a few hours. Work the valves every so often to work as much water out of the action as possible.
Re-grease all the tuning slides, and add some valve oil to the valve tubes while fluttering the keys, to let the oil contact the surfaces of the valves.
Reassemble the instrument, reinserting all tuning slides.

More often than bathing your tuba, you should boil the mouthpiece. This is more like a biweekly thing if you play a lot, especially if you don't have the chance to brush your teeth or at least rinse your mouth before beginning to play. This process is simple; bring a pot of water deep enough to fully submerge the mouthpiece up to a boil, and using a pair of tongs or some similar apparatus, lower the mouthpiece into the boiling water. Boil for about 5 minutes, to loosen the gunk and grime, then remove it and run it under lukewarm water until the mouthpiece is cool enough to handle. Then, run through the throat and backbore with a mouthpiece brush. Rinse, then repeat if desired, as necessary to clean out all the gunk, before letting the mouthpiece air-dry completely.
Comment: About boiling the mouth piece; I have a plastic type mouth piece. Is it OK for the plastic to boil? I guess the plastic these mouth pieces are quite robust, but I just ask...
Comment: I wouldn't leave it too long in the boiling water if it's plastic. Most of the ones I've used have been silver-plated copper/brass.
Comment: Buy a metal mouthpiece. Also, in relation to rotary valves, see my answer re: ultrasonic cleaning. They'll remove the rotary valves and clean them separately because they're a little more delicate.
Answer: Alternatively, find a music store with an ultrasonic cleaner; the one I worked at would do tubas for around $175. We recommended that, in addition to cleaning it yourself every 4-6 weeks, ultrasonically cleaning once a year.

How to clean a tuba thoroughly


$X^*$ is separable then $X$ is separable [Proof explanation]

Question: $X^*$ is separable then $X$ is separable
Proof:
Here is my favorite proof, which I think is simpler than both the one suggested by David C. Ullrich and the one I had given earlier, elaborating on David Mitra's hint. It uses only the Hahn–Banach theorem, but not Riesz's lemma. It is based on the hint presented in Exercise 5.25, Folland (1999, p. 160).
If $X^*$ is separable, let $\{f_n\}_{n\in\mathbb N}$ be a countable dense subset of it. By the definition of the operator norm $$\|f_n\|\equiv\sup_{\substack{x\in X\\\|x\|\leq 1}}|f_n(x)|,$$ it is possible, for each $n\in\mathbb N$, to choose some $x_n\in X$ such that $\|x_n\|\leq 1$ and $$|f_n(x_n)|\geq\frac{1}{2}\|f_n\|\tag{$\clubsuit$}$$ (if $f_n=0$, then simply choose $x_n=0$; if $\|f_n\|>0$, use the definition of the supremum).
Let $C\equiv\{x_1,x_2,\ldots\}$. I claim that $\operatorname{span} C$ is dense, which implies that $X$ is separable (see the last claim in my previous post). To see this, suppose, for the sake of contradiction, that $\operatorname{span} C$ is not dense; then $Y\equiv\overline{\operatorname{span} C}$ is a proper closed subspace. By the Hahn–Banach theorem, it is possible to choose $f\in X^*$ such that
\begin{align*}
f(y)=&\,0\quad\forall y\in Y,\\
\|f\|=&\,1;
\end{align*}
see again Theorem 5.8(a) in Folland (1999, p. 159). Since $\{f_n\}_{n\in\mathbb N}$ is dense in $X^*$, there exists some $n\in\mathbb N$ such that $\|f_n-f\|< 1/3$. But then
\begin{align*}
|f_n(x_n)|=|f_n(x_n)-\underbrace{f(x_n)}_{=0}|\leq\|f_n-f\|<\frac{1}{3},\tag{$\diamondsuit$}
\end{align*}
whereas
\begin{align*}
1=\|f\|\leq\|f-f_n\|+\|f_n\|<\frac{1}{3}+\|f_n\|,
\end{align*}
so that $\|f_n\|>2/3$. Putting this into ($\diamondsuit$),
$$|f_n(x_n)|<\frac{1}{3}<\frac{1}{2}\|f_n\|,$$ which contradicts ($\clubsuit$).

I don't understand the part apply Hahn Banach Theorem. This part in special:
$\begin{align*}
f(y)=&\,0\quad\forall y\in Y,\\
\|f\|=&\,1;
\end{align*}$

Can someone clarify me that part in special? Thanks for answer!
The answer is of this post: Showing $X^*$ is separable implies $X$ is separable using the Riesz lemma
Answer: Take a bounded linear functional $f \in Y^{\ast}$ s.t. $f\vert_Y = 0$. Then choose some $u \in X \setminus Y$ with $\Vert u \Vert = 1$ (which exists since $Y$ is proper), define $g \in (Y \oplus \mathbb{C}u)^{\ast}$ via $g(u) = 1$ and $g\vert_Y = f$ and extend linearly.
Then we have $\Vert g \Vert = 1$, since for every $x \in X$ with $\Vert x \Vert = 1$ we either have $g(x) = 1$ or $g(x) = 0$. Hence Hahn-Banach gives an extension $G \in X^{\ast}$ s.t. $\Vert G \Vert = \Vert g \Vert = 1$ and $G \vert_Y = g \vert_Y = f = 0$.

The above uses the norm preserving version of Hahn-Banach. But really, you only need any extension of the above defined $g$. Then you can you may rescale, and since $g\vert_Y = 0$, the rescaled $g$ is also $0$ on $Y$. The sublinear functional used for this would be $x \mapsto \Vert g \Vert \cdot \Vert x \Vert$.
Comment: What is for you $\mathbb{C}u$ ? thanks for your answer
Comment: The subspace spaned by $u$. Maybe the notation $\langle u \rangle$ is more standard.
Answer: Take $u\in X\setminus Y$ and define $f:Y\oplus \langle u\rangle\to \mathbb F$ by $f(y+cu)=c$. We can apply the Hahn-Banach theorem once we prove that $f$ is bounded. For this, use the fact that $Y$ is a closed subspace of $X$ so that there is a $\delta>0$ such that $\|y-u\|>\delta$ for all $y\in Y.$ Then, the claim follows from the calculation $\|y+cu\|=|c|\cdot \left \|\left(\frac{-1}{c}\right)y-u\right \|>c\delta.$
Answer: You only need the existence of a non-zero bounded linear functional on the quotient normed space $X/Y$, because composing it with the quotient map $X \rightarrow X/Y$ and then rescaling will give you the desired $f$.


How do I count elements in a while loop and apply css class?

Question: I have a repeater from ACF and what I want to is loop and count the items and based on the counted items output a particular css class.
Can I get help so the output of css classes depends on the counted items. For example if there was six items the class would be col-6 etc...
<?php
    if( have_rows('rainbow') ):

    $counter = 0;
    while( have_rows('rainbow') ): the_row();

        // vars
        $name = get_sub_field('name');
        $age = get_sub_field('age');
        $cssClass = 'col';

        for($i = 0; $i < $counter; $i++) {

            if($counter === 6) {
                $cssClass = 'col-lg-4';
            } elseif ($counter == 4) {
                $cssClass = 'col-xl-6';
            }
            else {
                $cssClass = 'col';
            }

        }

        echo '
';
            echo "
" . $name . "
";
            echo "
" . $age . "
";

            echo $counter;

        echo '
';

        $counter++;

    endwhile;

endif;
?>

Comment: why are you using for loop?
Comment: your question is still open, please close this by accepting the answer, this will help to future visitors
Answer: Don't know why are you using for loop here, $i < $counter this condition cant be true because $i and $counter both of them started from 0. so 0 < 0 == FALSE
You just need to remove for loop inside your while loop.
Or, if you are using for loop somewhere else in your code, then you can just move your conditions outside the for loop.
Second Solution:
Second, if you start $counter from 1 then you can achieve your desired result as given example:
<?php
$array = array(1,2,3,4,5,6);
$counter = 1;
foreach ($array as $key => $value) {
    $cssClass = 'col';
    for($i = 0; $i < $counter; $i++) {
        if($counter === 6) {
            $cssClass = 'col-lg-4';
        } elseif ($counter == 4) {
            $cssClass = 'col-xl-6';
        }
        else {
            $cssClass = 'col';
        }
    }
    echo $cssClass."
";
    $counter++;
}
?>

Result:
col
col
col
col-xl-6
col
col-lg-4

Comment: @PaddyGriffin: glad to help u, dont forgot to accept the answer this will help to future visitors.
Comment: I thought this solved my issue, but when I used the code in another project  it didnt work as expected.

In the first project I had this code running in a template part file which was looped through from a foreach loop

In my real project I want to use the above code in template file but not inside of foreach and wondering what needs to happen to get the code to fire correctly.
Comment: @PaddyGriffin: you can change foreach part as u need
Answer: <?php
$counter = 1;
while( have_rows('rainbow') ): the_row();
    // vars
    $name = get_sub_field('name');
    $age = get_sub_field('age');

    if ( $counter == 4 ) {
        $cssClass = 'col-xl-6';
    } elseif ( $counter == 6 ) {
        $cssClass = 'col-lg-4';
    } else {
        $cssClass = 'col';
    }

    echo '
';
        echo "
" . $name . "
";
        echo "
" . $age . "
";
        echo $counter;
    echo '
';

    $counter++;

endwhile;

try this
Comment: thanks for this I updated the code,  i was expecting if the count was 4 the class col-xl-6 would be outputted but it outputs col instead.


Solving $2^x \cdot 5^y = 0,128$

Question: $x,y \in \mathbb Z$
$2^x \cdot 5^y = 0,128$
$x+y = ?$
My attempt:
I know that
$$0,128 = \frac{128}{1000}$$
$$5^3 = 125$$
$$2^{-3} = \frac{1}{8}$$

EDIT:
$2^7 = 128$
Then we need to get
$0,128$
Comment: $2^{-3}=\frac{1}{8}$
Comment: @cansomeonehelpmeout missed it, nice catch.
Comment: Does it help if I point out that $2^7=128$?
Comment: @MJD Now, got it better. The thing is to get $0,128$.
Answer: Hint: $0.128=2^7\times 10^{-3}=2^4\times 5^{-3}$
Comment: How? I truly didn't get what you mean.
Comment: You can find $x$ and $y$ with that.
Comment: Yes, found that! However, I'd be grateful If you explain what you've done.
Comment: $2^x5^y=2^45^{-3}$. So, we have $2^x5^{y+3}=2^4$. As prime decomposition of an integer is unique, $x=4$ and $y+3=0$.
Comment: Hold on, why did you use $5^{-3}$ instead of $10^{-3}$?
Comment: $2^7\times 10^{-3}=2^7\times 2^{-3}\times 5^{-3}=2^4\times 5^{-3}$
Comment: I need prime decomposition to ensure the uniqueness. So we have to use $5$ instead of $10$.
Answer: You know that $128=2^7$, and $1000=10^3=(2\cdot 5)^3=2^3\cdot 5^3$. Therefore
$$0.128=\frac{128}{1000}=\frac{2^7}{2^3\cdot 5^3}$$
Can you do the rest?
Comment: For $1000$, we get $10^3$ hence $\frac{2^7}{10^3}$ and?
Comment: @Enzo, good! Now if you can write $10=2^x\cdot 5^y$ then $10^3=2^{3x}\cdot 5^{3y}$.
Answer: You can write 5 in terms of 10 and 2... so you can write the problem as:
$2^x \cdot (\frac{10}{2})^y=.128$
$2^{x-y} \cdot 10^y=.128$
Find $y$ first and then $x $

Solving $2^x \cdot 5^y = 0,128$


Pass model value from View to controller is not working

Question: My model has two properties, one of them is an object of another class
  public class Association : Entity
{
    public Association()
    {
        this.User = new User();
    }

    public User User
    {
        get;
        set;
    }

    public Role Role
    {
        get;
        set;
    }
};

and my view is strongly typed to this model
@model MuddyBoots.Greenlight.Association
.
.
@using (Html.BeginForm())
{

@Html.ValidationSummary(true)

     @Html.TextBoxFor(model => model.User.FirstName,new { id = "first-name" })
    @Html.ValidationMessageFor(model =>    model.User.FirstName)

    @Html.HiddenFor(model => model.Role, new { id="hiddenRole"})

<input type="radio" name="user-role" id="role-admin" value="01" checked="checked" /> Read only

<input type="radio" name="user-role" id="role-member" value="02" /> Restricted

<input type="radio" name="user-role" id="role-read" value="03"/> Standard

<input type="radio" name="user-role" id="role-subscriber" value="04" /> Administrator

}

my controller function is written like that:
[HttpPost]
    public ActionResult AddUser(Association association)
    {
        string firstName = association.User.FirstName;
        var role = association.Role;

         IRepository<Association> associationRepository = new IRepository<Association>(db);
        if (ModelState.IsValid)
        {
           siteRepository.Update(site);
            return RedirectToAction("Index");
        }
        return View(association);
    }

My problem is: when I post my view, my association object is null, it has no values.
to be more precise, when I try to debug these 2 lines:
 string firstName = association.User.FirstName;
 var role = association.Role;

their values are null, but if I comment the first line, the role variable has a value. So am sensing that the problem is related to the User property, but I do not know how to solve it.
Comment: Where is your post or equivalent button?
Answer: You seem to have used some hidden field for the Role type:
@Html.HiddenFor(model => model.Role, new { id = "hiddenRole" })

But the Role property is a complex type, you cannot serialize it as a hidden field. You will have to use hidden fields for each of the properties you want to be sent:
@Html.HiddenFor(model => model.Role.Property1)
@Html.HiddenFor(model => model.Role.Property2)
@Html.HiddenFor(model => model.Role.Property...)

Also you seem to be using some radio buttons inside your form which are named user-role but you cannot have a property on your Role class with this name (you cannot have dash in a property name), so I guess you will have to use the proper name here if you want the value of those radio buttons to be bound to some property of the Role class on your Association model.
For example let's suppose that your Role class looks like this:
public class Role
{
    public string Value { get; set; }
}

Now your view could look like this:
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

        @Html.TextBoxFor(model => model.User.FirstName, new { id = "first-name" })

            @Html.ValidationMessageFor(model => model.User.FirstName)

                @Html.RadioButtonFor(model => model.Role.Value, "01", new { id = "role-admin" })
                Read only

                @Html.RadioButtonFor(model => model.Role.Value, "02", new { id = "role-member" })
                Restricted

                @Html.RadioButtonFor(model => model.Role.Value, "03", new { id = "role-read" })
                Standard

                @Html.RadioButtonFor(model => model.Role.Value, "04", new { id = "role-subscriber" })
                Administrator

    <button type="submit">OK</button>
}

Answer: I don't think the ModelBinder will bind child objects.  You could create a custom ModelBinder to to bind your Association class or just create a ViewModel class that flattens your current Model into a single class.  So your AssociationViewModel model class might look like this:
public class AssociationViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string RoleName { get; set; }
}

public ActionResult AddUser(AssociationViewModel associationViewModel)
{
    if (ModelState.IsValid)
    {
        var association = new Association
        {
            User.FirstName = associationViewModel.FirstName,
            Role = new Role { Name = associationViewModel.RoleName }
        };

        IRepository<Association> associationRepository = new IRepository<Association>(db);
        ....
    }
 }


do i host react app, node js and mongo db separatly to host my whole website for free?

Question: I have made mern stack website that uses react, node, mongo and API. I want to ask if I want to host my website for free to test its functionalities, should I need to host it separately or can I host it on cpannel ?
and can you recommend me youtube video or document to host mern app to cpannel for free
Answer: You can host your backend with Heroku:
A video for it as you asked (https://www.youtube.com/watch?v=27GoRa4d15c)
There are two ways I prefer to host the frontend:

With netlify
Github pages
Using netlify is easy however using it free will limit hours it can be active monthly or something. But GitHub pages is also free.

https://www.c-sharpcorner.com/article/how-to-deploy-react-application-on-github-pages/
This is a site for deploying on github pages.
And here is a video on deploying with netlify (https://www.youtube.com/watch?v=8KGLOJHqNMg)
Before you judge me on the videos I have not watched them fully so I do not know how good they explain it but you can search on youtube and find plenty of other videos on deploying with these methods if you do not understand from these videos.
Comment: thanks for the videos, but it means I have to host the front end separately and backend separately, is it right?
Comment: @ArjadGohar Yes this is right but this is usually the case however there is one site where you can host all in one place I forgot its name but I will get back to you when i find it
Comment: I found it's name Zeet I haven't used it my self but i have seen others use it
Comment: thank you i will check that, i have one more question if you can help ,
Comment: i have uploaded my front end successfully on bluehost cpannel, and it is running fine, now I have also uploaded backend on node js on capnnel nad dit shows the following( screenshot https://ibb.co/2820Tpb) ,

can you tell me it node js is hosted successfully or not
Comment: @ArjadGohar Try setting up an app.get() to just show a simple hello world or something and you can try accessing the site. If you can access it then it is successful i guess


Finding fixed points via the Jacobian matrix eigenvalues

Question: I'm trying to express a fixed point when x1 and x2 are both not equal to zero for this system of equations. I know that one fixed point is $(0,0)$ when $x_1 = 0$.
$$
\begin{split}
x_1 &= \lambda x_1(1 - x_1) - 0.2x_1x_2 \\
x_2 &= 0.9x_2 + 0.2x_1x_2
\end{split}
$$
Where $\lambda \in (0,3)$ is a scalar. Initially, $x_1^{(0)} = 0$ and $x_2^{(0)} = 1$.
I built the Jacobian matrix A with both equations for $x_1$ and $x_2$. This gives me a $2 \times 2$ matrix
$$A = \begin{bmatrix}-λ-0.2x2&-0.2x1\\0.2x2&0.9+0.2x1\end{bmatrix}$$
When I try finding the eigenvalues of $A$ using $\det(A - \lambda I)$, it doesn't seem to work out.
$$(A - \lambda I) =
\begin{bmatrix}
-\lambda-0.2x_2-\lambda & -0.2 x_1\\
0.2 x_2                 & 0.9 + 0.2x_1-\lambda
\end{bmatrix}
$$
Any ideas what I'm doing wrong?
Answer: You are confusing the constant in your problem with the matrix eigenvalues. Rename the matrix eigenvalues to $\mu$ to get
$$A - \mu I =
\begin{bmatrix}
-\lambda-0.2x_2-\mu & -0.2 x_1\\
0.2 x_2             & 0.9 + 0.2x_1-\mu
\end{bmatrix}
$$
so
$$
\begin{split}
\det (A-\mu I)
 &= -(\lambda+0.2 x_2+\mu)(0.9 + 0.2x_1-\mu) + 0.04 x_1 x_2 \\
 &= (\mu+ \lambda+0.2 x_2)(\mu - 0.9 - 0.2x_1) + 0.04 x_1 x_2 \\
 &= \mu^2 + \mu \left[ \ldots \right] - \ldots
\end{split}
$$
and use the quadratic formula
Comment: @stevetronix please see the last couple of lines in the update
Comment: @stevetronix yes
Comment: Correct, and this results in: $$-0.9λ - 0.2λx1 + λu + 0.18x2 + 0.04x1x2 - 0.2x2u + 0.9u + 0.2x1u - u^2 + 0.04x1x2$$ How can this be factored to solve for u?
Comment: Thanks. So that would be $$u^2 + u[-0.9 - 0.2x1 + λ + 0.2x2] - 0.9λ - 0.2x1λ - 0.18x2$$ with $$a = 1, b = (-0.9 - 0.2x1 + λ + 0.2x2), c = - 0.9λ - 0.2x1λ - 0.18x2$$


C# List implementation... in Java

Question: I'm learning Java and I'm trying to do something I've always done in C#... in Java.
The goal is to wrap the class "MyItem" into a List of "MyItems". This makes it easier to reason about (MyItems is much easier to read/understand than List<MyItem>... or, say, I need to make it something more complicated like IEnumerable<KeyValuePair<string,List<Dictionary<int,bool>>>>... then ask for a MyKVPDictionaries instead of List<IEnumerable<KeyValuePair<...>>>>>).
Just looking around... It seems like C# allows you to keep the default implementations of stuff (Look below, .Add just works).
Looking at Java... is there a way to implement a list as done in c#? Or do I have to manually implement the individual parts of the List manually? (.add, .list, .contains, etc).
Below I have a "basic" implementation of a Class... and a List<Class> in C#.
Is it really that much more work to implement class MyItems implements List<MyItem> in Java or am I missing something to simplify the process?
(The Java code is only the MyItems.java class file with Resharper "Auto Implement missing members" stubs via IntelliJ).
C# version .NetFiddle:
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var myItems = new MyItems();
        myItems.Add(new MyItem("Hello"));
        myItems.Add(new MyItem(" "));
        myItems.Add(new MyItem("World"));
        myItems.Add(new MyItem("!"));

        foreach(var item in myItems)
            Console.Write(item.Name);
    }
}

public class MyItems : List<MyItem>
{

}

public class MyItem
{
    public MyItem(string name)
    {
        Name = name;
    }
    public string Name { get; private set; }
}

Java Version start/stub:
package items;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class MyItems implements List<MyItem> {
    @Override
    public int size() {
        return 0;
    }

    @Override
    public boolean isEmpty() {
        return false;
    }

    @Override
    public boolean contains(Object o) {
        return false;
    }

    @Override
    public Iterator<MyItem> iterator() {
        return null;
    }

    @Override
    public Object[] toArray() {
        return new Object[0];
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return null;
    }

    @Override
    public boolean add(MyItem generatePreSignedUrl) {
        return false;
    }

    @Override
    public boolean remove(Object o) {
        return false;
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        return false;
    }

    @Override
    public boolean addAll(Collection<? extends MyItem> c) {
        return false;
    }

    @Override
    public boolean addAll(int index, Collection<? extends MyItem> c) {
        return false;
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        return false;
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        return false;
    }

    @Override
    public void clear() {

    }

    @Override
    public MyItem get(int index) {
        return null;
    }

    @Override
    public MyItem set(int index, MyItem element) {
        return null;
    }

    @Override
    public void add(int index, MyItem element) {

    }

    @Override
    public MyItem remove(int index) {
        return null;
    }

    @Override
    public int indexOf(Object o) {
        return 0;
    }

    @Override
    public int lastIndexOf(Object o) {
        return 0;
    }

    @Override
    public ListIterator<MyItem> listIterator() {
        return null;
    }

    @Override
    public ListIterator<MyItem> listIterator(int index) {
        return null;
    }

    @Override
    public List<MyItem> subList(int fromIndex, int toIndex) {
        return null;
    }
}

Comment: Generic `List` in java is not a class its an interface. That's why you need to implement all of its members . You can inherit `ArrayList` which implements `List`.  `public class MyItems extends ArrayList`
Comment: "I" ditched you.
Answer: Java's List type is an interface, the counterpart of C#'s IList. You'll have to write most of the methods from scratch if you want to implement it. The counterpart of C#'s concrete List class would be Java's ArrayList:
public class MyItems extends ArrayList<MyItem> {

Comment: Ahh... I knew I was missing something basic. I think that'll get me in the right direction.
Comment: @WernerCD I suggest you familiarize yourself with [the Java API docs](http://docs.oracle.com/javase/7/docs/api/) (This link is for Java 7. I leave it as an exercise to the reader to find the docs for Java 8 if needed.) These docs tell you what names are classes and which are interfaces. Unlike C#, Java programmers typically do not start interface names with `I`.
Comment: Yeah, that was going to be my next question... C# and Java are very similar... but very different. I have a good basics book but was trying to do something beyond where I'm at in Java. I'll admit, I wouldn't have considered IList/List vs List/ArrayList. It doesn't help that the terminology is different and ArrayList is an older version of a List in C# (List is generic and ArrayList is objects).
Comment: @WernerCD `ArrayList` is generic since Java 5.
Comment: @Code-Apprentice Oohhhhh.... Difficult exercise: Replace `7` with `8` in the URL... Tough assignment you gave there. ;-)
Comment: @Andreas Don't laugh, [replacing is tricky](https://stackoverflow.com/q/12734721/1553851).
Comment: @WernerCD All of the Java Collections API is generic since Java 5. Even the antiquated `Vector` which no one should use any more.

C# List implementation... in Java


Maxmind geoipupdate mmdb.gz is not a valid gzip file

Question: I'am try to update my GeoIP Databases using the geoipupdater.
Using the following ProductIds
ProductIds GeoIP2-City GeoIP2-Connection-Type GeoIP2-Country GeoIP2-ISP

Geoipupdate Version 2.3.1 is installed
geoipupdate -V
geoipupdate 2.3.1

When I run the geoipupdate the City and Country Databases are getting updated/downloaded. But for the ISP and Connection-Type Updates I got the following output from the updater.
url: https://updates.maxmind.com/app/update_secure?db_md5=00000000000000000000000000000000&challenge_md5=0926a7ab0bf38eafe43622a25fd6e7e2&user_id=*****&edition_id=GeoIP2-Connection-Type
/usr/share/GeoIP/GeoIP2-Connection-Type.mmdb.gz is not a valid gzip file

url: https://updates.maxmind.com/app/update_secure?db_md5=00000000000000000000000000000000&challenge_md5=0926a7ab0bf38eafe43622a25fd6e7e2&user_id=*****&edition_id=GeoIP2-ISP
/usr/share/GeoIP/GeoIP2-ISP.mmdb.gz is not a valid gzip file

Why are the downloaded .gz files aren't valid?
thanks in advance!
Comment: I'd suggest that you contact email@example.com
Answer: I got the same error, but the reason was an expired subscription.
/my_path/data/GeoIP2-City.mmdb.gz is not a valid gzip file

I'd suggest you call the URL generated by geoipupdate to see the "real error".
curl -i "https://updates.maxmind.com/app/update_secure?db_md5=00000000000000000000000000000000&challenge_md5=f2d60fa3afdaa26b18dd94457a999999&user_id=******&edition_id=GeoIP2-City"

HTTP/1.1 200 OK
Date: Tue, 21 Feb 2017 08:38:13 GMT
Content-Length: 59
Content-Type: text/plain; charset=utf-8

Invalid product ID or subscription expired for GeoIP2-City


Equivalent Key Signatures

Question: I've noticed that a variety of pieces in the classical repetoire (certainly at least the piano repetoire), label what seems to be effectively the same key signature differently. That is, I am not aware of any differences in terms of key between a piece in "G Sharp major" and "A flat major" (or their equivalent minors). Is there any reason that sometimes a sharped key signature is used while at other times the equivalent flatted key signature is used?
As a related point, I have undoubtedly noticed the preference of certain "equivalent" key signatures over others. For example, one encounters "E flat" significantly more than "D sharp" and likewise "C sharp" significantly more than "D flat". Is there any particular reason for this, or is it simply a convention that has been handed down to use through musical history?
Answer: The short (and oversimplified) answer is: Because Ab Major has fewer flats than G# Major has sharps, and thus it's easier for musicians to read.  This becomes especially apparent with keys such as D# Major, which has a double-sharp in it---the seventh note of the D# Major scale is not D, but Cx (that's "C double-sharp").
The longer and more accurate answer is that these keys are not in fact equivalent.  Only in an equal-tempered tuning system do G# and Ab have the same pitch, Eb and D# have the same pitch, etc.  That is, only in equal temperament do enharmonically equivalent notes actually have the same pitch.  In every other tuning system, the enharmonically equivalent notes are slightly (but definitely noticeably) different from each other.  If you've only been exposed to fixed-pitch instruments such as the piano and the guitar, this concept can be challenging at first, but violinists, wind, and brass players know that their intonation depends on the context of the key in which they're playing.
This in turn leads to different keys having different sonic characteristics.  In the modern, equal-tempered era, we've mostly lost these distinctions, but to composers of two hundred years ago and more, the keys of Ab and G# didn't sound the same at all, and they would compose to a specific key in order to take advantage of its particular character.
Update: In response to Brian's comment, I thought it would be helpful to post an example.  Here are links to YouTube videos, all three of which were posted by the same person, using the same synthesizer, all three playing Bach's Air on the G String.  But each link uses a different tuning system:

Equal Temperament: http://www.youtube.com/watch?v=c6XkgNT20Eg
Just Intonation: http://www.youtube.com/watch?v=gdL8aPQUOk0
Pythagorean Tuning: http://www.youtube.com/watch?v=hq-SrgV7_Ow
Comment: Good answer: consider also that pieces with key changes in the middle are often set up so that the different keys are related in some way. This often necessitates the use of one key over the enharmonic spelling.
Comment: And in that time, I decided to ask that as [a separate question](http://music.stackexchange.com/questions/2993/examples-of-songs-or-phrases-played-in-different-temperaments) rather than just a comment. Perhaps you could provide your update as an answer to that question.
Comment: Thanks for the great answer. Equal temperement does indeed seem to be the key here! As a piano player, one just wouldn't generally notice it without having been taught music history/theory.
Comment: Yes, before equal temperament a work played in G# and any *other key* would sound different (different intervals between scale notes), but G# and Ab are identical keys on a keyboard, producing identical pitches. You are essentially arguing that, after playing a piece in G#, keyed instruments would be re-tuned before playing in Ab. Is there evidence that that was actually done?
Comment: @SteveClay It's not so much that performers would retune to play in Ab as it is that they would choose a program of pieces in related keys and then have the harpsichord tuned (or more likely, tune it themselves) so that all the pieces in that program would sound pretty good. In fact, performers playing in period style continue this practice to this day.
Comment: Interesting! So do you know if certain keys are chosen by the composer because of the common intonation choices of the performers?
Answer: There is a strong case for certain enharmonic key uses
depending on the mode (minor/Major).
These four little tables show that Eb is significantly
easier to write than D# for a major scale as
the latter would involve double sharps in the signature.
But F# and Gb Major are really close in complexity.
Major scales
Number of #s (upper lines) versus enharmonic number of bs

Number of bs (upper lines) versus enharmonic number of #s

Likewise C# minor is to be prefered to Db minor
but D# and Eb are interchangeable and this is indeed
what Bach did in its Well Tempered Keyboard (Preludium 8 and Fugue 8, BWV 853). He used
one for the prelude and the other for the fugue (See Alex Basson's answer about the validity of this substitution).
Minor scales
Number of #s (upper lines) versus enharmonic number of bs

Number of bs (upper lines) versus enharmonic number of #s

It explains that one favor keys that are practical in both modes
especially in styles when it is frequent to make modulations
or to switch between modes, such as variations.
Comment: Okay, so this seems pretty logical: using a fewer number of accidentals in the key signature. I think this is more or less the best reason. :-)
Comment: Ah, I knew enharmonic was the fancy theoretical term I was looking for! Looks like a good reply, but I'm about to doze off here, so will read tomorrow.
Comment: I think it's important to say, though, that Bach was trying to make a point with the Well-Tempered Clavier.  Up until that time, musicians did not consider D# and Eb interchangeable, as indeed they are not unless one is using equal temperament.
Comment: Also, I find the tables a bit confusing.  The first one, for example, seems to imply that Ab Major, say, has 4 sharps.  I can only assume that you mean to say that Ab has four altered notes (all flats) while its enharmonic equivalent, G#, has eight altered notes (all sharps).
Comment: Regarding "He used one for the prelude and the other for the fugue"... which BWV?
Comment: @Alex: I agree with your comment and your answer. I did not repeat the point about the equal temperament because you made it already and it was in the context of the piano literature but I have edited my answer. You correctly interpreted the tables but I have also added a few words to explain their meaning. I hope they will be less confusing that way.
Answer: This is a great question that is subtlely different from the usual "what is the difference between A♭ and G♯?" Apart from frequency differences in non-12-et tunings, that question relates to the function of the note within the chord/scale/key.
But if we're talking about choice of key, then there are other factors at work. Obviously in non-12-et tunings, the choice of A♭ major vs G♯ major does have to do with how it will sound. But let's assume 12-et for the rest of this answer.
There are three general factors that, I would have thought (but see below about Bach), led a composer in the common practice era to choose one key over another enharmonic one:

avoid double sharps and double flats in the key signature itself
reduce double sharps and double flats in the keys to be modulated to
reduce double sharps and double flats in the keys used by transposed instruments

As others have mentioned, the Well-Tempered Clavier is interesting here. The point of the piece was to demonstrate the 12-major and 12-minor keys on an instrument where enharmonic notes have the same frequency. So frequency-wise there really can only be 12 major keys.
But from a naming point of view (assuming you wouldn't be as crazy as to have double sharps or double flats in your tonic) you have 21 possible key names for each of major and minor.
How would one go about choosing which 12 key names out of 21 to use? First step might be to avoid double sharps and double flats in the key signature itself. Note that the result is different between major and minor keys (as WTC demonstrates). That reduces your choice from 21 to 15 (so G♯ D♯ A♯ E♯ B♯ F♭ majors are out)
Then it likely just comes down to what you're going to modulate too. If you are going to modulate to V, you might want to avoid having to introduce the double-sharp to do so (which means C♯ major is out). If you are going to modulate to V of V, then F♯ might be out too).
All that said, it makes it particular interesting that WTC does use C♯ major and F♯ major and instead eschews D♭ G♭ C♭ to get from 15 possibilities to 12. The C♯ major prelude and fugue does indeed need a double-sharp in modulated passages, even though the note is diatonic.
In the case of ensemble pieces with transposing instruments: imagine a clarinet part in concert C♯ major :-)
Comment: Thanks for the answer. I think your justification is pretty good, in general, though it is interesting how seemingly common C# major is as a key signature... WTC is far from the only example. What do you mean by modulate btw? I haven't encountered this term before in music.
Comment: Modulation is the process of changing the key within a piece (e.g. from the tonic to the dominant). See [en.wikipedia.org/wiki/Modulation_(music)](http://en.wikipedia.org/wiki/Modulation_(music)) for a lot more information.
Comment: I've cleaned up the comments.
Answer: Some of the answers have touched upon convenience for the player, but have missed one point about this. In making arrangements band and orchestral arrangements, I have found that wind players often prefer sharps to flats, preferring for example 7 sharps over 5 flats. This is noticeable particularly with transposing instruments. String players, on the other hand, seem to prefer flat keys to sharp ones.
Comment: -1: As a wind specialist, I will say that wind bands universally prefer flat keys over sharp keys. Many band instruments are keyed in Bb or Eb, which makes concert Eb the overwhelmingly popular band key in middle-school level ensembles.
Comment: @Colin, I fully understand how key signatures translate for transposing instruments; my issue is that I think you've got the instrument families mixed up. The other comments above seem to agree with this (also given that string instruments' open strings are the roots of sharp scales), and my personal experience as a wind instrumentalist and educator contradicts what you have suggested in your answer.
Comment: Do you know why this preference exists?
Comment: @Matthew: this is not strictly true about string players, but certain sharp keys can be awkward, especially in linked arpegio, and do not resonate well with open chords but the difference blurs when you progress in skill. Double-bass players have different tastes than violin/viola/cello because they have a different tuning.
Comment: I always anecdotally thought string players preferred sharps. Not sure where I picked up that impression, though.
Comment: @NReilingh - you are missing the point. The instruments are keyed in Bb or Eb, so their parts will have two or three more sharps (or two or three fewer flats) than concert. If a piece is in D, say, an Eb part will be in five sharps. What I'm saying is that wind players do not seem to be too unhappy with five sharps. I think your downvote is unwarranted.
Comment: Wind players get accustomed to sharp key signatures, because Bb and Eb instruments read two or three more sharps than the real key.  And a composer or copyist preparing a clarinet or sax part will naturally transpose "up one" unless it leads into an impenetrable forest of double (or even triple) sharps.

Because of this, we need not worry if an alto sax part ends up in 7 sharps, with a smattering of double sharps - they're used to it! But equally, we don't have to protect a wind player from flats. They're no problem for anyone but an absolute beginner, really!
Comment: Re Colin's answer - you never defined whether the key was the key of the piece, or the key the instruments part is written in to compensate. E.g. if the tune is basically in G maj., the trumpet part would be written in A .My experiece says that horn players prefer to read in flats, whereas guitarists prefer sharps - every open string on a guitar is the tonic of a # key, and it's maybe easier to sharpen a guitar note than flatten it, but brass players find it easier to flatten notes.
Comment: Sorry, Tim, but that really is rubbish. I'm a brass player. There's a valve combination (or trombone slide position) for each note. (OK, sometimes a choice of several.) You put down those valves, you blow the note. That's it. We don't take an E and flatten it, we just play Eb. And, although a violinist may initially learn open notes, then add other notes with a shift from that base position, I'm sure it isn't long before they just see the note - put a finger in the right place. You can over-think this sort of thing!

Equivalent Key Signatures


Como obter o tempo em segundos de uma data no formato string?

Question: Sei que a função time(0) me retorna os segundos desde o dia primeiro de janeiro de 1970, no caso o usuário entraria com uma data (dd-mm-aaaa ou em qualquer formato por motivo de limitação do sistema) e o sistema faria a verificação de qual data é mais antiga.
Há bibliotecas que trabalhem com isso? Qual seria a melhor maneira de passar uma data para o sistema para transforma-lo em segundos?
Answer: Existe esta struct que serve para manipular datas.
Acho que o que você deseja é algo desse tipo:
#include <stdio.h>
#include <time.h>

int main()
{
    struct tm tm = {};  // inicializa com zeros
    int dia, mes, ano;

    scanf(" %2d-%2d-%4d", &dia, &mes, &ano);
    tm.tm_mday = dia;
    tm.tm_mon  = mes - 1;
    tm.tm_year = ano - 1900;

    time_t tempo = mktime(&tm);
    puts(asctime(&tm));
    printf("%d\n", tempo);
}

Comment: Excelente, exatamente isso, mt obrigado!


How to open url as "chrome-extension" in web page?

Question: I have one web page and one chrome extension, how can I open url like this chrome-extension://chrome-id/page.html. Here is my code:
<code> $(document).on('click', '#btnOpenChromeExtension', function () {
    window.open("chrome-extension://chrome-id/webpage.html", "_blank");
 });
</code>
But when click, it open new tab in blank page with url is: about:blank. How can I open link is chrome-extension ?
Comment: Does it work (or do something else) when you leave out the second parameter? From w3schools: _blank - URL is loaded into a new window. This is default

so there's no need to specify it. Still a strange situation... Does the URL you supply lead to the extension when you paste it into the address bar manually?
Comment: @NilsO It work normaly with url contains "http", but it seem to be not work with url contains "chrome-extension"
Answer: This is restricted due to the extension policies. You need to add to the extension's manifest.json file the following:
<code>{
    ...
    "web_accessible_resources": [
        "page/mypage.html"
    ],
    ...
}
</code>
Of course, this must be your extension. This is the only way I know to make it work.
Answer: Try this:
<code>$(document).on('click', '#btnOpenChromeExtension', function () {
      window.location.href = "chrome-extension://chrome-id/webpage.html";
      //        OR
      window.location.replace("chrome-extension://chrome-id/webpage.html");
});
</code>
Comment: Nope. You can't normally open `chrome-extension://` or `chrome://` pages due to security restrictions, and this will not work.
Comment: @xan i remember you answered recently this could be done with tabs instead of window.open
Comment: @ZigMandel Correct. "Normally" here means "with methods available to webpages".
Comment: @sorryxi wasnt commenting on that but on the fact that the tabs thing isn't mentioned anywhere and seems to be better than the current 2 answers.