text:
Q: excel Worksheet_SelectionChange - copying data Scenario:
I have two worksheets the same except for "some content" in Sheet2 column C-E, and Sheet1 containing a Worksheet_SelectionChange handler
When I click on column B in Sheet1 the Worksheet_SelectionChange changes the cell colour and then sets column C-E to that of Sheet2 Column C
Problem:
Trouble is it falls over on an application error...
Can anyone help please, this is really annoying...just how do i copy the data from Sheet2 to Sheet 1 in a Worksheet_SelectionChange handler?
If I set S1C = "X" (as in hardcoded it's fine), its when I try to reference the cell from the second sheet that it doesn't work.
many thanks in advance,
Best regards
Code as follows:
Public benRel
Public rskOpt
Public resOpt
Public getRow
Public getCol

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

On Error GoTo ExitSubCorrectly
'turn off multiple recurring changes
Application.EnableEvents = False

'do not allow range selection
If Target.Cells.Count > 1 Then GoTo ExitSubCorrectly

'only allow selection within our range
Set myRange = Range("B8:B24")
If Not Application.Intersect(Target, myRange) Is Nothing Then
    ' At least one cell of Target is within the range myRange.
    ' Carry out some action.

    getRow = Target.Row
    getCol = Target.Column

    Select Case Range(Cells(Target.Row, Target.Column), Cells(Target.Row, Target.Column)).Style

        Case "Normal"
            Range(Cells(Target.Row, Target.Column), Cells(Target.Row, Target.Column)).Style = "Accent1"

            getData
            putData

        Case "Accent1"
            Range(Cells(Target.Row, Target.Column), Cells(Target.Row, Target.Column)).Style = "Normal"
            Range(Cells(Target.Row, Target.Column + 1), Cells(Target.Row, Target.Column + 3)).Value = ""

        Case Else

    End Select

Else
    ' No cell of Target in in the range. Get Out.
    GoTo ExitSubCorrectly
End If

ExitSubCorrectly:
' go back and turn on changes
' MsgBox Err.Description
Worksheets("Sheet1").Select
Application.EnableEvents = True

End Sub

Sub getData()

Worksheets("Sheet2").Select
Range(Cells(getRow, getCol), Cells(getRow, getCol)).Select
benRel = Range(Cells(getRow, getCol), Cells(getRow, getCol)).Offset(0, 1).Value
rskOpt = Range(Cells(getRow, getCol), Cells(getRow, getCol)).Offset(0, 2).Value
resOpt = Range(Cells(getRow, getCol), Cells(getRow, getCol)).Offset(0, 3).Value

End Sub

Sub putData()

Worksheets("Sheet1").Select
Range(Cells(Target.Row, Target.Column), Cells(Target.Row, Target.Column)).Offset(0, 1).Value = benRel
Range(Cells(Target.Row, Target.Column), Cells(Target.Row, Target.Column)).Offset(0, 2).Value = rskOpt
Range(Cells(Target.Row, Target.Column), Cells(Target.Row, Target.Column)).Offset(0, 3).Value = resOpt

End Sub

A: it looks to me like you could replace all three routines with
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

   On Error GoTo ExitSubCorrectly
   'turn off multiple recurring changes
   Application.EnableEvents = False

   'do not allow range selection
   If Target.Cells.Count > 1 Then GoTo ExitSubCorrectly

   'only allow selection within our range
   Set myRange = Range("B8:B24")
   If Not Application.Intersect(Target, myRange) Is Nothing Then
      ' At least one cell of Target is within the range myRange.
      ' Carry out some action.
      With Cells(Target.Row, Target.Column)
         Select Case .Style

            Case "Normal"
               .Style = "Accent1"
               .Offset(0, 1).Resize(, 3).Value = Worksheets("Sheet2").Cells(getRow, getCol).Offset(0, 1).Resize(, 3).Value
            Case "Accent1"
               .Style = "Normal"
               .Offset(0, 1).Resize(, 3).ClearContents
            Case Else

         End Select
      End With

   End If

ExitSubCorrectly:
   ' go back and turn on changes
   ' MsgBox Err.Description
   Application.EnableEvents = True

End Sub


text:
Q: Conditionally convert column data type from float to double precision I have redesigned my Firebird based SQL database. As part of this process I created new table named HARMONICS. Using GUI based administration tool I created following columns:
HARM_LP_ID Integer NOT NULL
HNUMBER Integer NOT NULL
HAMPCHNL0 Double precision
HAMPCHNL1 Double precision
HAMPCHNL2 Double precision
HAMPCHNL3 Double precision
HAMPCHNL4 Double precision
HAMPCHNL5 Double precision
HPHCHNL0 Double precision
HPHCHNL1 Double precision
HPHCHNL2 Double precision
HPHCHNL3 Double precision
HPHCHNL4 Double precision
HPHCHNL5 Double precision

After that I inserted into new entities some test data. The changes included also other tables, but these are not related to my problem so I will not list them here. Then I customized my application in order to work with new structure of relational database.
When application was fully tested I enhanced utility named Upgrader. The task of Upgrader is to convert between various versions of SQL databases. To accomplish this task I wrote SQL script. Following erroneous guides on official Firebird site (http://firebirdsql.org/manual/migration-mssql-data-types.html) I wrote following command for creating above mentioned table:
CREATE TABLE HARMONICS
(
  HARM_LP_ID Integer NOT NULL,
  HNUMBER Integer NOT NULL,
  HAMPCHNL0 Float,
  HAMPCHNL1 Float,
  HAMPCHNL2 Float,
  HAMPCHNL3 Float,
  HAMPCHNL4 Float,
  HAMPCHNL5 Float,
  HPHCHNL0 Float,
  HPHCHNL1 Float,
  HPHCHNL2 Float,
  HPHCHNL3 Float,
  HPHCHNL4 Float,
  HPHCHNL5 Float,
  CONSTRAINT PKHARMONICS1 PRIMARY KEY (HARM_LP_ID,HNUMBER)
);

I thought that Firebird data type "Float" is double precision float (the same as data type "double" in C). I eventually found that I was wrong but this was after I created official release of Upgrader utility. So now I have two versions of databases in circulation - one with single precision floating point numbers and second with double precision floating point numbers.
I am searching for SQL script that would check actual data type of columns in table HARMONICS. If this is double precision then script would do nothing. If this is single precision, script would convert columns with data type "Float" to "Double precision" with conserving all existing data. The point is script would not return error in either case. Is this possible? If yes then how?

A: You can check an actual type of a column using next query
SET TERM ^ ;
EXECUTE BLOCK AS BEGIN
  if (exists(select
    rf.rdb$field_name,
    f.rdb$field_type
    from
      rdb$fields f join rdb$relation_fields rf
      on rf.rdb$field_source = f.rdb$field_name
    where
      rf.rdb$relation_name = 'YOUR_TABLE_NAME'
      AND rf.rdb$field_name = 'YOUR_FIELD_NAME'
      AND f.RDB$FIELD_TYPE = 10)) then
  execute statement 'ALTER TABLE YOUR_TABLE_NAME ALTER YOUR_FIELD_NAME TYPE DOUBLE    PRECISION';
END^
SET TERM ; ^

rdb$field_type for FLOAT is 10, for DOUBLE PRECISION is 27.

redpajama_set_name: RedPajamaStackExchange


text:
Q: fork and wait process does not work with mke2fs when I redirect output I need to fork a process, redirect output (stdout and stderr) in buffer. My code seems to work with most of binary but not all. For example I can run my code with a very long "ls" like ls -R /proc/ and it is working perfectly. When I run mke2fs process, my code does not work anymore.
If I run mke2fs in a fork and wait for it, it is working perfectly. Now if I add redirect stuff, my programs never finish to run.
I wrote a little main to test this specific trouble :
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main ()
{
  pid_t pid;
  int status = -42;
  int pipefd_out[2];
  int pipefd_err[2];
  char buf_stderr[1024];
  char buf_stdout[1024];
  int count;
  int ret;

  pipe(pipefd_out);
  pipe(pipefd_err);

  memset (buf_stdout, 0, 1024);
  memset (buf_stderr, 0, 1024);

  pid = fork ();

  if (pid == -1)
  {
    fprintf (stderr, "Error when forking process : /usr/sbin/mke2fs\n");
    return 1;
  }

  if (pid == 0)
  {
    close(pipefd_out[0]);
    close(pipefd_err[0]);

    dup2(pipefd_out[1], 1);
    dup2(pipefd_err[1], 2);

    close(pipefd_out[1]);
    close(pipefd_err[1]);

    char **args;

    args = malloc (sizeof (1024));
    args[0] = strdup("/usr/sbin/mke2fs");
    args[1] = strdup("/dev/sda4");
    args[2] = strdup("-t");
    args[3] = strdup("ext4");
    args[4] = NULL;

    execvp ("/usr/sbin/mke2fs", args);

    /*
    args = malloc (sizeof (1024));
    args[0] = strdup("/bin/ls");
    args[1] = strdup("-R");
    args[2] = strdup("/proc/irq");
    args[3] = NULL;

    execvp ("/bin/ls", args);
    */
    perror ("execv");
    fprintf (stderr, "Error when execvp process /usr/sbin/mke2fs\n");
    return 1;
  }
  close(pipefd_out[1]);
  close(pipefd_err[1]);

  if (waitpid(pid, &status, 0) == -1)
  {
    fprintf (stderr, "Error when waiting pid : %d\n", pid);
    return 1;
  }

  do
  {
    count = read(pipefd_out[0], buf_stdout, sizeof(buf_stdout));
  }
  while (count != 0);
  do
  {
    count = read(pipefd_err[0], buf_stderr, sizeof(buf_stderr));
  }
  while (count != 0);

  ret = WEXITSTATUS(status);

  FILE* file = NULL;
  file = fopen("/root/TUTU", "w");

  if (file != NULL)
  {
    fwrite(buf_stdout, 1, sizeof(buf_stdout), file);
    fwrite(buf_stderr, 1, sizeof(buf_stdout), file);
    fclose(file);
  }

  return 0;
}

If I run ps, I could see my child process running :
# ps | grep sda4
  936 root      2696 S    {mke2fs}  /dev/sda4 -t ext4

I am not able to understand why I got this strange behavior. Not sure if its related, but output of mke2fs is not classic. Instead of print output and move forward the prompt, the process seems to update the output during the computing. It is a kind of progress bar. Not sure if my explanation is really clear.
Thanks,
Eva.

A: You can't wait for the program to finish (what you do with waitpid) before reading its stdout/stderr from the pipe. When the program writes to the pipe and its full it will sleep until you read from the pipe to make space in it. So the program waits until there's more space in the pipe before it can continue and exit, while you're waiting for the program to exit before you read from the pipe to make space in it.
The simplest solution in this case would be to just move waitpid until after you're done reading from the pipes. It should be fine since the program you execute will close the pipes when exiting.


text:
Q: Question about keep running a Javascript app on Synology NAS my goal is to keep an app running on my Synology, i can run the app connecting in SSH and everything is fine but when i close the connection obviously the app stop to work.
I'm not very expert with Unix and co. so my actual workaround for this is that:
Guacamole Docker + Firefox Docker: I connect to the firefox docker, then use guacamole for the ssh and run the app from there. I can close everything and the app is still running fine. But I know I'm wasting so much everything for an easy task.
I know for sure that there is a better way to accomplish that so can anyone help me? Thanks in advance!

A: Usually, when you start something in a shell, that something is bound to that shell, so when you terminate the shell (like when you close the ssh connection) whatever was bound to it also terminates.
For your process to survive the shell termination, you have to detach it, there are various ways to do it and I'm not experienced in the specific unix distribution that Synology uses so I can't be 100% sure but this will probably work: https://askubuntu.com/questions/8653/how-to-keep-processes-running-after-ending-ssh-session
It uses a software, tmux, to do the detatching thing.
That said, using docker is not a bad idea. I don't think there will be any noticeable performance difference or wasted resources.


text:
Q: SSRS Data Driven Subscription Data Source Credentials Configuration I am creating a data driven subscription and that requires you to stored credentials. However, they want want a link to the report embedded in the email. If the user clicks the link then stored credentials will be what is authenticated and not the actual user.
They would like the user to be prompted for authentication when they manually execute the report. Here are a couple of things I was considering:

*

*I think I can accomplish this by creating a copy of the report that uses a different data source configured to prompt the user for credentials and use the URL to this report to include in the data driven subscription.

*I don't think I can do this, in sql update the Credential Retrieval to go from Using the Following Credentials to Prompt the User for Credentials.  However, if you switch it back to use the setting Using the Following Credentials, then I will need to reapply the username and password. Not quite for sure how to do that programmatically.
Does anybody else have an idea on how to handle this?


text:
Q: Problem of Running Monodevelop-Stable on Linux I've tried to install Monodevelop-Stable on Arch-Based Linux ( Manjaro ) and i'd fault 3 times, it wasn`t possible to build from Github sources or from AUR or Flatpak, so i decided to use monodevelop-stable-bin also from AUR, but when i tried to run my app , i got this problem

"$(MSBuildBinPath)\Microsoft.CSharp.targets" was not found. Confirm that the path in the  declaration is correct, and that the file exists on disk (MSB4019)

Another words:

"MonoDevelop/7.0/MSBuild/2472_1/Microsoft.Csharp.targets" was not found. Confirm that the path in the  declaration is correct, and that the file exists on disk (MSB4019)

But i have in my directory:

Microsoft.Csharp.Crosstargetting.targets

Notice , that this answer also wasn`t helpful:
this one
Question is indeed so popular on the internet , but i still haven`t found an answer , and i need some help

A: I have the same problem, I talked a bit more in detail in this answer, but the short of it is that, for now, it seems that there is no way to use Monodevelop on Arch based systems.
I recommend using a Ubuntu based distro for programming (there are many other similar problems with Arch). There Monodevelop should work just fine.
Of course, you can try to use other IDEs, like JetBrains Rider (I haven't personally tested it) or just use text editors with appropriate extensions, like VSCode or Atom.


text:
Q: How do I know which answer was up voted? If I have answered dozens of questions in the last day, and I see my reputation go up, how do I know which answer was up voted?
In activity I see Answered, Commented, Accepted, but no indication of an up or down vote.

A: In the bar on the top of every page, click on the envelope before your name, then on the "reputation" tab, then on "today".


text:
Q: Switch to New Tab Based on Click of a hyperlink On the product page of an ecommerce store I'm trying to switch to another tab based on the click of a hyperlink.
So from a product description, I have a "Read the FAQ" link, that once clicked, I would like to automatically switch to the FAQ tab.
See here: http://www.lifestyleclotheslines.com.au/austral-addaline-35-foldown-clothesline
I tried to replicate the basics of this fiddle but didn't have much luck, I'm sure I was doing something wrong.
$(document).ready(function() {
    $('#myTabs').tabs();

    $('#showTab1').click(function() {
        $('#myTabs').tabs('select', '#tabone');
    });

    $('#showTab2').click(function() {
        $('#myTabs').tabs('select', '#tabtwo');
    });
});

http://jsfiddle.net/zEwQz/495/
Any help would be awesome.
Thanks!

A:

Tab One

Tab Two

Faq Tab

You've selected Tab 1

You've selected Tab 2

You've selected Faq Tab

Read the FAQ

<input type="button" id="showTab1" value="Show tab 1"/>
<input type="button" id="showTab2" value="Show tab 2"/>

 $(document).ready(function() {
        $('#myTabs').tabs();

        $('#showTab1').click(function() {
            $('#myTabs').tabs('select', '#tabone');
        });

        $('#showTab2').click(function() {
            $('#myTabs').tabs('select', '#tabtwo');
        });
        $('#showFaqTab').click(function() {
            $('#myTabs').tabs('select', '#faqtab');
        });
    });

Not Sure what are you looking for. Please have a look on the updated fiddle
http://jsfiddle.net/zEwQz/500/

A: You are having same id attribute for both anchor link and the button i.e.  (there would be unique ID for an element on the web page)
Read the FAQ

<input type="button" id="showTab2" value="Show tab 2"/>

Try to change it and it will work.
Read the FAQ

<input type="button" id="showTab2" value="Show tab 2"/>

$(document).ready(function() {
    $('#myTabs').tabs();

    $('#showTab1').click(function() {
        $('#myTabs').tabs('select', '#tabone');
    });

    $('#showTab2').click(function() {
        $('#myTabs').tabs('select', '#tabtwo');
    });

        $('#lnkshowTab2').click(function() {
        $('#myTabs').tabs('select', '#tabtwo');
    });
});

DEMO


text:
Q: How to route WCF REST services? Was planning to use Service Routing (on WCF/REST) to do some common tasks before a request hits the actual service. Now that I read more about it, looks like REST is not supported yet on RoutingService and the suggested method is to use System.Web.Routing or ARR.
What needs to happen in the router is a key validation, a header value extraction and versioning.
ARR doesn't look right for this as it just routes and there is no "handler" we have access to. System.Web.Routing looks like a lot of custom implementation which might undermine the efficiency of WCF.
An old school alternative am thinking of is to have the common functionalities in one chain-of-responsibilities implementation and just compose it in every service. This has the disadvantage of being referenced in N number of places for N services. But this increasingly looks like the only alternative if I don't want to mess with the WCF handling of endpoints.
Am looking for advice on a right way to do this, and any samples.

A: Didn't try, but maybe writing a custom service behavior can solve your problem. Take a look here : Extending WCF with Custom Behaviors.
The idea is to extend the WCF engine with a custom behavior, then attaching your service with this behaviors. This is transparent for the services.

A: Take a look at HttpMessageHandlers in the new WCF Web Api project htttp://wcf.codeplex.com  This mechanisms allows you to do something similar to Rack or WSGI.  I have a couple of examples of what you can do with them on my blog http://www.bizcoder.com/index.php/2011/05/22/how-to-get-ahead-with-messagehandlers/


text:
Q: Combinations/Permutations question (would like the source as well) My friend posed me this question; but she could not remember where she had gotten it from and would like to know, as she reworded the question but the data is still the same; just that the vocabulary was made more succinct.
Also, would appreciate if someone could show how to do it.
Question:
A pack of sweets contains $25$ sweets, a combination of mini-cupcakes and mini-macarons. If there are $18$ varieties of mini-cupcakes, and $10$ varieties of mini-macarons, how many ways can you fill a pack of sweets assuming that the order does not matter i.e. only the amount of each sweet type in the pack matters?

A: Hint.
(Preassuming that a pack of sweets is allowed to contain $25$ mini-cupcakes or mini-macrons)
There are $28$ varieties in total, so actually are looking for the number of sums: $$v_1+\cdots+v_{28}=25$$where the $v_i$ are nonnegative numbers.
This can be solved with stars and bars.
If the pack of sweets is not allowed to contain $25$ mini-cupcakes or mini-macrons then this can be repaired by subtracting the number of cases where $v_1+\cdots+v_{18}=0$ and the number of cases where $v_{19}+\cdots+v_{28}=0$.

A: No idea on the source, but as for the solution:
Let the number of cupcakes be $c$, and the number of macarons be $m$.
The first statement gives us $c + m = 25$.
So for each pair of values $c,m$, you'd need to calculate how many different combinations of varieties are possible. To do this, consider the number of ways you can divide $c$ cupcakes between $b$ boxes, where each box represents one variety of cupcake and empty boxes are allowed. Calculate the same quantity for the macarons, and multiply together.
Then you just sum those products for all combinations of $c,m$.
Hint 1:

 You can arrange 3 items into 3 boxes in the following ways:
 XXX||
 XX|X|
 XX||X
 X|XX|
 X|X|X
 X||XX
 |XXX|
 |XX|X
 |X|XX
 ||XXX
 Can you work out a general formula for putting $x$ objects into $b$ boxes?

Hint 2:

 $x$ items can be put into $b$ boxes in $\left(\array{x+b-1\\b-1}\right)$ ways. Imagine the items in a line. You can divide them into $b$ groups by inserting $b-1$ dividers. There are a total of $x+b-1$ objects - items and dividers. So there are $\left(\array{x+b-1\\b-1}\right)$ ways of inserting the dividers.

A: A permutation in which the order does not matter is known as a combination. If the number of permutations of permutations of a set of n objects if given by the factorial $ n! $ then it is a exercise in combinatorics to show that if we want to choose a combination of $k$ objects from a collection of $n$ objects we have $n!/k!(n-k)!$ ways of doing so, which is also given in the notation $ n \choose k$.
Addressing the question, one way is to count according to how many mini-macaroons can be included in a pack of sweets. If for instance, we want to know how many packs of sweets have 8 mini-macaroons, we choose 8 varieties of mini macaroons from the 10 varieties of mini-macaroons, $10 \choose 8$, then to make up the packet of 25 sweets, we choose 17 mini-cupcakes from the 18 varieties of mini-cupcakes, $18 \choose 17$, then the total number of packs of this type is given by the product $10 \choose 8$$18 \choose 17$. Then to find the total of all types, simply sum over all the possible ways
$\sum_{i=7}^{10}$ $10 \choose i $ $18 \choose 25-i$

A: Indicating the number of m.-cupcakes as $x$, and that of m.-macaronis as $y$,
then we shall have
$$
\left\{ \matrix{
  0 \le x \le 18 \hfill \cr
  0 \le y \le 10 \hfill \cr
  x + y = 25 \hfill \cr}  \right.
$$
which, geometrically corresponds to the sketch below.

The solution is just
$$
\begin{gathered}
  \left\{ \begin{gathered}
  0 \leqslant x \leqslant 18 \hfill \\
  0 \leqslant y \leqslant 10 \hfill \\
  x + y = 25 \hfill \\
\end{gathered}  \right.\quad  \Rightarrow \quad \left\{ \begin{gathered}
  0 \leqslant x \leqslant 18 \hfill \\
  0 \leqslant 25 - x \leqslant 10 \hfill \\
  x + y = 25 \hfill \\
\end{gathered}  \right.\quad  \Rightarrow \quad  \hfill \\
   \Rightarrow \quad \left\{ \begin{gathered}
  0 \leqslant x \leqslant 18 \hfill \\
  15 \leqslant x \leqslant 25 \hfill \\
  x + y = 25 \hfill \\
\end{gathered}  \right.\quad  \Rightarrow \quad \left\{ \begin{gathered}
  15 \leqslant x \leqslant 18 \hfill \\
  x + y = 25 \hfill \\
\end{gathered}  \right. \hfill \\
\end{gathered}
$$


text:
Q: Determine whether $\sin x \left| {\sin x} \right|$ is differentiable and find the derivative function.
Determine whether $f(x)=\sin x \left| {\sin x} \right|$ from
  $\mathbb{R}$ to $\mathbb{R}$ is differentiable and find the derivative
  function.

I know to let $g(x)=\sin x$. Then we have  $f(x)=g(x) \left| {g(x)} \right|$. Also $g'(x)=\cos x$.
What do I do from here?

A: The function $|\sin x|$ has corners at every $x = k \pi$, where $k$ is an integer. So while $f(x)$ is continuous everywhere on $\mathbb{R}$, it is not differentiable at any $x = k \pi$. However, it is still differentiable on intervals like $(k \pi, (k+1) \pi)$. Differentiating $f(x)$ on this interval gives us $f'(x) = \cos x |\sin x| + \sin x \frac{d}{dx} |\sin x|$. Over $(k \pi, (k + \frac{1}{2}) \pi)$, $\frac{d}{dx} |\sin x| = |\cos x|$, because $|\sin x|$ increases here. At $x = (k + \frac{1}{2}) \pi$, $|\sin x|$ attains its maximum of 1, so $\frac{d}{dx} |\sin x| = 0$. Over $((k + \frac{1}{2}) \pi, (k + 1) \pi)$, $\frac{d}{dx} |\sin x| = -|\cos x|$, because $|\sin x|$ decreases here. Hence, $f'(x)$ is piecewise-defined.

A: Let $g(x)=\sin x$ and $h(x)=|x|$.
Then, $f(x)=(g \cdot h\circ g)(x)$.
By product rule $(g\cdot h\circ g)'=g'\cdot(h\circ g)+g\cdot(h\circ g)'$
By chain rule $(h\circ g)'=(h'\circ g)\cdot g'$
By [algebraic] substitution $f'=g'\cdot(h\circ g)+g\cdot((h'\circ g)\cdot g')$
This might look difficult at first, but each of the operations is quite simple, so it all works out nicely in the end.
Comment: you may wish to define the derivative of $h$ as $\text{sgn}(x)$ depending on the intended application - otherwise, the derivative is defined piecewise.

A: You can apply the chain rule, together with the product rule, at points where $\sin x\ne0$, because the derivative of $x\mapsto |x|$, for $x\ne0$, can be written $|x|/x$. Thus
$$
f'(x)=\cos x\lvert\sin x\rvert+\sin x\cos x\frac{\lvert\sin x\rvert}{\sin x}
=2\cos x\lvert\sin x\rvert
$$
Now observe that
$$
\lim_{x\to k\pi}f'(x)=0
$$
and therefore (by l'Hôpital), you have $f'(k\pi)=0$.
Thus the derivative is $f'(x)=2\cos x\lvert\sin x\rvert$, for every $x\in\mathbb{R}$.


text:
Q: VBA Import MS Access to MS Word I have a VBA module in MS-Access that is supposed to load data from a database into Form Fields in a MS-Word document.  I thought it was working fine, but it appears to be inconsistent.  Sometimes it works and sometimes it doesn't.  I can't figure out what keeps it from working.  When I step through the debugger it doesn't throw any errors, but sometimes it doesn't open MS-Word.
Here is the relevant code:
Dim appWord As Word.Application
Dim doc As Word.Document
'Avoid error 429, when Word isn't open.
On Error Resume Next
Err.Clear

'Set appWord object variable to running instance of Word.
Set appWord = GetObject(, "Word.Application")

If Err.Number <> 0 Then
'If Word isn't open, create a new instance of Word.
Set appWord = New Word.Application
End If

Set doc = appWord.Documents.Open("\\srifs01\hresourc\EHS Department\EHS Database\IpadUpload\Lab Inspection Deficiency Resolution Report.docx", , True)

'Sometimes word doesn't open and I think the issue is around here.
With doc
.FormFields("frmID").Result = Me!id
.FormFields("frmSupervisor").Result = Me!LabPOC
.FormFields("frmInspector").Result = Me!InspectorName
.FormFields("frmBuilding").Result = Me!BuildingName
.FormFields("frmRoom").Result = Me!Rooms
.FormFields("frmComments").Result = Me!Comments
.Visible = True
.Activate
.SaveAs "'" & Me!id & "'"
.Close
End With

Set doc = Nothing
Set appWord = Nothing

Any help is appreciated.  Thanks in advance.

A: "When I step through the debugger it doesn't throw any errors, but sometimes it doesn't open MS-Word."
That's because you have On Error Resume Next.  That instructs VBA to ignore errors.
Assume you've made this change in your code ...
Dim strDocPath As String
strDocPath = "\\srifs01\hresourc\EHS Department\EHS Database" & _
    "\IpadUpload\Lab Inspection Deficiency Resolution Report.docx"

Then, when you attempt to open strDocPath, VBA would throw an error if appWord isn't a reference to a Word application instance ... AND you haven't used On Error Resume Next:
Set doc = appWord.Documents.Open(strDocPath, , True)

You can get rid of On Error Resume Next if you change your assignment for appWord to this:
Set appWord = GiveMeAnApp("Word.Application")

If Word was already running, GiveMeAnApp() would latch onto that application instance.  And if Word was not running, GiveMeAnApp() would return a new instance.
Either way, GiveMeAnApp() doesn't require you to use On Error Resume Next in your procedure which calls it.  Include a proper error handler there instead.  And you can reuse the function for other types of applications: GiveMeAnApp("Excel.Application")
Public Function GiveMeAnApp(ByVal pApp As String) As Object
    Dim objApp As Object
    Dim strMsg As String

On Error GoTo ErrorHandler

    Set objApp = GetObject(, pApp)

ExitHere:
    On Error GoTo 0
    Set GiveMeAnApp = objApp
    Exit Function

ErrorHandler:
    Select Case Err.Number
    Case 429 ' ActiveX component can't create object
        Set objApp = CreateObject(pApp)
        Resume Next
    Case Else
        strMsg = "Error " & Err.Number & " (" & Err.Description _
            & ") in procedure GiveMeAnApp"
        MsgBox strMsg
        GoTo ExitHere
    End Select
End Function

You could also include a check to make sure appWord references an application before you attempt to use it.  Although I don't see why such a check should be necessary in your case, you can try something like this ...
If TypeName(appWord) <> "Application" Then
    ' notify user here, and bail out '
Else
    ' appWord.Visible = True '
    ' do stuff with Word '
End If

A: I don't use the New keyword when opening or finding an application.
This is the code I use for excel:
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err.Number = 429 Then 'Excel not running
    Set xlApp = CreateObject("Excel.Application")
End If
On Error GoTo 0

(note also the On Error GoTo 0 - I don't want the resume next to be active all through the code)

A: The GiveMeAnApp function worked great for me with a similar problem I was experiencing. Except, to avoid Error 462 (cannot connect to server etc) if I closed the Word document after the data merge and attempted another merge of data to Word. (which caused error 462) I did this: Once I call GiveMeAnApp I then called for a New Word document before calling the Word template I wished to transfer data to Word into.
By always having the New Word document present this avoided error 462 in my circumstances. It means I am left with an empty Word doc but this is ok for me and preferable to the only other solution I could come up with which was to quit the db and re open and run the merge to Word aga.
I am grateful for the help set out in this thread. Thanks all.


text:
Q: populate datagridview from a list and edit the list (adding) I have a List
List <string> aList = new List<string>();
aList.Add("A,B");
aList.Add("A,C");
aList.Add("A,D");
aList.Add("A,E");

I have datagridview, and I want to display this list on this datagridview.
aDataGridView.DataSouce = aList; // Dosent seems to work.

When this is displayed on the datagridview I want the user to add to it from the gridview.For example:
DataGridView:
    (This column added by the user) and if user does not add anyhing, that row is excluded  from aList.
A B apple
A C banana
A D
A E
Is there anyway I can achieve this. sorry I am a beginner in C#.
Many Thanks

A: I would suggest utilizing a datatable as it can ready be used as a datagridview.datasource.


text:
Q: In your architecture, how do you decouple a url from the database layer & business objects layers BACKGROUND
We've got some links on our site that have formats that look like:
http://oursite.com/books/c_sharp_in_depth_12345.
To handle this, we use a simple property called Url:
public class Book
{
    public string Url { get; set;}
}

Basically, the URL comes from our website's domain, a section of the site (i.e. books), the name of the page and a unique id to identify the resource. The full URL is being stored in the database.
We don't like the fact that our database is storing the section name. That's a property of web layer property, not a property of the book. The database should not be dependent upon the web layer.
So we remove the section from the URL and get the following:
public class Book
{
    public string UrlWithoutSection { get; set;}
}

OK, that works for this URL. But then our company's SEO czar says that our URL is wrong and that Google, our-one-true-love, will only love us if we re-write our urls like this:
http://oursite.com/programming-books/c-sharp-in-depth-12345
Uh, oh, I thought that we had removed the database dependency to the web layer, but we hadn't. Turns out, we had removed the dependency to the section, but the format of the URL still exists in the database. We fix this by abstracting the URL into an object:
public class OurUrl
{
    public string title { get; set; }
    public string id { get; set; }
}

Cool, now the dependency to the web layer is gone. Uh oh, here this time our CEO comes to us. We just bought a new company and now we're selling magazines. Uh, great? The magazine URLs are going to look like this:
http://oursite.com/magazines/computers/stack-overflow-the-magazine/2012/01/01/12345
OK, no problem, just create another object.
public class OurMagazineUrl : OurUrl
{
    public DateTime PublishedDate { get; set; }

    // Magazine enum will have to be created.
    public MagazineType Type { get; set; }
}

It works, except then I begin to realize that we have plans for a big site. Lots of URLs. Lots of differently formatted URLs. Creating a new class every time seems like a major headache.
THE PROBLEM IN A NUTSHELL
How do you handle URLs so that the web layer is properly decoupled from the business layer and the data layer? I've come up with several thoughts about solutions:
MORE ABOUT THE PROBLEM
I'm hoping that this helps clarify some confusion.
We are using ASP.Net MVC. We use routes. We use helpers. We pass flattened DTOs to our web layer, not business objects. This problem concerns the service layer and an explosion of DTOs.
This is mainly a high traffic news site, not a line of business site. It can have many different urls and the urls can change at any time. They can be complex and arbitrarily determined by management.
URL Examples (not real, made up for example purposes).
 1. http://oursite.com/news/wi/politics/supreme-court/recent-ruling-someid
 2. http://oursite.com/news/wi/politics/election-2012/candidate-x-takes-stand-on-issue-y-someid
 3. http://oursite/com/news/politics/mayor-says-things-are-a-ok-someid
 4. http://oursite.com/news/milwaukee/local-bar-named-to-HOF-someid
 5. http://oursite.com/news/wi/politics/supreme-court-someid
 6. http://oursite.com/news/whatever-cat-our-CEO-wants/subcat1/subcat2/etc/2011/10/31/some-story-someid

All of the above are "articles" and we have an Article class. An article has a number of navigation properties, such as AuthorObject, RelatedLinksCollection, etc. Business objects are far too heavy to pass to a client, so we pass DTOs that flatten information (e.g. AuthorName). The above links, however can require different information, even though they are all "articles".

*

*needs Category, Subcategory, Title and Id

*needs Category,Subcategory, PoliticsCategory, Title and Id

*needs Category, Title and Id

*needs Category, Title and Id

*needs Category, Subcategory, Title and Id

*needs CeoCategory, CeoSubcategory, PublishedDate,Title and Id

In static programming languages, such as c#, the normal way would be to handle this would be to create separate DTO classes. You could add inheritance to reduce some of the code, but you still end up with multiple "article" dto classes.
public class IArticleDto {
  public string title { get; set; }
  public string body { get; set; }
  public string Category { get; set; }}

public class StateArticleDto: IArticleDto {
  public string title { get; set; }
  public string body { get; set; }
  public string Category { get; set; }}
  public string StateCode { get; set; }
  public string Subcategory { get; set; }
}

public class SupremeCourtArticleDto: IArticleDto {
  public string title { get; set; }
  public string body { get; set; }
  public string Category { get; set; }}
  public string Subcategory { get; set; }
}

public class ArbitraryCeoArticleDto: IArticleDto {
//who knows
}

etc.
The ability to write custom urls in any way possible in not negotiable. If an article relates to something (state, Category, etc.), it can become part of the url.
Solutions?

*

*Continue to add Url objects as needed. How many? At least a dozen, but naming them will be troublesome. Doing one per business object solves the name issue, but that means dozens or hundreds of new objects. Yuck.

*IOC - Pass in the route pattern to the Data Access layer via configuration. The data access layer can then create a full url. The url pattern name is still a problem.

*Use a Dictionary<TKey, TValue>, KeyValuePair<TKey, TValue>, etc. to pull in.

*Use an Expando or DynamicObject for the url details. So url will contain a couple basic properties (name and id), but other properties could be added when necessary.
I'm thinking about using 4), because it seems like something that dynamic programming does better than static languages. However, it may just be that I'm looking at it most, because I like new toys to play with (I haven't used expando before).
It's bettern than 1), because of the object explosion. I'm not sure that 2) will work for complex scenarios. You could pass in simple route name + route information to the data layer using DI, but it seems harder to accomplish with no additional gain. And it probably wouldn't work for complex routes -- for that, I think that you need to have a rules engine on the UI side.
As compared to 3), I think that 4) is slightly better. Someone correct me if I'm mistaken, but dynamic types seem to be no more than syntatic sugar on top of a  dictionary, but with the advantage of cleaner code. Just a thought.

A: I'm going to be blunt and say that the fact that you're asking this question and based on the solutions you're proposing, you're not taking a birds-eye architectural view of the problem at hand. I don't know the intimate details of your application, but being able to have a bit outlook and the ability to picture what it might be used to in the future will help with the URI design.
The solutions you're proposing are all revolving around very concrete, programmatic details, while the problem is abstract and not related to programming at all. Solving the problem is all about writing down the entities in your domain, the actions that are possible to perform on them and how they relate to each other.
Bill de hÓra has a blog post regarding Web resource mapping criteria for frameworks (here's a cached version, should the real one still give HTTP 500 errors) and Joe Gregorio has written about how to RESTify DayTrader that should give you the right idea around how to envision the complete URI space of your application. Planning, drawing, thinking and writing is what it sounds like you and your team need to do.
When the complete scope and space of the URIs in your application is designed, you're ready to implement it. However you then do it is up to you, and then I'd recommend using URI Templates to define the URIs themselves and regular code to map the code that will handle the URIs (be it Controllers, Handlers or whatever). In ASP.NET MVC, the configuration code is written against the RouteTable class, while in OpenRasta it is done against a ResourceSpace class.

A: You are correct to see the need to decouple your domain entities (books, magazines, etc) from any awareness of their URL.
The only indentifier you should need to access a book (for example) it its Id - in your example, 12345. Any other taxonomy elements should be handled in the presentation logic, as might you want a different URI structure for non-WWW channels? And if you launch the site multi-lingual? Having /magazines/computers/ persisted in the database would be a hinderance.
The requirements of your SEO czar may change over time, as the techniques to rank higher in search engines change also.
As such, this is a matter of URL routing.
In an ASP.NET Webforms solution, you would add the following entries to your Global.asax file:
void Application_Start(object sender, EventArgs e)
{
    RegisterRoutes(System.Web.Routing.RouteTable.Routes);
}

public static void RegisterRoutes(System.Web.Routing.RouteCollection routes)
{
    routes.MapPageRoute("Book",
        "{productType}/{categoryName}/{productName}/{productId}",
        "~/Books.aspx");

    routes.MapPageRoute("Magazine",
        "{productType}/{categoryName}/{productName}/{year}/{month}/{day}/{productId}",
        "~/Magazines.aspx");
}

Books.aspx and Magazines.aspx would then collect the relevant parts of the URL, with:
var categoryName = Page.RouteData.Values["categoryName"];

and when you have collected enough information to uniquely identify the product you want to display, you can then query your domain / data tier to get the information you need.
When new product types become available (or a new URL structure is requested by your stakeholders), you simply need to add another route.

A: maybe a state machine you could maintain an external DSL.
Main
.*=Product
nj|ny=State
([a-z]*-)*=Title
20[1-9][1-9]->ExpectMonth =Year
ExpectMonth
[0|1][0-9] = Month -> ExpectDay

ect....
And a T4 to generate struct code
struct Url {
 string Product {get;set}
 string State {get;set;}
}

I think the "monolithic class" antipattern is mitigated somewhat by code generation.

A: Here is my first go at #4. It works and the dynamic object type works elegantly.
public class ArticleDto
{
//normal Article properties
//code goes here

//new dyamic property for the Uri Details
public dynamic UriDetails { get; set; }
}

Then I created a custom class to handle the URI details. I added a constructor with name + id, because I always want a resource name + id to be passed with no exceptions.
public class UriDetails : DynamicObject
{
    //TODO put error handling in here to ensure that they're not empty?
    public string ResourceName { get; set; }
    public int ResourceId { get; set; }

    public UriDetails(int resourceId, string resourceName)
    {
        ResourceId = resourceId;
        ResourceName = resourceName;
    }
//other code that you need to override
}

Then, in my DataAccess code
ArticleDto = new ArticleDto();
//Set the regular properties
//code goes here

//Set the mandatory uri properties
ArticleDto.UriDetails = new UriDetails(id, articleTitle);

//Set any other properties specific to this call
ArticleDto.Date = publishedDate;

One note: this solves the problem of the service layer, but the web layer still needs to know how to build the URL. That will be some type of helper class / rules engine that will determine what's used based on the property names & types in UriDetails.
Let me know what you think.


text:
Q: Adding META-INF\services\javax.xml.parsers.SAXParserFactory to jar I have a folder which has few class files, the command i was using to create a jar was
jar cfm0 my.jar MANIFEST *.class

Now I also want to add following to the jar META-INF\services\javax.xml.parsers.SAXParserFactory. Please suggest what will be the command which  will create a jar with classes and META-INF\services\javax.xml.parsers.SAXParserFactory.
I thought of tampering with jar i.e. add META-INF\services\javax.xml.parsers.SAXParserFactory using 7z but wasnt convinced.
Using this command returns following error
jar cfm0 CAM_AAA_JDBCPowerReports.jar META-INF/services/javax.xml.parsers.SAXParserFactory *.class

java.io.IOException: invalid header field
        at java.util.jar.Attributes.read(Attributes.java:389)
        at java.util.jar.Manifest.read(Manifest.java:180)
        at java.util.jar.Manifest.<init>(Manifest.java:50)
        at sun.tools.jar.Main.run(Main.java:149)
        at sun.tools.jar.Main.main(Main.java:1147)

Please note I dont use any IDE. All I use is Editplus and command prompt

A: The correct way to do it is
jar cfm0 my.jar MANIFEST META-INF/services/javax.xml.parsers.SAXParserFactory *.class


text:
Q: Map correctly YAML config file in golang I write an API in go which can create organisation which have default policies rules.
I want to use an external config YAML file to include some policies in my API (I actually put the policies inside my code in the function which creates my entity organisation) :
policy.yml
- role: "admin"
  organisationid: organisation.ID
  policies:
    [{Object: "/*", Action: "*"}]

- role: "user"
  organisationid: organisation.ID
  policies:
    [{Object: "/me", Action: "GET"},
    {Object: "/organisations", Action: "GET"},
    {Object: "/acl/roles", Action: "GET"}]

I extract it using go-yaml lib and the expected output should be :
[{admin organisation.ID [{/* *}]} {user organisation.ID [{/me GET} {/organisations GET} {/acl/roles GET}]}]

But when I extract it in a struct like :
// OrganisationRole ...
type OrganisationRoleNoPolicy struct {
    Role           string              `json:"role"`
    OrganisationID string              `json:"organisation"`
    Policies       []map[string]string `json:"policies"`
}

func extractYaml() (config []OrganisationRoleNoPolicy) {

    filename := "policy.yml"
    source, err := ioutil.ReadFile(filename)
    if err != nil {
        panic(err)
    }
    err = yaml.Unmarshal(source, &config)
    if err != nil {
        log.Fatalf("error: %v", err)
    }
    fmt.Printf("--- config:\n%v\n\n", config)
    return
}

I get this :
[{admin organisation.ID [map[Object:/* Action:*]]} {user organisation.ID [map[Object:/me Action:GET] map[Object:/organisations Action:GET] map[Object:/acl/roles Action:GET]]}]

Maybe I don't get well how to use or properly write YAML, so guys could you help me understanding how to map it to obtain the output expected.

A: Finally find it, I have to change my Yaml a little to have a proper array, the case seems to be very important too :
- role: "admin"
  organisationid: organisation.ID
  policies:
    - {object: "/*", action: "*"}

- role: "user"
  organisationid: organisation.ID
  policies:
    - {object: "/me", action: "GET"}
    - {object: "/organisations", action: "GET"}
    - {object: "/acl/roles", action: "GET"}

and my struct is a bit differents it contains a struct than include my two strings :
type policy struct {
    Object string `json:"obj" binding:"required"`
    Action string `json:"act" binding:"required"`
}

// OrganisationRole ...
type OrganisationRole struct {
    Role           string   `json:"role"`
    OrganisationID string   `json:"organisation"`
    Policies       []policy `json:"policies"`
}


text:
Q: What policies or rights to be provided for a user with which we will run the terraform scripts? We are creating eks clusters and other resources from terraform.
What are the policies to be given to that user account?

A: The answer is: it fully depends on your needs.
If you're running Terraform on CodeBuild or ECS and have configured an IAM Task Role, Terraform will use the container's Task Role.
If you're running Terraform on EKS and have configured IAM Roles for Service Accounts (IRSA), Terraform will use the pod's role.
See AWS Identity and Access Management Documentation for always up to date information and test your policies with the help of IAM policy simulator.
However, from my experience it is much easier to use AWS managed policies than to write policies yourself - see AWS managed policies for Amazon Elastic Kubernetes Service for an overview.


text:
Q: Unpacking a lists of list, into individual lists using another list Problem:I have a List of lists (lists_of_lists), that each contain 5 floats in each list. I am trying to unpack lists_of_lists and for every unpacked list, name it using the values in my country_list
Example of desired output:
Brazil = [28.42, 56.12, 59.97, 61.69, 60.34]
British = [39.1, 57.96, 56.29, 56.5, 71.25]
Note: the ordering in both lists correspond, as demonstrated above.
Resources:
list_of_lists = [[28.42, 56.12, 59.97, 61.69, 60.34], [39.1, 57.96, 56.29, 56.5, 71.25], [14.3, 42.33, 58.54, 41.24, 49.76]]
country_list = ['brazil', 'british', 'cantopop', 'mandopop', 'french', 'german', 'indian', 'iranian', 'malay', 'philippines-opm', 'spanish', 'swedish', 'turkish']
My thinking:
is that I should use a for loop to iterate through the country_list and for every string (country name), create a new list and populate using the same positioned list in the list_of_lists
Any hints would be great. Thank you

A: dict(zip(country_list, list_of_lists))

will give you a dictionary of country: list, as
{'brazil': [28.42, 56.12, 59.97, 61.69, 60.34], 'british': [39.1, 57.96, 56.29, 56.5, 71.25], 'cantopop': [14.3, 42.33, 58.54, 41.24, 49.76]}

As you can see the shortest element zipped is used (here country_list).

A: enumerate gives you iterator for both index and value
list_of_lists= [[28.42, 56.12, 59.97, 61.69, 60.34], [39.1, 57.96, 56.29, 56.5, 71.25], [14.3, 42.33, 58.54, 41.24, 49.76]]

country_list = ['brazil', 'british', 'cantopop']

# to print
for idx, country in enumerate(country_list):
    print(country, list_of_lists[idx])

# to store in a dictionary:
d = dict((country, list_of_lists[idx]) for idx, country in enumerate(country_list))

A: Creating "named" variables makes no sense. Put them into a dictionary:
list_of_lists= [[28.42, 56.12, 59.97, 61.69, 60.34],
                [39.1, 57.96, 56.29, 56.5, 71.25],
                [14.3, 42.33, 58.54, 41.24, 49.76]]

country_list = ['brazil', 'british', 'cantopop', 'mandopop', 'french',
                'german', 'indian', 'iranian', 'malay', 'philippines-opm',
                'spanish', 'swedish', 'turkish']

merger = {k:v for k,v in zip( country_list, list_of_lists)}

print(merger)

Output:
{'brazil': [28.42, 56.12, 59.97, 61.69, 60.34],
 'british': [39.1, 57.96, 56.29, 56.5, 71.25],
 'cantopop': [14.3, 42.33, 58.54, 41.24, 49.76]}

Shortest list wins. You can use the dictionary, to get all of brazils values:
print(merger["brazil"])    # [28.42, 56.12, 59.97, 61.69, 60.34]

To get all values iterate the dict:
for key in merger:
    print(key)
    print(merger[key])

Output:
brazil
[28.42, 56.12, 59.97, 61.69, 60.34]
british
[39.1, 57.96, 56.29, 56.5, 71.25]
cantopop
[14.3, 42.33, 58.54, 41.24, 49.76]

See:

*

*https://docs.python.org/3/tutorial/datastructures.html#dictionaries

A: I would create a dict to store the results.
myDict = {}
for i in range(len(list_of_lists)):
    myDict[country_list(i)] = list_of_lists(i)


text:
Q: Rscript appears to have a length limit. Options to circumvent it? I want to pass arbitrarily long strings to Rscript -e.  However, there appears to be a length limit.
Consider the pattern:
$ Rscript -e 'cat("some string goes here")'

If the string has a length of 9993 (on my machine), the command fails and hangs indefinitely.  If it has a length of 9992, it outputs the string as I desire.  (Your numbers may be different; you can do a binary search to find them if you're so inclined.)  The failure looks like this:
WARNING: '-e cat("hihihihihihihihihihihihihihihihihihihihihihihihihihihihihihi!hihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihi

(Note that the string is truncated in exactly this same way in my console: this input string is not the full input string.  This also means that I know there's a WARNING, but I don't know what it's warning me about!)
What is a good way to get around this limitation?  I could stick the content in a temp file under /tmp, but that strikes me as too messy.
What I'm really looking to do is to use Rscript (specifically, knitr) as a text filter: old string goes in, new string comes out.
For reference, here is my first iteration of this filter.  The problem is that when the input becomes too large, nanoc hangs indefinitely.  (I now know this is because Rscript is hanging; hence, this question.)

A: This is a limitation of readline (or whatever function is doing duty for stdin), not Rscript or R. If you don't want to follow Joshua's advice to source from a file then you will need to rewrite your system's input program.


text:
Q: Ruby rand function in method Using Ruby why can't I pass random variable here? I tried different combinations such as removing numbers.
money= rand(100)

def paycheck(money)
  "Lets make this amount, #{money} today"
end

puts paycheck("100")
puts paycheck("200")
puts paycheck("500")

A: You can:
money= rand(100)
puts paycheck(money)

When you define your method paycheck(money) - it is different variable money that the one on this line: money = rand(100)

A: You can do something like this:
def paycheck(limit)
  money = rand(limit.to_i)
  "Lets make this amount, #{money} today"
end

puts paycheck("100") #=> Lets make this amount, 14 today
puts paycheck("200") #=> Lets make this amount, 111 today
puts paycheck("500") #=> Lets make this amount, 119 today


text:
Q: raw template comes up in the screen at django I have this in the url.py
from django.conf.urls.defaults import patterns, include, url
from django.views.generic import ListView
from blog.models import Post

urlpatterns = patterns('',
    url(r'',
        ListView.as_view(
            queryset=Post.objects.all().order_by('-created')[:2],
            template_name='blog.html'
            )
        ),
)

and this in the template/blog.html
(% extends "base.html" %)

(% block content %)

(% for post in object_list %)

{{ post.title }}

    on {{post.created}}

    {{post.body|safe|linebreaks}}

    {% for tag in post.tags.all %}
        {{tag}}
        {% if not forloop.last %}, {% endif %}
    {% endfor %}

(% endfor %)
(%  endblock %)

So as the tutorial says now when I will visit the site rounte it should contain 2 of the blogs but, when I go there I it shows me in the browser:
(% extends "base.html" %) (% block content %) (% for post in object_list %)
on
(% endfor %) (% endblock %)

A: Yes the problem is that on the templates you have to use {} instead of () for template tags and {{}} for variables
{% extends "base.html" %}

 {% block content %}

{% for post in object_list %}

{{ post.title }}

    on {{post.created}}

    {{post.body|safe|linebreaks}}

    {% for tag in post.tags.all %}
        {{tag}}
        {% if not forloop.last %}, {% endif %}
    {% endfor %}

{% endfor %}
{%  endblock %}


text:
Q: DD-WRT: Port not fowarding when connecting with public IP from LAN I am having an issue where I can't connect to my home-server from my LAN when using the public IP address of the DD-WRT router. I am essentially having the same problem as detailed here: DD-WRT: How to allow port forwarding to apply to requests originating from inside the LAN?; however, none of the solutions provided are working for me. I am fairly certain that I am have modified the correct values for it to apply to my LAN setup. The router is a Netgear WNR834B v2 and it is running DD-WRT v24-sp2 18777. I am using the default IP (192.168.1.1) for it and I know that the domain an the port forwards work ordinarily.
EDIT: Got it! I found that I needed to enable Local DNS and use this answer from the linked question.

A: DD-WRT is likely not configured for hairpin routing.  Connecting to the Public IP from the LAN is usually a bad idea, and you will not be able to identify the connection source.  The best option is to connect directly to the desired server from inside the network.
The Shorewall FAQ 2 covers doing configuring the router so that it will work.  Shorewall builds an iptables firewall from a set of specification file, so the steps are not the required iptables commands, but map fairly easily to iptables.  I believe you should be able to run shorewall-lite on DD-WRT, in which case you will need to build all your firewall in Shorewall rather than the DD-WRT tool.
Using split DNS is far easier and I would recommend that approach.  A tool like dnsmasq can provide the necessary internal DNS from a /etc/hosts file.  It acts as a caching server for addresses on the Internet.   It also provides DHCP, do if you don't run it on your DD-WRT router, you will want to decide which DHCP server to enable.  If you have the memory you can install in on DD-WRT as a replacement for the default DHCP server.
EDIT: If you choose to use dnsmasq it is best to set it up as the active DHCP server.  If you don't run it on your router, disable DCHP on the routers.  Alternatively, use fixed addresses outside the DHCP address range for the servers your want to route to.  Using fixed addresses is a good idea for servers anyway.   Add the addresses of the servers to the /etc/hosts file on the host running dnsmasq, and restart dnsmasq.  If you configure dnsmasq with a domain, you can also lookup DHCP clients by name.
Determine the address of the dnsmasq host. (This should be a private network address like 192.168.0.10.)  Configure your DHCP server to list this address as the first DNS nameserver.  For linux hosts and others with a /etc/resolve.conf file use this address for the first nameserver entry.  For other servers with static nameserver entries make this address the first specified address.
DHCP clients will need to have their DNS data updated.  Triggering a DHCP renewal should update the data.   Many systems have internal DNS caches, so the changes may not be visible immediately.  Rebooting clients after all the server configuration has been done should clear all caches and reload DHCP specified configuration.


text:
Q: nativescript project broken build error I have my nativescript project tested and it worked, then I made a few changes to the project, suddenly something went wrong and some build errors appeared, I went to the previous point by git reset, removed all untracked git clean -fdX files including package-lock.json files to start freshly. I ran tns install or npm install and tns run, surprisingly the project produced a build error! isn't the point of packaging by npm to make sure that we can make up the same environment, every time and everywhere for the project?
I have also removed and installed nativescript and I noticed that npm produce some warning that some hash doesn't match the one npm has, I think i have fixed that by npm cache --force clean and npm cache verify, I don't know if it has anything to do with the build error?
how do I reset the project so it works again???
any help will be apperciated.
my gitignore file:
npm-debug.log
.DS_Store

*.js.map
vendor*.ts
**/*.js
!tools/*.js
hooks/
lib/
node_modules/
platforms/
tmp/
typings/
.idea
.cloud
/.project
.vscode

package.json:
    {
      "description": "NativeScript Application",
      "license": "..",
      "readme": "NativeScript Application",
      "repository": "<fill-your-repository-here>",
      "nativescript": {
        "id": "org.nativescript.projectname",
        "tns-android": {
          "version": "4.0.1"
        }
      },
      "scripts": {
        "lint": "tslint \"app/**/*.ts\""
      },
      "dependencies": {
        "@angular/animations": "~5.2.0",
        "@angular/common": "~5.2.0",
        "@angular/compiler": "~5.2.0",
        "@angular/core": "~5.2.0",
        "@angular/forms": "~5.2.0",
        "@angular/http": "~5.2.0",
        "@angular/platform-browser": "~5.2.0",
        "@angular/platform-browser-dynamic": "~5.2.0",
        "@angular/router": "~5.2.0",
        "nativescript-angular": "~5.3.0",
        "nativescript-permissions": "^1.2.3",
        "nativescript-theme-core": "~1.0.4",
        "nativescript-ui-sidedrawer": "~4.0.0",
        "reflect-metadata": "~0.1.10",
        "rxjs": "~5.5.5",
        "tns-core-modules": "4.0.0",
        "zone.js": "~0.8.18"
      },
      "devDependencies": {
        "@angular/compiler-cli": "~5.2.0",
        "@ngtools/webpack": "~1.9.4",
        "babel-traverse": "6.4.5",
        "babel-types": "6.4.5",
        "babylon": "6.4.5",
        "clean-webpack-plugin": "~0.1.19",
        "codelyzer": "~4.0.2",
        "copy-webpack-plugin": "~4.3.0",
        "css-loader": "~0.28.7",
        "extract-text-webpack-plugin": "~3.0.2",
        "lazy": "1.0.11",
        "nativescript-dev-sass": "~1.5.0",
        "nativescript-dev-typescript": "~0.7.0",
        "nativescript-dev-webpack": "~0.10.0",
        "nativescript-worker-loader": "~0.8.1",
        "raw-loader": "~0.5.1",
        "resolve-url-loader": "~2.2.1",
        "sass-loader": "~6.0.6",
        "tslint": "~5.8.0",
        "typescript": "~2.7.2",
        "uglifyjs-webpack-plugin": "~1.1.6",
        "webpack": "~3.10.0",
        "webpack-bundle-analyzer": "^2.9.1",
        "webpack-sources": "~1.1.0"
      }
    }

build error:
Gradle build...
         + applying user-defined configuration from D:\workspace\tns\projectname\app\App_Resources\Android\app.gradle
Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead.
Configuration 'debugCompile' in project ':app' is deprecated. Use 'debugImplementation' instead.
         + adding nativescript runtime package dependency: nativescript-optimized
         + adding aar plugin dependency: D:\workspace\tns\projectname\node_modules\nativescript-ui-sidedrawer\platforms\android\TNSSideDrawer-release.aar
         + adding aar plugin dependency: D:\workspace\tns\projectname\node_modules\nativescript-ui-core\platforms\android\TNSCore-release.aar
         + adding aar plugin dependency: D:\workspace\tns\projectname\node_modules\tns-core-modules-widgets\platforms\android\widgets-release.aar
D:\workspace\tns\projectname\platforms\android\app\src\main\res\values\styles.xml:40:5-41:13: AAPT: error: resource drawable/splash_screen (aka org.nativescript.projectname:drawable/splash_screen) not found.

D:\workspace\tns\projectname\platforms\android\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:1660: error: resource drawable/splash_screen (aka org.nativescript.projectname:drawable/splash_screen) not found.
error: failed linking references.

Failed to execute aapt
com.android.ide.common.process.ProcessException: Failed to execute aapt
        at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:796)
        at com.android.build.gradle.tasks.ProcessAndroidResources.invokeAaptForSplit(ProcessAndroidResources.java:551)
        at com.android.build.gradle.tasks.ProcessAndroidResources.doFullTaskAction(ProcessAndroidResources.java:285)
        at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.java:109)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:173)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
        at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:60)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:128)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:46)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$ExecuteTasks.run(DefaultGradleLauncher.java:311)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.initialization.DefaultGradleLauncher.runTasks(DefaultGradleLauncher.java:202)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:132)
        at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:107)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
        at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
        at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
        at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
        at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:45)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:29)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:71)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:45)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:51)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:64)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:29)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:55)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:42)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:58)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:33)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
        at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:503)
        at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:482)
        at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:79)
        at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:794)
        ... 122 more
Caused by: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
        at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:503)
        at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:462)
        at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:79)
        at com.android.builder.internal.aapt.v2.QueueableAapt2.lambda$makeValidatedPackage$1(QueueableAapt2.java:179)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        ... 1 more
Caused by: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
        at com.android.builder.png.AaptProcess$NotifierProcessOutput.handleOutput(AaptProcess.java:463)
        at com.android.builder.png.AaptProcess$NotifierProcessOutput.err(AaptProcess.java:415)
        at com.android.builder.png.AaptProcess$ProcessOutputFacade.err(AaptProcess.java:332)
        at com.android.utils.GrabProcessOutput$1.run(GrabProcessOutput.java:104)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDebugResources'.
> Failed to execute aapt

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 14s


text:
Q: Obtaining the Taylor Series Method, order two So here's the problem I'm having trouble with...
The initial value problem:
$$
    x'(t) = \cos(x+t^2)
$$
with $x(-5) = -1$ on the interval $[-5, 3]$.
I have no idea how to star this problem off and need some advice.
I'm looking at a practice example and this is how they did it.
$$ x'(t) = (x+t)^2 $$ and the second derivative is $$ x''(t) = 2(x+t) (x'(t) + 1) $$
I don't understand why they put x'(t) into the second derivative...

A: We can write
\begin{align*}
x(t+h) &= x(t) + hx^{\prime}(t) + \frac{h^{2}}{2}x^{\prime\prime}(t) + \mathcal{O}(h^{3})\\
& = x(t) + h\cos(x+t^{2}) + \frac{h^{2}}{2}x^{\prime\prime}(t) + \mathcal{O}(h^{3})
\end{align*}
Since
\begin{align*}
x^{\prime\prime} &= [x^{\prime}]^{\prime}\\
 &= [\cos(x+t^{2})]^{\prime}\\
 &= -2t\sin(x+t^{2})-\sin(x+t^{2})x^{\prime}\\
 &= -2t\sin(x+t^{2}) - \sin(x+t^{2})\cos(x+t^{2})\end{align*}
We get that
$$x(t+h) = x(t) + h\cos(x+t^{2}) + \frac{h^{2}}{2}\left(-2t\sin(x+t^{2}) - \sin(x+t^{2})\cos(x+t^{2})\right) + \mathcal{O}(h^{3})$$

A: The problem asks to solve the ordinary differential equation
$$x'(t)=cos(x+t^2)$$
in the interval I=[-5, 3] with the the initial value $x(-5)=-1$ by a Taylor series
$$x(t) = \sum_{i=0}^{\infty} a_{_i} (t-t_0)^i$$
and to compute the coefficients $a_i, i = 0,1,2$.
The differential equation satisfies a global Lipschitz condition. Hence a unique solution $x(t), t \in I$, exists.
We choose $t_0 = -5$, then $a_0 = -1$. Moreover
$$cos \ z = 1 - (1/2) z^2 + \mathscr O(4)$$
$$t^2 = (t+5)^2 -10(t+5) +25$$
$$x(t) = -1 + a_1(t+5) + \mathscr O(2)$$
$$x'(t) = a_1 +2a_2(t+5) + \mathscr O(2).$$
Comparing coefficients for $x'(t)=cos(x+t^2)$ gives
$$x'(t) = 1 -(1/2)[-1 + a_1(t+5) -10(t+5) +25]^2 + \mathscr O(2)$$
$$x'(t) = 1 -(1/2)[24 + (a_1-10)(t+5) ]^2 + \mathscr O(2)$$
$$x'(t) = 1 -(1/2)[24^2 + 48(a_1-10)(t+5) + \mathscr O(2)]$$
$$a_1 +2a_2(t+5) + \mathscr O(2) = -287 -24(a_1-10)(t+5) + \mathscr O(2).$$
Comparing coefficients on both sides gives
$$a_1 = -287, a_2 = 3564.$$


text:
Q: Webclient not working when threading (VB 2013) So here's my program flow:
Public Function previewAssigner()
    Dim pt1 As Thread

    pt1 = New Thread(AddressOf pt)

    pt1.Start()
End Function
Private Sub pt()
    MsgBox("PT")

    Dim tClient As WebClient = New WebClient

    Dim tImage As Bitmap = Bitmap.FromStream(New MemoryStream(tClient.DownloadData(apicurl)))

    FormDisplay.PictureBox1.Image = tImage
End Sub

Messagebox appears saying PT just fine, but image does not load. But if I paste the code in pt() to the function, it works just fine. What am I doing wrong?

A: It's a bit fiddly to access a control from a different thread: see How to: Make Thread-Safe Calls to Windows Forms Controls.
If you wanted a method to set an arbitrary PictureBox to an image from an arbitrary URL, you could do something like this:
Imports System.IO
Imports System.Net
Imports System.Threading

Public Class Form1

    Delegate Sub SetImageCallback(target As PictureBox, bmp As Bitmap)

    Friend Class ImageLoaderParameters
        Property Target As PictureBox
        Property URL As Uri
    End Class

    Sub LoadImageFromUrl(target As PictureBox, url As Uri)
        Dim ilp As New ImageLoaderParameters With {.Target = target, .URL = url}
        Dim t1 As New Thread(AddressOf LoadImageFromUrlHelper)
        t1.Start(ilp)

    End Sub

    Private Sub LoadImageFromUrlHelper(args As Object)
        Dim ilp = DirectCast(args, ImageLoaderParameters)
        Using wc As New WebClient
            Dim tImage As Bitmap = CType(Bitmap.FromStream(New MemoryStream(wc.DownloadData(ilp.URL))), Bitmap)
            SetImage(ilp.Target, tImage)
        End Using

    End Sub

    Friend Sub SetImage(target As PictureBox, bmp As Bitmap)
        If target.InvokeRequired Then
            Dim d As New SetImageCallback(AddressOf SetImage)
            Me.Invoke(d, New Object() {target, bmp})
        Else
            target.Image = bmp
        End If

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim src1 As New Uri("file:///C:/temp/hit.png")
        LoadImageFromUrl(PictureBox1, src1)

    End Sub

End Class

To check it works, I tested it with two pictureboxes and loaded, in turn, a slow-to-download image and a fast-to-download image. The fast one appeared first despite being started second.


text:
Q: How do I find the mode of a column of categorical data? I want to find the most repetitive value (which is the mode) of a column of categorical data and fill the blank cells with this value.
"Embarked" column has only three values: S,Q,C
When I try to calculate mean and median it gives an error already, because its no numerical value, but I can take a mode of this column, when I try this part of code it doesn't give an error:
embarked=df_missing['Embarked']
df_missing['Embarked']=df_missing['Embarked'].fillna(embarked.mode())

But it also doesn't fill the empty cells. How can I find the mode of this column.

A: That should be working, but try this approach.
First try df_missing['Embarked'].value_counts() and see whether you get what you expect.
Then try:
embarked_mode = df_missing['Embarked'].mode()
df_missing['Embarked'].fillna(embarked_mode, inplace=True)

If your columns doesn't contain cells aren't actually Na then as @Quang Hoang says, it may be that you have empty strings. In this case you can try:
embarked_mode = df_missing['Embarked'].mode()
df_missing['Embarked'].replace('\s+', embarked_mode, regex=True, inplace=True)


text:
Q: How to securely allow Github Actions to check PR and post results in comment I'm trying to understand the security model in Github Actions (GHA).  Let's say I have the following requirements on a public repo:

*

*Allow pull requests from forked repos to be opened

*GHA should run unit tests on pull requests

*GHA should post unit test results as a PR comment

In order for the third requirement to work, the pull request needs access to the GITHUB_TOKEN with repo write permissions.  This will require the following two permissions:

*

*Run Workflows from fork pull requests.

*Send write tokens to Workflows from fork pull requests

Now if write tokens are sent to the Workflows in fork PRs, what's to prevent a hacker from changing the Workflow in the PR and using it for any number of malicious purposes (creating a malicious release in the original repo or exfiltrating repo secrets)?  I understand you can limit the permissions of the token, but this is done within the workflow; the hacker can just as easily remove the limitations as part of the PR.
Is there any way to accomplish the three requirements without this security hole?

A: The must-read for this question is: Keeping your GitHub Actions and workflows secure Part 1: Preventing pwn requests
GH Action provides the event type "pull_request_target", which has write permissions and can comment the PR. Do not use this without being careful! The PR's code is untrusted - if you build it, it might inject malicious code and compromise your repository and might steal your secrets.
The proposed solution for this is:

*

*Have a workflow triggered by "pull_request" event. This runs with read-only GITHUB_TOKEN. Here you can run the unit tests. At the end of this workflow, the unit test results are uploaded as a build artifact.

*Have another workflow, that is triggered by the event "workflow_run". It runs when the PR-workflow has completed. This second workflow runs in the context of the base repository with write-access GITHUB_TOKEN and all other configured secrets. It can download the artifact from the first workflow run and use this build result to create a comment to the PR.
Important: The incoming artifact data from the first workflow run must still be considered untrusted. But:

When used in a safe manner, like reading PR numbers or reading a code coverage text to comment on the PR, it is safe to use such untrusted data in the privileged workflow context.

See https://securitylab.github.com/research/github-actions-preventing-pwn-requests/ for a complete usage example.
Note: Your screenshot about the configuration for "Fork pull request workflows" has meanwhile been renamed to "Fork pull request workflows in private repositories":

With private repos, you are in control with whom you share your code. So you might decide to trust by default.
But with public repository, anyone can fork the repo.
Update: All links to the github actions blog post series:

*

*Keeping your GitHub Actions and workflows secure Part 1: Preventing pwn requests

*Keeping your GitHub Actions and workflows secure Part 2: Untrusted input

*Keeping your GitHub Actions and workflows secure Part 3: How to trust your building blocks


text:
Q: Binance API Signature with Google Scripts WORKING FIRST BUT NOW NOT I use this script in Google script app to Signature the API Binance and work fine in the last year but now not working why? any solution.
The code
function SignatureTest() {
  var key = 'Key';
  var secret = 'Secret Key';

  var curTime = Number(new Date().getTime()).toFixed(0);
  var string = "symbol=LTCBTC&timestamp=" + curTime;
  var sKey = Utilities.computeHmacSha256Signature(string, secret);
  sKey = sKey.map(function(e) {
      var v = (e < 0 ? e + 256 : e).toString(16);
      return v.length == 1 ? "0" + v : v;
  }).join("");
  var params = {
    'method': 'get',
    'headers': {'X-MBX-APIKEY': key},
    'muteHttpExceptions': true
  };
  var url = "https://api.binance.com/api/v3/allOrders?" + string + "&signature=" + sKey;
  var data = UrlFetchApp.fetch(url, params);
  Logger.log(data.getContentText())
}

the result error:
{
"code": 0,
"msg": "Service unavailable from a restricted location according to 'b. Eligibility' in https://www.binance.com/en/terms. Please contact customer service if you believe you received this message in error."
}
I try to run script above but not working


text:
Q: How to use hyperbus driver file? I am so confused to understand hyperbus to communicate between Traveo II Body Evaluation Board to one hyperram, I read the datasheet (https://www.cypress.com/part/s27kl0641dabhi020) but still not understand how to implement example code. so for that, I search on google and I found this link (https://github.com/torvalds/linux/blob/master/drivers/mtd/hyperbus/hyperbus-core.c) but not found any example code yet so anyone helps me or anyone provides the useful link or one example code?

A: In Linux, drivers/mtd/hyperbus/ implements hyperbus as a Memory Technology Device, also known as an MTD device; so, the hyperbus is accessed via the Linux MTD subsystem. mtd-utils contains example code for accessing the MTD subsystem; see http://linux-mtd.infradead.org/ for further links.
The Linux MTD hyperbus subsystem exports a character device (/dev/mtdN).  An userspace application opens this device (read-write), then does an MEMGETINFO ioctl() to obtain the MTD device information into a struct mtd_info_user structure (defined in <mtd/mtd-user.h>). Operations to read, write, and erase blocks are done via ioctl()s (defined in <mtd/mtd-abi.h>).  (On a Linux workstation, you'll find these in /usr/include/mtd/ if standard C development packages have been installed; on Debian derivatives, they're provided by the linux-libc-dev package.)
On these machines, Device Tree is used to describe the actual hardware, including hyperbus. You do not "configure" the hyperbus from the userspace when you open the character device; each hyperbus is described by a device tree blob (.dtb) or an overlay the kernel loads (or receives from the bootloader like uboot) at bootup.  I assume you already have the Device Tree etc. configured, since you are asking about how to use the character device; the character device(s) are created by the kernel from the Device Tree descriptions, and only show up if the hyperbus(es) have been configured.


text:
Q: Request-URI Too Long Symfony Controller I'm trying to get all the errors from all the queries I do in my project and redirect this errors to a controller called "error" that will treat theses errors as I want. The problem looks like when I redirect all the information goes in the url generated by the function via GET.
I suppose that if this information is sent via POST will disappear this problem but I'm not using obviously any form inside the controller. So, how can I say to the redirect function that these information shouldn't go with the url and instead should go via POST?
Is possible what I'm trying to do?
Inside Controllers:
    try {
        $results = $queries->aQuery();
    } catch (ErrorException $errorException) {
        return $this->redirect($errorException->redirectResponse);
    }

Inside the service query:
public function aQuery(){

    $query="SELECT * FROM blabla ...";
    try {
        $stmt = $this->DB->->prepararQuery($query);
        $stmt->execute();
        $results = $stmt->fetchAll();
    } catch (DBALException $DBALException) {
        $errorException = new ErrorException($this->router->generate('error',
            [
                'errorQuery' => $query,
                'errorData' => "0 => '".$data1."', 1 ....",
                'errorOrigin' => 'a place',
                'errorResponseText' => $DBALException->getMessage()
            ]
        ));
        throw $errorException;
    }
}

The ErrorException:
class ErrorException extends \Exception
{
    /**
     * @var \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public $redirectResponse;

    /**
     * ErrorException constructor.
     * @param \Symfony\Component\HttpFoundation\RedirectResponse $redirectResponse
     */
    public function __construct(string $redirectResponse)
    {
        $this->redirectResponse = $redirectResponse;
    }

}

A: If what you are trying to achieve is a centralized way to handle exceptions have a look at https://symfony.com/doc/4.0/event_dispatcher.html#creating-an-event-listener and use kernel.exception event
public function onKernelException(GetResponseForExceptionEvent $event)
{
    if (! $event->getException() instanceof ErrorException) {
        return;
    }

    // handle your custom ErrorException
    $response = new Response();
    $response->setContent($event->getException()->getMessage());

    // sends the modified response object to the event
    $event->setResponse($response);
}


text:
Q: Dummit Foote Exercise 13.3.15 A Field F is said to be formally real if $-1$ can not be written as sum of squares in F.
let $f(x)$ be an irreducible polynomial in $F[x]$ of odd degree with $\alpha$ as a root.
Now the Question is Prove that $F(\alpha)$ is also Formally real.
What i have done so far is to check that i can not exclude the condition of degree of $f(x)$ being odd. If $f(x)$ is of even order then this need not be the case. For example for  $f(x)=x^2+1$ over $\mathbb{Q}$ we have $i$ as a root and in $\mathbb{Q}(i)$ we have $-1=i^2$. So, i have to use that $f(x)$ is a polynomial of odd degree.
But i am unable to decide how to proceed with this.
Before this exercise there is an exercise if $[F(\alpha):F]$ is odd then $F(\alpha)=F(\alpha^2)$. I have proved this already. I somehow feel i should use this result to prove given result.
But no progress in this way too..
Any small hint would be appreciated.
Thank You.

A: Have you read the hint given in the book? For example suppose there is an irreducible polynomial $f$ of odd degree such that $F(\alpha)$ is not formally real, $\alpha$ a root of $f$. Choose such an irreducible polynomial of minimal degree. If $-1$ can be written as a sum of squares $p_1(\alpha)^2,\ldots,p_m(\alpha)^2$ then this means we have an equation
$$-1 = p_1(\alpha)^2 + \ldots + p_m(\alpha)^2.$$
So this means that under the isomorphism $F(\alpha) \cong F[x]/(f(x))$, the element $\alpha$ on the L.H.S corresponds to $\overline{x}$ the residue of $x$ in the quotient. So this means in the quotient ring we have
$$-1 = p_1(\overline{x})^2 + \ldots + p_m(\overline{x})^2$$
and so therefore in the polynomial ring $F[x]$ we have an equation $-1 + f(x)g(x) = p_1(x)^2 + \ldots + p_m(x)^2$. So by comparing degrees, we see that $\deg g$ is odd and furthermore $\deg g < \deg f$.

Question 1: Why is $\deg g < \deg f$? Hint: What is the maximal degree that a "polynomial"  $p(\overline{x})$ in the quotient can have?
Question 2: I have spelt out enough details, can you use the hint in Dummit and Foote to complete the rest?


text:
Q: query for balance due and due date for entity I am trying to get a list of guests who have not yet fully paid their total charges (those who still have a balance).
I want to display like so:

1231231(reservation id) - John Doe(guest name) 2013-11-17(date due) 153.14(balance due)

without the ( ) of course.
I have tinkered but still can't find a query that is satisfactory.
Here is a link to the SQLFiddle.
If I haven't provided enough info, kindly let me know.

A: Are you looking for something like this?
SELECT r.id,
       CONCAT(g.fname, ' ', g.lname) guest_name,
       r.arrival date_due,
       r.total_price - COALESCE(p.payment_amt, 0) balance_due
  FROM reservations r JOIN guests g
    ON r.guest = g.id LEFT JOIN
(
  SELECT reservation, SUM(payment_amt) payment_amt
    FROM payments
   GROUP BY reservation
) p
    ON r.id = p.reservation
HAVING balance_due > 0

Sample output (based on provided sample data):

|      ID | GUEST_NAME |                        DATE_DUE | BALANCE_DUE |
|---------|------------|---------------------------------|-------------|
| 1000023 |   John Doe | November, 09 2013 00:00:00+0000 |        40.5 |
| 1000022 |   John Doe | November, 09 2013 00:00:00+0000 |        40.5 |
| 1000018 |   John Doe | November, 01 2013 00:00:00+0000 |          54 |
| 1000019 |   John Doe | November, 08 2013 00:00:00+0000 |          54 |
| 1000020 |  Mary Jane | November, 08 2013 00:00:00+0000 |          54 |
| 1000021 |  Mary Jane | November, 08 2013 00:00:00+0000 |          54 |

Here is SQLFiddle demo