how to create a function that enqueues an entire structure and not just an integer

Question: when compiled i receive these messages

[error] variable or field 'Enqueue' declared void
  49  14  C:\weblinky1.cpp    [Error] variable or field 'enqueue' declared void
49 20  C:\weblinky1.cpp    [Error] no match for 'operator*' (operand types are 'documents' and 'node')
49 35  C:\weblinky1.cpp    [Error] no match for 'operator*' (operand types are 'documents' and 'node')
49 45  C:\weblinky1.cpp    [Error] expected primary-expression before 'struct'
50 14  C:\weblinky1.cpp    [Error] variable or field 'dequeue' declared void
50 20  C:\weblinky1.cpp    [Error] no match for 'operator*' (operand types are 'documents' and 'node')
51 14  C:\weblinky1.cpp    [Error] variable or field 'getRear' declared void
51 20  C:\weblinky1.cpp    [Error] no match for 'operator*' (operand types are 'documents' and 'node*')
52 15  C:/weblinky1.cpp    [Error] variable or field 'getFront' declared void
52 21  C:\weblinky1.cpp    [Error] no match for 'operator*' (operand types are 'documents' and 'node*')
C:\Users\marshalee\Desktop\DSLabTest1_1300054246\weblinky1.cpp In function 'int main()':
60 11  C:\weblinky1.cpp    [Error] no match for 'operator*' (operand types are 'documents' and 'node*')
114    49  C:\weblinky1.cpp    [Error] 'enqueue' was not declared in this scope
122    39  C:\weblinky1.cpp    [Error] 'dequeue' was not declared in this scope
126    27  C:\weblinky1.cpp    [Error] no match for 'operator==' (operand types are 'documents' and 'long long int')
138    42  C:\weblinky1.cpp    [Error] 'deletedocsize' was not declared in this scope
147    48  C:\weblinky1.cpp    [Error] 'searchfoldername' was not declared in this scope
157    32  C:\weblinky1.cpp    [Error] 'searchID' was not declared in this scope
165    33  C:\weblinky1.cpp    [Error] 'averagedocsize' was not declared in this scope
173    29  C:\weblinky1.cpp    [Error] could not convert 'isEmpty()' from 'void' to 'bool'
182    36  C:\weblinky1.cpp    [Error] 'getRear' was not declared in this scope
193    45  C:\weblinky1.cpp    [Error] 'getFront' was not declared in this scope
C:\weblinky1.cpp  At global scope:
221    19  C:\weblinky1.cpp    [Error] variable or field 'enqueue' declared void

bellow is my complete code
    enter code here/**
 * Queue implementation using linked list in C.
 */

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>

#define CAPACITY 100    // Queue max capacity

/* Queue structure definition */
   struct documents
{
     int id;
    char docname[50];
    char foldername[50];
    float docsize;
    struct document * next;
    struct document * previous;

};

//Delacre document variable
struct documents Queue;

//Create node for linked list
struct node
{
    struct documents Queue;
    struct node* previous;
    struct node* next;
};

// Creating an empty linked list
struct node * rear = NULL;
struct node * front = NULL;

/* Queue size */
unsigned int size = 0;

void enqueue(Queue ** rear, Queue ** front, struct documents Queue);
void dequeue(Queue ** front);
void getRear(Queue * rear);
void getFront(Queue * front);
void isEmpty();
void isFull();

int main()
{
    int ch, data;
    Queue *rear, *front;
     struct documents Queue;
    int id;
    float docsize;
    char* docname;
    char* foldername;

    rear  = NULL;
    front = NULL;

    /* Run indefinitely until user manually terminates */
    while (1)
    {
        /* Queue menu */
        printf("--------------------------------------------\n");
        printf("  QUEUE LINKED LIST IMPLEMENTATION PROGRAM  \n");
        printf("--------------------------------------------\n");
        printf("1. Enqueue\n");
        printf("2. Dequeue\n");
        printf("3. Delete by Size of Document\n");
        printf("4. Display Documents based on Folder Name\n");
        printf("5. Enter ID to Display Index where Documents was
          found\n");
        printf("6. Display Document Size Average\n");
        printf("7. Size of the Queue\n");
        printf("8. Get Rear\n");
        printf("9. Get Front\n");
        printf("0. Exit\n");
        printf("--------------------------------------------\n");
        printf("Select an option: ");

        scanf("%d", &ch);

        /* Menu control switch */
        switch (ch)
        {
            case 1:

                 printf("\nEnter Document ID#: ");
                   scanf("%d", &Queue.id);
                    Queue.id = id;
                    printf("Enter Document size#: ");
                    scanf("%f", &Queue.docsize);
                     Queue.docsize = docsize;
                     printf("Enter Document name: ");
                      scanf("%s", &Queue.docname);
                       strcpy(Queue.docname, docname);
                       printf("Enter folder name: ");
                        scanf("%s", foldername);
                         strcpy(Queue.foldername, foldername);

                // Enqueue function returns 1 on success
                // otherwise 0
                if (enqueue(&rear, &front, Queue))
                    printf("Document added to queue.");
                else
                    printf("Queue is full.");

                break;

            case 2:
                Queue = dequeue(&front);

                // on success dequeue returns element removed

                if (Queue == NULL)
                    printf("Queue is empty.");
                else
                    printf("Queue => %d", Queue.front);

                break;

           //Delete by Size of Document
           case 3:

                 printf("Enter Document size: ");
                    scanf("%f", &docsize);
                    deletedocsize(docsize);

                break;

        //Display Documents based on Folder Name
        case 4:

                 printf("Enter Document Folder Name: ");
                     scanf("%s", foldername);
                    searchfoldername(foldername);

                break;

        //Enter ID to Display Index where Documents was found
        case 5:

                 printf("Enter Document ID#: ");
                     scanf("%f", &id);
                    searchID(id);

                break;

        //Display Document Size Average
        case 6:

                 averagedocsize();

                break;

            case 7:

                // isEmpty() function returns 1 if queue is emtpy
                // otherwise returns 0
                if (isEmpty())
                    printf("Queue is empty.");
                else
                    printf("Queue size => %d", size);

                break;

            //get rear of document queue
            case 8:
                data = getRear(rear);

                if (Queue == Queue.rear)
                    printf("Queue is empty.");
                else
                    printf("Rear => %d", Queue.rear);

                break;

            case 9:

                Queue = getFront(front);

                if (Queue == NULL)
                    printf("Queue is empty.");
                else
                    printf("Front => %d", Queue.front);

                break;

            case 0:
                printf("Exiting from application.\n");
                exit(0);

            default:
                printf("Invalid choice, please input number between (0-
       5).");
                break;
        }

        printf("\n\n");
    }
}

/**
 * Enqueues/Insert an element at the rear of a queue.
 * Function returns 1 on success otherwise returns 0.
 */
void enqueue(Queue *q)
{
     Queue * temp= NULL;

    // Check queue out of capacity error
    if (isFull())
    {
        return 0;
    }

    // Create a new node of queue type
    temp = (Queue *) malloc (sizeof(Queue));

    // Assign data to new node
    temp->docs= en;

    // Initially new node does not point anything
    temp->next = NULL;
    temp->previous = NULL;

    // Link new node with existing last node
    if ( (*rear) )
    {
        (*rear)->next = temp;
    }

    // Make sure newly created node is at rear
    *rear = temp;

    // Link first node to front if its NULL
    if ( !( *front) )
    {
        *front = *rear;
    }

    // Increment quque size
    size++;

    return 1;
}

/**
 * Gets, element at rear of the queue. It returns the element
 * at rear of the queue on success otherwise return as
 * error code.
 */
int getRear(Queue * rear)
{
    //  if queue is empty otherwise rear.
    return (isEmpty())
            ? NULL
            : rear->Queue.rear;
}

/**
 * Gets, element at front of the queue. It returns the element
 * at front of the queue on success otherwise return  as
 * error code.
 */
int getFront(Queue * front)
{
    // if queue is empty otherwise front.
    return (isEmpty())
            ? NULL
            : front->Queue.front;
}

/**
 * Checks, if queue is empty or not.
 */
int isEmpty()
{
    return (size <= 0);
}

/**
 * Checks, if queue is within the maximum queue capacity.
 */
int isFull()
{
    return (size > CAPACITY);
}

// deleting any node based on position
void Delete(int n)
{
    struct documents temp1 =front;

      if(n == 1){
        front= temp1->next;
        free(temp1);
        return;
      }
      int i for(i =0; i<n-2; i++)
        temp1 = temp1->next;
      struct node* temp2 = temp1->next;
        temp1->next = temp2 -> next;
        free(temp2);
}

 //or using this method
void Dequeue(int n)
{
    struct documents temp1;

    if(Front == NULL)
    {
        printf("Queue is empty.\n");
    }
    else
    {
       int currentIndex = 0;
       struct documents *temp1 = (struct documents*)malloc(sizeof(struct
        documents));
        bool traversing = true;

        tem1 = Front;
        temp1 = temp1->Queue;

        while(temp1 !=NULL) {
            if(temp1.id == n)
                {
                    temp1->previous->next=temp1->next;
                    free(temp1);
                printf("Item Deleted", currentIndex);
                return;
            }

            currentIndex++;

            temp1 = temp1->next;
            if (temp1 == NULL) {
                temp1 = temp1->previous;
            }
            temp1 = temp1->Queue;
        }
    }
}

//search by foldername
void searchfoldername(char foldername[])
{
    struct documents Queue;

    if(Front == NULL)
    {
        printf("Queue is empty.\n");
    }
    else
    {
    struct documents *tempp = (struct documents*)malloc(sizeof(struct
     documents));
        bool traversing = true;
        int currIndex = 0;

        tempp = Front;
        tempy = tempp->Queue;
        Front = Front->next;

        while(traversing) {
            if(strcmp(tempy->foldername, foldername) == 0))
            {
                printf(" ID: %d\n", tempy->id);
                printf("Document Name: %s\n", tempy->docname);
                printf("Folder Name: %s\n", tempy->foldername);
                printf("Document Size: %d\n", tempy->docsize);
                printf("Document positioned at index: %d", currIndex);
                return tempy.foldername;
            }

            currIndex++;

            tempp = tempp->next;
            if (tempp == NULL) {
                tempp = tempp->previous;
            }
            tempy = tempp->Queue;
        }
    }
}

//delete document size
Void deletedocsize(int docsize)
{
    struct documents Queue;

    if(Front == NULL)
    {
        printf("Queue is empty.\n");
    }
    else
    {
        struct documents *tempp = (struct documents*)malloc(sizeof(struct
          documents));
     bool traversE = true;
        int currIndex = 0;

        tempp = Front;
        tempy = tempp->Queue;
        front = front->next;
            while(traversE) {
            if(strcmp(tempy->docsize, docsize) <= Queue.docsize))

            {
                free(tempp);
                    return;
            }

            currIndex++;
              tempp = tempp->next;
            if (tempp == NULL) {
                tempp = tempp->previous;
            }
            tempy = tempp->Queue;
        }
    }
}
};

//Enter ID to Display Index where Documents was found
void searchID(int id)
{
    struct documents Queue;

    if(Front == NULL)
    {
        printf("Queue is empty.\n");
    }
    else
    {
        struct documents *tempp = (struct documents*)malloc(sizeof(struct
         documents));
        bool traversing = true;
        int currIndex = 0;

        tempp = Front;
        tempy = tempp->Queue;
        Front = Front->next;

        while(traversing) {
            if(strcmp(tempy->id, id) == Queue.id))
            {
                printf("Document positioned at index: %d", currIndex);
                return tempy.id;
            }

            currIndex++;

            tempp = tempp->next;
            if (tempp == NULL) {
                tempp = tempp->previous;
            }
            tempy = tempp->Queue;
        }
    }
}

//find and display the Average of all document size
void averagedocsize()
{
    struct documents Queue;

    if (front == NULL)
    {
        printf("\n ooops List is Empty\n");
    }
    else
    {
        struct documents *tempp = (struct documents*)malloc(sizeof(struct
           documents));
        int count = 0;
        tempp = front;
        Queue = tempp->Queue;
        while (tempp != NULL)
        {
            if(strcmp(Queue.docsize, docsize) == 0) {
                sum=0;
                while (count<=rearindex)
                {
                    sum = sum + docsize;
                    average =rearindex;
                }

                count++;
            }
            tempp = tempp->next;
            if (tempp == NULL) {
                printf("Average Document Size is : %d\n\n", average);
                break;
            }
            Queue = tempp->;
        }
        free(tempp);
    }
}

Comment: `Queue` is _not_ declared as a type, so `Queue **` [or `Queue *`] is invalid. And, your `typedef` declares the `struct` name `Book` but _not_ a type of `Book` (i.e. it's legal but a bit malformed). Try: `typedef struct Book { what_you_already_have } Book;` Then, do `void Enqueue(Book **rear, Book **front, Book *en)`. When you did `struct Book Queue;`, `Queue` is merely a global instance of type `struct Book`--it does _not_ declare a _type_ of `Queue`.
Comment: When I compile this code I get a bunch of errors, but none of them is the error you say you got.  Please read and follow the [instructions for producing a minimal, complete, verifiable example program](https://stackoverflow.com/help/mcve).
Comment: Please don't shout.
Comment: While the code is certainly incorrect, it is hard to see how it would yield `[error] variable or field 'Enqueue' declared void` - it seems likely that this is not the code that generated the error.  Copy & paste your code and the errors carefully - do not remove content - for example the error message will include information such as the line number - don't remove that, and ensure the code you post includes that line.  Also your title bares no relation to the body text - the title is much broader (too broad), and the body very specific (about an error message).
Comment: From a style point of view, the name `Queue` is too generic to refer to specifically a queue of books, and the type is not a queue, but an element of a queue. `typedef Book* BookQueue ;` perhaps makes more sense, then the `Enqueue` parameters would have type `BookQueue*`.
Comment: thank you. I have updated the post to include my current code.
Comment: thank you. I have updated the post to include my current code.
Comment: In my opinion, if you're confused by the typedef (which seems to be the case given that the syntax is pretty mangled), just skip it.  Defining variables with "struct Queue A" is more clear than using a (mangled) typedef and defining variables with "Queue A".  Just don't use typedef's at all.
Answer: You have defined a variable Queue rather than a type, and the typedef is incomplete :
typedef struct Book
{
    int bID;
    char bName;
    char FolderName;
    struct Book * next
    struct Book * next
} Queue ;

void Enqueue(Queue ** rear, Queue ** front, Queue en) ;


How can I select a unit in Unity and activate the Canvas on that unit?

Question: I'm currently working on a turn based strategie game and I would like to give the player more information for each unit they got.

The Code is as followed:
    public void UnitSelection ()
    {
        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast (ray, out hit, Mathf.Infinity))
        {
            if (hit.collider.tag == "Unit Player 1")
            {
                // How can I select the Canvas from here + Canvas.SetActive(true)
            }
        }
    }

I can select a unit with the mouse but I don't know how to get to the Canvas on that GameObject.
Should I work with a tag (isn't that bad practice?) or with other methods?
If you need any more info just write it in a comment. I will add everything you need.
Thanks in advance.
Answer:
Assuming hit.collider is the parent object ArmoredBear_a06 of the Canvas you could use GetComponentInChildren
public void UnitSelection ()
{
    if (Physics.Raycast (Camera.main.ScreenPointToRay(Input.mousePosition), out var hit, Mathf.Infinity))
    {
        var hitCollider = hit.collider;

        if (hitCollider.CompareTag("Unit Player 1"))
        {
            // pass in true to also get inactive or disabled components
            var canvas = hitCollider.GetComponentInChildren<Canvas>(true);

            if(!canvas)
            {
                Debug.LogWarning($"Hitting {hitCollider.name} but no Canvas found in children");
                return;
            }

            canvas.gameObject.SetActive(true);
        }
    }
}

Or alternatively if you anyway know that the Canvas is always the first child you can use transform.GetChild
public void UnitSelection ()
{
    if (Physics.Raycast (Camera.main.ScreenPointToRay(Input.mousePosition), out var hit, Mathf.Infinity))
    {
        var hitCollider = hit.collider;

        if (hitCollider.CompareTag("Unit Player 1"))
        {
            var canvas = hitCollider.tramsform.GetChild(0);

            canvas.gameObject.SetActive(true);
        }
    }
}

Answer: You have a several options to get a canvas.
First
Get Canvas directly (if collider on the root object) like this:
public void UnitSelection ()
{
   Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
   RaycastHit hit;
   if (Physics.Raycast (ray, out hit, Mathf.Infinity))
   {
      if (hit.collider.tag == "Unit Player 1")
      {
         Canvas canv = hit.collider.GetComponentInChildren<Canvas>(true);
         canv.gameObject.SetActive(true);
         //or you can change only canvas state like this canv.enabled = true;
      }
   }
}

Second:
Or you can attach script to your Unit and change state of Canvas internal:
Part of Bot Script:
public class Bot : MonoBehaviour
{
    [SerializeField] private GameObject canvasObject;

    public void ChangeStateCanvas(bool state)
    {
        canvasObject.SetActive(state);
    }
}

Script with change canvas state:
public void UnitSelection ()
{
   Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
   RaycastHit hit;
   if (Physics.Raycast (ray, out hit, Mathf.Infinity))
   {
      if (hit.collider.tag == "Unit Player 1")
      {
         hit.collider.GetComponent<Bot>().ChangeStateCanvas(true);
      }
   }
}

Comment: First will fail. See [my answer](https://stackoverflow.com/a/62891235/7111561): You would need to pass in `true` in order to find inactive or disabled components. Second is valid but a bit overkill ;)


Default to original language in nodes list

Question: I set up a multilingual blog with Drupal 8 (in English and Chinese), I want to list articles according to current language in the front page.
However, if an article does not has an translation in the current language, I want it to default to the original untranslated version(whatever language), with a hint like "This content is not available in Chinese, we are showing the original article in English."
Assuming that I have 3 blog articles (nodes), with or without translation:

Article 1 (original language: English; translated to: Chinese)
Article 2 (original language: Chinese; translated to: English)
Article 3 (original language: English)

When a user visits the English front page at example.com/en, they will see:

Article 1 (in English, original)
Article 2 (in English, translated)
Article 3 (in English, original)

which is the default behaviour of Drupal 8.

Now, when a user visits the Chinese front page at example.com/zh-hans, I would like them to see:

Article 1 (in Chinese, translated)
Article 2 (in Chinese, original)
Article 3 (in English, with a hint)

However, Drupal 8 out of the box will display:

Article 1 (in Chinese, translated)
Article 2 (in Chinese, original)

I tried editing the front page as it is a view in Drupal 8, but with the filters in view I could not achieve this.

(Filters in view)
Do I need to implement a custom filter for the front page view? Please suggest where should I start, I have no idea how to do this.
Thanks!
Comment: Hi Radium, have you been able to resolve this?
Answer: See the solution to How do I get Views content items in "my language" but fall back to "default" if the content isn't translated? whether it helps just by configuring in admin. It seems to solve the same problem.
Unfortunately, I have the same problem, and I can't get the solution described there to work. Reading all the issues linked in meta Make multilingual views work, it seems to me that there is no built-in solution. I tried to implement a hook_views_post_execute() and to filter the ViewExecutable $view manually, like in the following, but it did not work - either still shows multiple translations per entity, or entities are missing:
# File modules/contrib/modulename/modulename.module
# Enabled in admin/extend
function modulename_views_post_execute(ViewExecutable $view)
{
  $contentLangcode = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();

  # trying either one of:
  # $Filtered = filterLangcodeOrEn($contentLangcode, $view->result);
  $Filtered = filterNodeOnce($view->result);

  $view->result = $Filtered;
  $view->total_rows = count($Filtered);
}

function filterNodeOnce($rows)
{
  $Nodes = array();
  foreach ($rows as $row) {
    $Nodes[$row->nid] = $row;
  }

  return array_values($Nodes);
}

function filterLangcodeOrEn($contentLangcode, $rows)
{
  # group by nid
  $EntitiesLangcodesRow = array();
  foreach ($rows as $row) {
    $EntitiesLangcodesRow[$row->nid][$row->node_field_data_langcode] = $row;
  }

  # select
  $Filtered = array();
  foreach ($EntitiesLangcodesRow as $LangcodesRow) {
    if (isset($LangcodesRow[$contentLangcode])) {
      $Filtered[] = $LangcodesRow[$contentLangcode];
    }
    else if (isset($LangcodesRow["en"])) {
      $Filtered[] = $LangcodesRow["en"];
    }
  }
  return $Filtered;
}


Proof of chain rule using little-oh; Hunter

Question: The following is a proof of the chain rule from John K. Hunter's lecture notes. It uses the little-oh concept, i.e. a function $f(h)$ is little-oh of $h$ if $\lim_{h\to 0} f(h)/h=0$. Come to think of it, the proof below answer's this question. Anyway, I have only one question about the proof at the very end.
The proof uses the following proposition:

Proposition 8.11. Suppose that $f: (a,b)\to \mathbb{R}$. Then $f$ is differentiable at $c\in (a,b)$ if and only if there exists a constant $A\in\mathbb{R}$ and a function $r: (a-c,b-c)\to\mathbb{R}$ such that $$f(c+h)=f(c)+Ah+r(h), \quad \lim_{h\to 0}\frac{r(h)}{h}=0.$$ In that case, $A=f'(c)$.

Theorem 8.21 (Chain rule). Let $f: A\to\mathbb{R}$ and $g: B\to\mathbb{R}$ where $A\subset\mathbb{R}$ and $f(A)\subset B$ and suppose that $c$ is an interior point of $A$ and $f(c)$ is an interior point of $B$. If $f$ is differentiable at $c$ and $g$ is differentiable at $f(c)$, then $g\circ f: A\to\mathbb{R}$ is differentiable at $c$ and $$(g\circ f)'(c)=g'(f(c))f'(c).$$

In the proof below, I think there is a typo in the tagged equation (it should be = instead of <).

Proof. Since $f$ is differentiable at $c$, there is a function $r(h)$ such that
$$
f(c+h)=f(c)+f^{\prime}(c) h+r(h), \quad \lim _{h \rightarrow 0} \frac{r(h)}{h}=0,
$$
and since $g$ is differentiable at $f(c)$, there is a function $s(k)$ such that
$$
g(f(c)+k)=g(f(c))+g^{\prime}(f(c)) k+s(k), \quad \lim _{k \rightarrow 0} \frac{s(k)}{k}=0 .
$$
It follows that
$$
\begin{aligned}
(g \circ f)(c+h) & =g\left(f(c)+f^{\prime}(c) h+r(h)\right) \\
& =g(f(c))+g^{\prime}(f(c)) \cdot\left(f^{\prime}(c) h+r(h)\right)+s\left(f^{\prime}(c) h+r(h)\right) \\
& =g(f(c))+g^{\prime}(f(c)) f^{\prime}(c) \cdot h+t(h)
\end{aligned}
$$
where
$$
t(h)=g^{\prime}(f(c)) \cdot r(h)+s(\phi(h)), \quad \phi(h)=f^{\prime}(c) h+r(h) .
$$
Since $r(h) / h \rightarrow 0$ as $h \rightarrow 0$, we have
$$
\lim _{h \rightarrow 0} \frac{t(h)}{h}=\lim _{h \rightarrow 0} \frac{s(\phi(h))}{h} .
$$
We claim that this limit exists and is zero, and then it follows from Proposition 8.11 that $g \circ f$ is differentiable at $c$ with
$$
(g \circ f)^{\prime}(c)=g^{\prime}(f(c)) f^{\prime}(c) .
$$
To prove the claim, we use the facts that
$$
\frac{\phi(h)}{h} \rightarrow f^{\prime}(c) \quad \text { as } h \rightarrow 0, \quad \frac{s(k)}{k} \rightarrow 0 \quad \text { as } k \rightarrow 0 .
$$
Roughly speaking, we have $\phi(h) \sim f^{\prime}(c) h$ when $h$ is small and therefore
$$
\frac{s(\phi(h))}{h} \sim \frac{s\left(f^{\prime}(c) h\right)}{h} \rightarrow 0 \quad \text { as } h \rightarrow 0 .
$$
In detail, let $\epsilon>0$ be given. We want to show that there exists $\delta>0$ such that
$$
\left|\frac{s(\phi(h))}{h}\right|<\epsilon \quad \text { if } 0<|h|<\delta .
$$
First, choose $\delta_{1}>0$ such that
$$
\left|\frac{r(h)}{h}\right|<\left|f^{\prime}(c)\right|+1 \quad \text { if } 0<|h|<\delta_{1}
$$
If $0<|h|<\delta_{1}$, then
$$
\begin{align}
|\phi(h)| & \leq\left|f^{\prime}(c)\right||h|+|r(h)| \\
& <\left|f^{\prime}(c)\right||h|+\left(\left|f^{\prime}(c)\right|+1\right)|h| \\
& <\left(2\left|f^{\prime}(c)\right|+1\right)|h| \tag{*}.
\end{align}
$$
Next, choose $\eta>0$ so that
$$
\left|\frac{s(k)}{k}\right|<\frac{\epsilon}{2\left|f^{\prime}(c)\right|+1} \quad \text { if } 0<|k|<\eta
$$
(We include a "1" in the denominator on the right-hand side to avoid a division by zero if $f^{\prime}(c)=0$.) Finally, define $\delta_{2}>0$ by
$$
\delta_{2}=\frac{\eta}{2\left|f^{\prime}(c)\right|+1}
$$
and let $\delta=\min \left(\delta_{1}, \delta_{2}\right)>0$.
If $0<|h|<\delta$ and $\phi(h) \neq 0$, then $0<|\phi(h)|<\eta$, so
$$
|s(\phi(h))| \leq \frac{\epsilon|\phi(h)|}{2\left|f^{\prime}(c)\right|+1}<\epsilon|h| .
$$
If $\phi(h)=0$, then $s(\phi(h))=0$, so the inequality holds in that case also. This proves that
$$
\lim _{h \rightarrow 0} \frac{s(\phi(h))}{h}=0 .
$$

If $\phi(h)= 0$, then $s(\phi(h))=0$. Why? I have a far-fetched idea. The author states that we have $ \frac{s\left(f^{\prime}(c) h\right)}{h} \rightarrow 0 $ as $h \rightarrow 0$. If $o(h)$ denotes all functions that approach zero faster than $h$ as $h\to 0$, and if $s(h)\in o(h)$, then by limit substitution also $s(ah)\in o(h)$, where $a$ is a constant. However, what happens when $a=f'(c)=0$, as presumably can be the case. Then does $ \frac{s\left(f^{\prime}(c) h\right)}{h} \rightarrow 0 $ when $h\to 0$? Only if $s(0)=0$. I don't know, maybe there's a simpler explanation.
Answer:
Yes that seems to be a careless typo in the text you flagged.

I believe that the conditions imposed on $r(h)$  in Proposition 8.11  ought to have stated  explicitly that $r(h)$ is continuous as $h\to 0$. Then it is evident that $r(0)$ must be zero. The same applies to the expression $s(k)$.

There is a much cleaner conceptual approach to the definition of the derivative that was developed by Caratheodory about 100 years ago (based upon the simpler concept of continuity) . See e.g Question about Caratheodory's approach and the reference to Bernstein' notes cited therein. The Chain Rule can be proved in one line using this approach.

A nice expository article explores this in detail:
The Derivative á la Carathéodory
Stephen Kuhn
The American Mathematical Monthly, Vol. 98, No. 1 (Jan., 1991), pp. 40-44 (5 pages)
https://www.jstor.org/stable/2324035
Quoting from its introduction:

But there is another, less well known, characterization of the
derivative which appears in the last textbook [2] written by
Constantin Caratheodory (1873-1950). This formulation is not only
elegant but useful on both theoretical and pedagogical grounds. The
proofs of many important theorems concerning differentiability become
significantly easier and, in the process, some of the less
enlightening details are rightly submerged. Caratheodory's formulation
also gives us a much clearer view of the fact that continuity is
essential for differentiability; indeed, the definition itself
contains the necessary continuity. This formulation, which shifts the
details from the theory of limits to the theory of continuous
functions, requires that our students develop a clearer understanding
of continuity than is typical and it demands that we reevaluate this
understanding and continually reinforce it. We believe that
Caratheodory's insight deserves to be better known and we hope that
the present article will help in that effort.

The multi-variable extension of Caratheodory's approach is explained in this article:

On the Differentiability of Functions of Several Variables
Michael W. Botsko, Richard A. Gosser
The American Mathematical Monthly, Vol. 92, No. 9 (Nov., 1985), pp. 663-665 (3 pages)
https://www.jstor.org/stable/2323717
Comment: By solving for $r(h)= f(c+h) -f(c)- f'(c) h$ one can deduce that $r(h)$ is continuous. I  should have pointed that out earlier.
Comment: Thank you for the answer! Interesting. $r(h)$ in Proposition 8.11 is nothing more than the Peano form of the remainder, right? Nowhere have I seen it stated being continuous, e.g. on [Wikipedia](https://en.wikipedia.org/wiki/Taylor%27s_theorem#Statement_of_the_theorem), but maybe that's just obvious?


Drag the view by touching below the object and move accordingly

Question: I have created an simple drag drop application in android.But now i want to move the view on x-axis without touching the view itself.the View should move from anywhere on the screen where user touched the screen.How can I achieve this effect.
Currently i am using this tutorial for drag drop operations.I have applied the OnTouchListner on parent view.But i think this is not the good idea.Please can anyone suggest me the correct way of doing it.
Here is my code
<code> rel.setOnTouchListener(this);

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                dX = v.getX() - event.getRawX();
                dY = v.getY() - event.getRawY();
                lastAction = MotionEvent.ACTION_DOWN;
                break;

            case MotionEvent.ACTION_MOVE:
                v.setY(event.getRawY() + dY);
                v.setX(event.getRawX() + dX);
                lastAction = MotionEvent.ACTION_MOVE;
                break;

            case MotionEvent.ACTION_UP:
                if (lastAction == MotionEvent.ACTION_DOWN)
                    Toast.makeText(MainActivity.this, "Clicked!", Toast.LENGTH_SHORT).show();
                break;

            default:
                return false;
        }
        return true;
    }
</code>
and my xml code is
<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rel"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <ImageView
            android:id="@+id/ball"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/ball" />
</RelativeLayout>
</code>
Comment: can you remove `v.setY(event.getRawY() + dY);` line from `case MotionEvent.ACTION_MOVE:` ?
Comment: @MayurRaval yes and it will now move only in x axis
Answer: Finally this problem is resolved by making some changes in my code.Hope this will help someone achieving this effect.
<code>@Override
public boolean onTouch(View v, MotionEvent event) {

    switch (event.getActionMasked()) {
        case MotionEvent.ACTION_DOWN:
            dx = v.getX() - event.getRawX();
            dy = v.getY() - event.getRawY();
            ball_dx = ball.getX();
            lastAction = MotionEvent.ACTION_DOWN;
            break;

        case MotionEvent.ACTION_MOVE:
            //  ball.setY(event.getRawY() + dy);
            if ((event.getRawX() + dx + ball_dx) < screenwidth - 80 && (event.getRawX() + dx + ball_dx) > 10)
                ball.setX(event.getRawX() + dx + ball_dx);
            lastAction = MotionEvent.ACTION_MOVE;
            break;

        case MotionEvent.ACTION_UP:
            if (lastAction == MotionEvent.ACTION_DOWN)
                Toast.makeText(MainActivity.this, "Clicked!", Toast.LENGTH_SHORT).show();
            break;
        default:
            return false;
    }
    return true;
}
</code>
Answer: As I commented , I am writing that as answer May be it help someone.This code will move view on X axis only
<code>@Override
public boolean onTouch(View v, MotionEvent event) {

    switch (event.getActionMasked()) {
        case MotionEvent.ACTION_DOWN:
            dX = v.getX() - event.getRawX();
            dY = v.getY() - event.getRawY();
            lastAction = MotionEvent.ACTION_DOWN;
            break;

        case MotionEvent.ACTION_MOVE:
           //remove this v.setY() line
            v.setX(event.getRawX() + dX);
            lastAction = MotionEvent.ACTION_MOVE;
            break;

        case MotionEvent.ACTION_UP:
            if (lastAction == MotionEvent.ACTION_DOWN)
                Toast.makeText(MainActivity.this, "Clicked!", Toast.LENGTH_SHORT).show();
            break;

        default:
            return false;
    }
    return true;
}
</code>


How to mask a specific value without knowing exact key, within a JSON string, in Java

Question: I am receiving a JSON in the form of a string, need to mask a piece of information, however the JSON strucutre and key-names are always different but value's pattern is recognizable. Question being, what is an efficient way to traverse through String/JSONObject to mask that piece of data.
I've tried turning the String into a JSONObject and traverse through every embedded JSONObject/Array, detect the pattern, and replace that original value with its masked version. But this seems very time consuming when Logging this information out to console.
Value's pattern for reference is a 9-digit (Long) number.
Structure always varies from "{"key1":[{"innerKey1":123456789}]}" to "{"key1":"value1", "key2":{"innerKey1":123456789}"
Sample result : "{"key1":[{"innerKey1":"XXXXXX789"}]}"
Comment: Could you also post the expected result against the JSON string you received?
Comment: Ultimately I would have to return a String in the following manner, as for the first example I gave herein:  "{"key1":[{"innerKey1":"XXXXXX789"}]}"
Answer: If the JSON structure is always provided as optimized single line string you could just find the value in the string and replace it or get even more elaborate and use a regular expression to find the innerKey1:12345 match and replace that.
If this is just for logging purposes you can even implement this as a filter, depending on your logging framework it might be even configurable instead of having to code it.
Comment: Yes, my first alternative was playing w actual string itself, wondering if there was a JSONObject or ObjectMapper method that I wasn't taking advantage of, but I'll keep on the lookout.


Sublime Text 2 Tab Auto-Complete

Question: I have mostly worked in Adobe Dreamweaver (don't hate too much, I really like some of its feature that I'm about to mention). I'd really like to become proficient in Sublime Text 2. There are two things I'm looking to figure out:

When I start typing a tag and it auto suggests what it thinks I'm typing, I can hit tab or enter to auto-complete the tag. But when I do this, it makes the closing tag too. I hate this, because I go back to change things often, then when I tab to auto complete, it adds in the entire closing tag. So my question is can I make it ONLY auto-complete the opening tag when I hit tab or enter? (btw, I have emmet installed too)
My next question, if anyone is familiar with Dreamweaver, whenever I open an HTML file, it opens all corresponding files in a sub menu below the tab. So I open say, index.html, and below it appears, automatically, my css file, js file, and any files that I've put in the html file. With Sublime Text, I have to go to the trouble to open all those files with it. Is there any plugin or way to make Sublime replicate this?

Thanks so much for any help anyone can provide!
Answer: This is a bit old, and maybe you've discovered the answer, but for #1, you can set the "auto_complete_commit_on_tab" setting to true in your user settings.
http://www.sublimetext.com/docs/2/auto_complete.html
Comment: @Abhinay do you have auto_complete_commit_on_tab set to true? If so, I think enter becomes only a new-line.
Comment: @Andrew Yeah,I figured it out after asking you, but thanks for help.I saw my theme was actually overriding this command and setting it to auto_complete_commit_on_tab true.Still your solution works for me indirectly. thanks.
Comment: Thank you very much! It's the little things that matter and this worked.
Comment: @Andrew Hey can you tell me what do i need to do if my autocompletion doesn't work,its going to the new line on hitting enter instead of completion. can you help ?

Sublime Text 2 Tab Auto-Complete


Flowable delegateExpression in service task is not working

Question: The flowable version which I'm using is 6.4.1.
<code>@Component

public class MyClass implements JavaDelegate {

    @Autowired
    private MySampleService mySampleService;

    @Override
    public void execute(DelegateExecution delegateExecution){
        sampleService.doSomeTask();
    }
}
</code>
Here, myClass bean would be created for class MyClass. Hence, in the bpmn, I can use it like flowable:delegateExpression="${myClass}".
But I'm getting error
<code>"unknown property used in expression: ${myClass}" </code>
And without delegateExpression, mySampleService would be null.
Any suggestions?
Comment: How are you creating the process engine? Are you using the Spring Boot starters or are you manually creating it?
Comment: Earlier I was creating it manually, which needed a few more configurations. Here is the link to the flowable forum which can help -> https://forum.flowable.org/t/autowired-not-working-in-javadelegate-for-servicetask/6849/9
Comment: Glad that you resolved it. Btw I am one of the main Flowable developers. We answer questions both here and the Forum
Comment: Yeah, I recognized with the name. Thank you so much for the response, I had tried almost everything whatever I knew. That's I decided to post it online.
Answer: There are two ways to configure flowable:

Manually - When using 'regular' Spring, you also need to register the ProcessEngineFactoryBean. This will take the engineConfiguration and create a SpringExpressionManager (https://github.com/flowable/flowable-engine/blob/master/modules/flowable-spring/src/main/java/org/flowable/spring/SpringExpressionManager.java) that has access to the expression manager.
SpringBoot, provides out of the box configuration. One only need to provide the needed beans, like DataSource, AsyncExecutor, etc. (based on you the scenario) and spring boot will take care of the rest.


Formula to adjust a note by cents

Question: I'm trying to find a formula to adjust a note frequency by a variable number of cents. So for example if a middle C was played then how do you find "N" cents adjustment to that frequency? I hope I'm explaining this correctly.
I thought it was something like:
x * (1 + (N * 0.00057778951))
where x is the original frequency, but it just doesn't seem to be correct.
Answer: A cent is the 1200th part of an octave which is a factor of 2.
Consequently, an adjustment of N cents means multiplying your frequency by 2N/1200.
Comment: So using my formula it would be x*2^(y/1200). That seems to be what I'm looking for, since making y=100 changes the note by 1 semitone.

Formula to adjust a note by cents


javascript code getTimezoneOffset

Question: I am a bit confused with this, i know the code gives me the time difference from GMT, but for which city or country? How do i get the time difference between gmt and the time in Kabul Afghanistan.
<code>            var now = new Date();
            alert(now.getTimezoneOffset());
</code>
Comment: It's the offset between current user's computer's timezone and GMT.
Answer: The difference is the value showing in the alert.
Answer: It gives you the offset of the client local time zone.
To get the offset of different time zone, use external libraries as stated here, or just get the offset manually and use it, as explained here.

javascript code getTimezoneOffset


Custom build Mootools implementing in Joomla 1.5

Question: Greetings everyone.. can someone guide me please on how to implement my custom mootools..in Joomla 1.5
i have these files below
PHP FILE

promocode.php

CSS (for my js)

sexyalertbox.css

Javascripts

mootools1.js
mootools-more.js
sexyalertbox.v1.js
sexyalertbox.packed.js
jquery

i managed to put the php file in one of my component in joomla which is the ignite_gallery and display it like i wanted it to be.. but the only thing i'm lacking is that my mootools is not working at all, unlike when i run it from my root file outside the Joomla.
i am using Joomla 1.5.22 and my mootools version is 1.2 and i am using the rhuk_milkyway template
the solutions i have tried already are declaring this code below in my php file
<?php
  $document =& JFactory::getDocument();
  $document->addStyleSheet("/Joomla/media/system/css/sexyalertbox.css");
  $document->addScript("/Joomla/media/system/js/mootools1.js");
  $document->addScript("/Joomla/media/system/js/sexyalertbox.v1.js");

  /////// i cut some lines and i just point out where i used the javascript////

  if(!empty($promocode)){
  $message= "
 Successfully Save!  ";
 }
?>

i also tried putting these scripts in C:\xampp\htdocs\Joomla\templates\rhuk_milkyway\index.php

<jdoc:include type="head" />

 <link rel="stylesheet" href="<?php echo $this->baseurl ?>/media/system/css/sexyalertbox.css" type="text/css" />

Suddenly no luck.. it is still not working.. help me please..
Any suggestion or advice is highly sought.. God bless and have a nice day..
Answer: If you are adding your own version of MooTools or subsequent dependent scripts into the head of your template then you should go into the Joomla! plugins and disable (unpublish) the MooTools plugin. Joomla! 1.5x by default uses an older version of MooTools and it often has conflicts with other libraries such as jQuery or newer versions of MooTools.
The other option is to use an extension such as this one:
Disable Joomla! core mootools implementation
This will allow you to turn off the default MooTools header tag that is inserted by the Joomla! template parse. Then your site (content pages, modules, et cetera) should be able to properly leverage the custom MooTools and subsequent scripts you have inserted into the head.
Cheers
Aaron


XSLT - For-each-group

Question: This is a really basic question, but I'm not understanding how the for-each-group works. I want to combine adjacent top-level sections that don't have a sub section into a list. If there are sections WITH subsections I want to treat those differently, leaving the top level intact and combining the sub-sections into a list. I don't want to mix these up.
Source XML
  <?xml version="1.0" encoding="UTF-8"?>

     <sec>
        <title>A1</title>

Stuff A 1

     </sec>
     <sec>
        <title>A2</title>

Stuff A 2

     </sec>
     <sec>
        <title>A3</title>

Stuff A 3

        <sec>
           <title>B1</title>

Stuff B1

        </sec>
        <sec>
           <title>B2</title>

Stuff B2

        </sec>
     </sec>
     <sec>
        <title>A4</title>

Stuff A 4

     </sec>

Desired Result

     <list>
           <list-item><title>A1</title>
Stuff A 1
</list-item>
           <list-item><title>A2</title>
Stuff A 2
</list-item>
     </list>
     <sec>
        <title>A3</title>

Stuff A 3

        <list>
          <list-item><title>B1</title>
Stuff B1
</list-item>
          <list-item><title>B2</title>
Stuff B2
</list-item>
        </list>
     </sec>
     <list>
        <list-item><title>A4</title>
Stuff A 4
</list-item>
     </list>

XSLT fragment
This is definitely not correct. Also, it is not the only way I've tried, just the least messy to post. The way I think for-each-group should work I keep getting the error An empty sequence is not allowed as the @group-adjacent attribute of xsl:for-each-group. So this is just a snippet to get someone who knows what they are doing started.
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

        <xsl:template match="@*|node()" name="default" mode="#all">
            <xsl:copy>
                <xsl:copy-of select="@*"/>
                <xsl:apply-templates mode="#current"/>
            </xsl:copy>
        </xsl:template>

        <xsl:template match="body">

                <xsl:for-each-group select="sec[not(sec)]" group-adjacent=".">
                    <list>
                        <xsl:apply-templates select="current-group()"/>
                    </list>
                </xsl:for-each-group>

        </xsl:template>

        <xsl:template match="sec[not(sec)]">
            <list-item>
                <xsl:copy-of select="*"/>
            </list-item>
        </xsl:template>

    </xsl:stylesheet>

Answer: Try
<xsl:for-each-group select="sec" group-adjacent="exists(child::sec)">

which will give a group of sec elements that have a sec child, followed by a group that don't, and so on.
Within the for-each-group you may need to do <xsl:choose><xsl:when test="child::sec">... to apply different processing to the two kinds of group.

XSLT - For-each-group


Pegar coordenada da imagem ao clicar nela

Question: Estou em um projeto Xamarin/Android. Preciso que quando o usuário tocar em cima de uma ImageView eu consiga pegar as coordenadas (da imagem) desse toque.
Como fazer isso?
Answer: Recentemente passei por um caso parecido, e, se você está realmente querendo as coordenadas da imagem, a maneira que você fez não irá funcionar, pois o argumento e contém informações do lugar do ImageView que foi tocado, e não o lugar da Imagem.
para exemplificar melhor:
digamos que você tem um aparelho com a resolução de 1920x1080, e um ImageView com width com valor setado como match_parent, e o src com uma imagem 1280x720. Caso você toque no canto superior direito da imagem, o GetX() retornará 1080 (lugar da tela) e não 720 (lugar da imagem que foi realmente tocado)
Solução: continue usando este método, mas para saber a posição real do toque na Imagem, calcule a diferença de tamanho da imagem antes de ser colocada na ImageView, e depois de ser colocada.
byte[] decodedString = Base64.Decode(ImagemOriginal, Base64Flags.Default);
Bitmap decodedByte = BitmapFactory.DecodeByteArray(decodedString, 0, decodedString.Length);
int originalWidth = decodedByte.Width;

ImageView imag = _View.FindViewById<ImageView>(Resource.Id.img);
imag.SetImageBitmap(decodedByte);
Double fatorDiferenca = (double)imag.MeasuredWidth /(double)originalWidth;

então sempre que você quiser pegar a posição na imagem, multiplique o valor obtido pelo GetX() por fatorDiferenca:
var posicaoReal = e.Event.GetX() * fatorDiferenca;

(isso vale tanto para X quanto para Y)
Edit: Para poder desenhar algo no lugar que você clicou você deve usar apenas o GetX() e o GetY() normalmente, pois você estará desenhando efetivamente no ImageView e não na imagem que serviu como resource. Para você desenhar algo dentro do seu ImageView receio que você terá que fazer uma classe herdando de ImageView para que possa fazer isso:
   public class CustomImageView : ImageView
   {
        private int _CurrentX;
        private int _CurrentY;

        public override bool OnTouchEvent(MotionEvent e)
        {
            if (e.Action == MotionEventActions.Up)
            {
                _CurrentX = (int)e.GetX();
                _CurrentY = (int)e.GetY();

                Invalidate();
            }

            return true;
        }

        protected override void OnDraw(Canvas canvas)
        {
            base.OnDraw(canvas);

            using (var paint = new Paint(PaintFlags.AntiAlias))
            {
                paint.Color = Color.Red;

                canvas.DrawCircle(_CurrentX, _CurrentY, 20, paint);
            }
        }
    }

Para que você saiba qual lugar da imagem você está clicando, em pixels, você tem que fazer da maneira que eu tinha dito, pegue o GetX() e multiplique pelo fator de diferença, se quiser pode armazenar em uma variável para usos futuros.
Comment: Estou querendo fazer isso inclusive, se tu quiser editar tua resposta pra se adequar a isso (de colocar um pequeno quadrado no lugar do toque) que também estou com dificuldade em criar o atributo
Comment: Não pretendo desenhar na imagem em si, mas sim na posição correspondente ao toque. E ainda nem é um desenho, é jogar um objeto novo naquela posição mesmo
Answer: Eu resolvi meu problema fazendo o seguinte:
Primeiro criei uma relação entre o meu ImageView e a minha Activity:
private ImageView _myImage;
_myImage = FindViewById<ImageView>(Resource.Id.myImage);
Então criei um evento de toque do meu ImageView:
_myImage.Touch += _myImage_Touch;
E no método dele, ele pega as coordenadas do toque através do parâmetro e acessando o e.Event.GetX(); e e.Event.GetY(); Usei também um if que verifica se o valor de e.Event.Action é igual à MotionEventActions.Down. Desse modo, o evento só é executado uma vez, quando o dedo encosta na tela.
O método ficou assim:
private void _imgRoute_Touch(object sender, View.TouchEventArgs e)
{
    if(e.Event.Action == MotionEventActions.Down)
    {
      float x = e.Event.GetX();
      float y = e.Event.GetY();

      //resto do meu código
    }
}


Zariski topology and polynomial maps

Question: I've read on my book that Zariski topology is coarser than every topology in which polynomial maps are continous, but no proof of this fact is given. Could someone sketch me the proof of this?
Answer: It suffices to prove that, in any topology where polynomial maps are continuous, the Zariski-closed subsets are closed. So suppose $X$ is an algebraic set with such a topology and let $Y \subseteq X$ be Zariski-closed. Then there must exist polynomials $f_1, \ldots, f_r$ such that $Y = X \cap V (f_1, \ldots, f_r)$, and
$$V (f_1, \ldots, f_r) = V (f_1) \cap \cdots \cap V (f_r)$$
but $V (f) = f^{-1} \{ 0 \}$, and $\{ 0 \}$ is a closed subset of $k$, so $Y$ is indeed closed.
Note that we are assuming that points in $k$ are closed subsets – but this is a reasonable hypothesis.

Zariski topology and polynomial maps


Vector Field vs. Gradient Field?

Question:
Suppose we have a gradient field $\vec{F}$. Is there thus a vector field $\vec{G}$ such that the curl of ($\vec{G}$) = $\vec{F}$?

So, I'm trying to find examples/counter-examples. If we take a vector field and div(curl($\vec{F}$)) $\ne$ 0, then we know this isn't the case. This is my thinking. Can anyone guide me through?
Comment: https://en.wikipedia.org/wiki/Helmholtz_decomposition
Answer: The "usual" result is that this is impossible: it's a direct consequence of the Hodge decomposition of vector fields, and can be derived by assuming that
$$F = \nabla \phi = \nabla \times G$$
and noticing that
$$\langle F, F\rangle = \langle \nabla \phi, \nabla \times G\rangle = -\langle \phi, \nabla \cdot (\nabla \times G)\rangle = \langle \phi, 0\rangle = 0,$$
so that $F=0$. Here we have used the fact that the gradient and divergence are adjoint operators, which can be proven using integration by parts:
\begin{align*}
\langle \nabla \phi, v\rangle &= \int_{\mathbb{R}^3} \nabla \phi \cdot v\,dA \\
&= \int_{\mathbb{R}^3} \left[\nabla \cdot (\phi v) - \phi \nabla \cdot v\right]\,dA\\
&= - \langle\phi, \nabla \cdot v \rangle,
\end{align*}
where the first term of the second line vanishes by Stokes's theorem, provided that $\|p\|^2\phi(p) v(p)$ vanishes as $\|p\|\to \infty.$
However since you have not said anything about the behavior of $F$ as $\|p\|\to\infty$, the "usual" result does not necessarily apply. $$F = (0,0,1)$$
is both the gradient of
$$\phi = z$$
and the curl of
$$G = \frac{1}{2}(-y, x, 0).$$

Vector Field vs. Gradient Field?


Non linearly separable data to linearly separable data in the same dimension or lower dimension

Question: In continuation to this question, Non linear to linearly seperable
I am trying to understand if we do not want to transform to a higher dimension is it possible to still find a feature map that maps non linearly separable data into linearly separable data. If yes whats the intuition. For example in the image below I am trying to check if there is any 1D transformation I can use to find linearly separable data.
Also can we find transformation in lower dimension. Any reference material to read would be helpful as well.
Comment: Good question; note that it's not enough just to have *some* map, we need one that's continuous(ly differentiable).
Comment: by *assumption* there is a mapping from a given data point to its class, and using the mapping, the problem is linearly separable. ie if my feature already solves the class mapping.
Answer: Every case is different, and it's not generally possible for every data set, but there's a very simple transformation that makes your data linearly separable:
x = 1:20
y = c(0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1)
f = function(x) (x - 1) %% 4

plot(x, y, main = 'Not linearly separable')

plot(f(x), y, main = 'Linearly seperable')

x %% 4 here is the modulo or remainder operator: the remainder when x is divided by 4.
Answer: Yes, it is sometimes possible. In the example you give, a point $t$ is class X precisely when $\sin(\pi t)>0$.


Registering with a Performing Rights Organization

Question: Out of curiosity, I've recently taken a look at the websites of ASCAP and BMI, two big PROs. As a musician, if I wanted to hypothetically register with such an organization:

Should I register as a writer or as a publisher (or both)?
What are the differences between those two PROs?
Comment: Are you planning on representing the works of other songwriters? Do you collaborate in your songwriting? If the answer is 'no' to both of these, I don't see any value in registering as a publisher.
Comment: I think the answer to your first question is: Are you a writer or a publisher, or both?
Comment: @MatthewRead: I'm a musician, but I know that many musicians nowadays set up their own (albeit unincorporated) publishing companies. Is that worthwhile?
Comment: That's a whole different question, and to answerable we'd have to know a lot about your goals, abilities, etc.  I'm not sure this is the right platform for that, but maybe you could ask [in the chatroom](http://chat.stackexchange.com/rooms/440/musical-practice-and-performance).
Comment: @MatthewRead: Oh okay, thanks. Honestly, this whole question is more of a hypothetical one, since I'm just curious as to why some people decide to make their own publishing companies/register for those PROs as a publisher, while others don't bother and register as a writer. I don't think I'll be doing either any time soon :)
Answer: If you plan to represent and collect for other songwriters/composers, you obviously need to register as a publisher.
If you collaborate with other songwriters/composers, one (possible) advantage of registering as a publisher is you don't need to tell the PRO the split between the collaborators; you can establish that separately (usually in a contract between publisher and the other writers) as the PRO will just make a single payment to the publisher. Also, you can enter into agreements without having to get all the collaborators involved each time (although I think this is more of an issue with things like mechanical and sync rights than performance rights).
There may also be income tax implications in receiving royalties as an individual versus publishing company.
Answer: It goes like this:
In virtually every nation in the world, except the United States of America, each nation's government has its own bureau which collects royalties for songwriters and publishing companies, and disburses the funds to the songwriters and publishing companies (the "rights holders") after they withhold administrative costs.
However, in the USA, we do things by the private sector and capitalism. ASCAP and BMI are independent non-profit organizations who perform this function.
There is also a third performing rights company, SESAC, which operates in the USA. It is a privately held, for-profit company.
All three of these performing rights organizations collect royalties for songwriters and publishing companies regarding performances within the USA. These agencies also deal with the performing rights government bureaus of all the other nations of the world to collect royalties for American composers when their music is performed overseas, and for foreign composers whose works are performed in the USA.
There is a misapprehension that these performing rights organizations are "labor unions". They are not. They exist to collect royalties based on the USA and international laws.
ASCAP was started by music publishing companies, and was the first such company, and the only one for many years. BMI was created as a rival organization by the national association of radio stations in 1939 at a critical juncture when ASCAP wanted to raise the rates that radio stations had to pay to ASCAP to collect royalties for songwriters when they played their records. BMI started luring songwriters away from ASCAP with the promise of higher payments. For a short time, radio stations refused to play records of songs written by songwriters who registered with ASCAP. From 1939 to 1941 there was a huge struggle until the US government intervened and created a legal framework for both groups to coexist.
Today there is little functional difference between ASCAP and BMI. I'm told there was a time when a professional songwriter registered with ASCAP would refuse to co-write a song with another songwriter registered with BMI, because it made collecting any royalties on a co-written song much more difficult. But these days those barriers seem to have gone away.
Answer: More and more people are self publishing, as the standard model of the music publishing industry gets further and further behind reality and the price of self publishing goes down.
I would say: weigh up the annual cost and if there is a chance you may publish (and this includes online only eg through iTunes, Play.com etc) it is well worth looking into.
As @James said the collaboration angle mainly has a difference around sync rights and mechanical royalties - but I wouldn't worry so much about the difference around PRO paying to one individual or more as that shouldn't change the amount you get.


Converting an Array to an Object

Question: I am trying to write a function which takes in an array of arrays, and returns an object with each pair of elements in the array as a key-value pair. I have searched stack overflow and came up with the following code. However, my code below only returns the first array { make: 'Ford' }. My code does not return the rest of the arrays. Any suggestions on why my function does not return the rest of the array of arrays?

var array = [
  ['make', 'Ford'],
  ['model', 'Mustang'],
  ['year', 1964]
];

function fromListToObject() {

  for (var i = 0; i < array.length - 1; ++i) {
    var object = {};
    //creates an object as a variable
    var newArray = array[i];
    //creates a variable for the array within the array
    object[i] = newArray[1];
    //sets the object of the element to position 1 of the array within the array
    object[newArray[0]] = object[i];
    //sets the key of the element to position 0 of the array within the array
    delete object[i];
    // removes the previous key of 0
    return object;
  }
}

console.log(fromListToObject(array));
Comment: Declare `object` outside of your loop.
Comment: Try walking through your code with the debugger. Step by step. You might add `object` as a "watch" to see how its value changes.
Comment: Possible duplicate of [Convert JavaScript array of 2 element arrays into object key value pairs](http://stackoverflow.com/questions/26454655/convert-javascript-array-of-2-element-arrays-into-object-key-value-pairs)
Comment: Thank you all for your solutions. I tried to declare the object outside of the loop but it didn't seem to work..The function still only returned the first array of arrays.
Answer: Try this
You have declared obj inside the loop.
During iteration
object = Object {make: "Ford"}, i = 0

After the first iteration your function
console.log(fromListToObject(array));
is called.
This is because you call the return inside the loop, this should be done outside the loop.
Rewrite your code as

var array = [
    ['make', 'Ford'],
    ['model', 'Mustang'],
    ['year', 1964]
  ],
  i, j = array.length,
  object = {}

function fromListToObject() {

  for (i = 0; i < j; i++) {
    var newArray = array[i];
    object[i] = newArray[1];
    object[newArray[0]] = object[i];
    delete object[i];
  }
  return object;
}

console.log(fromListToObject(array));

var array = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]];

var obj = {};
array.forEach(function(data){
    obj[data[0]] = data[1]
});
console.log(obj);
Comment: That works just fine, but what is wrong with the OP's code?
Comment: torazaburo mean, you should explain **why** OP's code was failing and why your code gives proper output. Remember, you are answering for readers and not just OP.
Comment: In OP's code, the result obtained is just
{
  "make": "Ford"
}
Comment: Thanks Geethu! I was curious to understand why my code didn't work but your code works as well!!
Answer: Your code has several issues.

The target object is reset to {} in each iteration. So you should move var object = {} out of your loop.

You return from inside your loop, which immediately ends it: that should happen after the loop.

You iterate one time too few. Remove the - 1:
   for (var i = 0; i < array.length; ++i) {

There is an assignment to a numerical property, which you delete 2 lines later: that is a costly operation, which you should avoid. Just do the assignment in one operation:
   object[newArray[0]] = newArray[1];

Here is everything corrected:

var array = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]];

function fromListToObject() {
  var object = {}; // out of the loop
  for (var i = 0; i < array.length; ++i) { // iterate to last
    var newArray = array[i];
    object[newArray[0]] = newArray[1];
  }
  return object; // out of the loop
}

var obj = fromListToObject(array);

console.log(obj);

ES6 Version
If you can use ES6 syntax, then consider this solution:

function fromListToObject(array) {
    return Object.assign(...array.map( ([key,val]) => ({[key]: val}),{}));
}

const array = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]];
const obj = fromListToObject(array);
console.log(obj);

Using Map
You might also be interested in the ES6 Map object, which works similarly to an object, and can be constructed from your array in the most simple way:
const mp = new Map(array);

You can then access the key values as follows:
mp.get('make') === 'Ford';

And iterate:
mp.forEach( function (val, key) {
    console.log(key, val);
});

Comment: Thanks trincot. I was curious to understand why my code didn't work but your code works as well!!
Comment: I added a list of issues in your code and a version of it that has it corrected.
Answer: While: Not Counting!
object = {};
while( array[0] )object[ array[0][0] ] = array[0][1], array.shift();

will result in:
object;
>> Object { make: "Ford", model: "Mustang", year: 1964 }

array;
>> Array [ ]

This action will actually dispatch array members for patching the object!
The array content will be physically dislocated to the newly declared object.

Converting an Array to an Object


Php get Excel file via sftp

Question: I'm a complete noob in PHP and tried to solve my problem via the forum here but without luck!
I have a little download script that downloads a .csv file from a FTP server. That server is changed to a sftp server.
The problem I'm facing is that I'm unable to connect to the server anymore and just can't see why my code won't work. Any help greatly appreciated.
My old script:
function downloadFile(){
    $ftp_server = "feed.onftpsite.com";
    $ftp_username="1234";
    $ftp_userpass="1234";

    $conn_id = ftp_ssl_connect($ftp_server);
    $login_result = ftp_login($conn_id, $ftp_username, $ftp_userpass);
    ftp_pasv($conn_id, true);
    $server_file = "map/file.csv";
    $localfile = "some_other_file.csv";
    if (ftp_get($conn_id, $localfile, $server_file, FTP_ASCII)){
        echo "Successfully downloaded $localfile.";
    }else{
        echo "Error in downloading $localfile.";
    }
    ftp_close($conn_id);
}

Now I tried to change this to a sftp format:
function downloadFile(){
    $ftp_server = "feed.onftpsite.com";
    $ftp_username="1234";
    $ftp_userpass="1234";

    $conn_id = ssh2_connect($ftp_server, 22);
    $login_result = ssh2_auth_password($conn_id, $ftp_username, $ftp_userpass);
    ftp_pasv($conn_id, true);
    $server_file = "map/file.csv";
    $localfile = "some_other_file.csv";

    if (fopen($conn_id, $localfile, $server_file, FTP_ASCII)){
        echo "Successfully downloaded $localfile.";
    }else{
        echo "Error in downloading $localfile.";
    }
    //ftp_close($conn_id);
}

Why doesn't above code work?
Comment: What actually happens when you run your new code? Do you get any error messages? What do they say?
Answer: Not sure what the error is, but I can recommend trying phpseclib. Otherwise try providing an error message from the code above.
phpseclib is very simple to use, for exammple:
$sftp = new \phpseclib\Net\SFTP($host);
if (!$sftp->login($user, $password)) {
    exit('Login Failed');
}
$sftp->chdir('textfiles/');

$file = $sftp->get('example.txt');

Php get Excel file via sftp


What's the probability that a bookmaker is mispricing odds on soccer games?

Question: An English soccer team plays a series of matches against different opponents of varying ability. A bookmaker offers odds for each match as to whether it will be a home win, away win, or draw. Part-way through the season, the team has played $n$ matches and has drawn $k$ of them, which is more than might be expected from the odds.
What is the probability that the bookmaker is mis-pricing the odds on these matches, rather than just being unlucky? If the bookmaker continues to price the team's remaining matches in a similar way, and I bet $\$1$ that each one will be a draw, what is my expected return?
Comment: Previously asked at http://math.stackexchange.com/q/31871/18398
Answer: The answer to your question depends intricately on what information and assumptions you are going to use.  This is because the result of a game is an extraordinarily complicated process.  It can become arbitrarily complicated depending on what information you have about:

Players in the particular team - perhaps even particular combinations of players may be relevant.
Players in other teams
Past history of the league
How stable the team's players are - do players keep getting selected and dropped, or is it the same 11.
The time that you place your bet (during the game? before? how much before? what info is lost from betting before to betting on the day?)
some other relevant feature of soccer which I have omitted.

The odds that a book-maker gives are not a reflection of the book-makers odds.  which is impossible if they are probabilities.  A book-maker will adjust the odds down when someone bets on a draw, and adjust them up when someone bets on a non-draw.  Thus, the odds are a reflection of the gamblers (who use that book-maker) odds as a whole.  So it is not the bookmaker who is miss-pricing per se, it is the gambling collective - or the "average gambler".
Now if you are willing to assume that whatever "causal mechanism" is resulting in a draw remains constant across the season (reasonable? probably not...), then a simple mathematical problem is obtained (but note there is no reason for this to be "more right" than some other simplifying assumption).  To remind us that this is the assumption being used, an $A$ will be put on the conditioning side of the probabilities.  Under this assumption the binomial distribution applies:
$$P(\text{k Draws in n matches}|\theta,A)={n \choose k}\theta^{k}(1-\theta)^{n-k}$$
And we want to calculate the following
$$P(\text{next match is a draw}|\text{k Draws in n matches},A)$$
$$=\int_{0}^{1}P(\text{next match is a draw}|\theta,A)P(\theta|\text{k Draws in n matches},A)d\theta$$
where
$$P(\theta|\text{k Draws in n matches},A)=P(\theta|A)\frac{P(\text{k Draws in n matches}|\theta,A)}{P(\text{k Draws in n matches}|A)}$$
is the posterior for $\theta$.  Now in this case, it is fairly obvious that it is possible for a draw to happen, and also possible for it to not happen, so a uniform prior is appropriate (unless there is extra information we wish to include beyond the results of the season) and we set $P(\theta|A)=1$.  The posterior is then given by a beta distribution (where $B(\alpha,\beta)$ is the beta function)
$$P(\theta|\text{k Draws in n matches},A)=\frac{\theta^{k}(1-\theta)^{n-k}}{B(k+1,n-k+1)}$$
Given $\theta$ and $A$ the probability that the next match is a draw is just $\theta$ so the integral becomes:
$$\int_{0}^{1}\theta \frac{\theta^{k}(1-\theta)^{n-k}}{B(k+1,n-k+1)}d\theta=\frac{B(k+2,n-k+1)}{B(k+1,n-k+1)}=\frac{k+1}{n+2}$$
and hence the probability is just:
$$P(\text{next match is a draw}|\text{k Draws in n matches},A)=\frac{k+1}{n+2}$$
But note that it depends on $A$ - the assumptions that were made.  Call the "priced odds" a probability conditional on some other unknown complex information, say $B$.  So if the published odds are different to the the above fraction, then this says that $A$ and $B$ lead to different conclusions, so both can't be right about the "true outcome" (but both can be right conditional on the assumptions each made).
THE KILLER BLOW
This example showed that the answer to your question boiled down to deciding if $A$ was "more accurate" than $B$ in describing the mechanics of the soccer game.  This will happen regardless of what the proposition $A$ happens to be.  We will always boil down to the question of asking "whose assumptions are right, the gambling collective's or mine?"  This last question is a basically unanswerable question until you know exactly what the proposition $B$ consists of (or at least some key features of it).  For how can you compare something that is known with something that is not?
UPDATE: An actual answer :)
As @whuber has cheekily pointed out, I haven't actually given an expected value here - so this part simply completes that part of my answer.  If one was to assume that $A$ is true with priced odds of $Q$, then you would expect, in the next game to receive
$$Q\times P(\text{next match is a draw}|\text{k Draws in n matches},A)-1$$
$$=Q\times \frac{k+1}{n+2}-1=\frac{Q(k+1)-n-2}{n+2}$$
Now if you assume that the value of $Q$ is based on the same model as yours then we can predict exactly how $Q$ will change into the future.  Suppose $Q$ was based on a different prior to the uniform one, say $Beta(\alpha_Q,\beta_Q)$, then the corresponding probability is
$$P(\text{next match is a draw}|\text{k Draws in n matches},A_Q)=\frac{k+\alpha_Q}{n+\alpha_Q+\beta_Q}$$
with expected return of
$$\frac{Q(k+\alpha_Q)-n-\alpha_Q-\beta_Q}{n+\alpha_Q+\beta_Q}$$
Now if we make the "prior weight" $\alpha_Q+\beta_Q = \frac{N}{2}$  where $N$ is the length of the season (this will allow the "miss-pricing" to continue into the remainder of the season) and set the expected return to zero we get:
$$\alpha_Q=\frac{2n+N}{2Q}-k$$
(NOTE: unless this is the actual model, $\alpha_Q$ will depend on when this calculation was done, as it depends on $n,k,Q$ which will vary over time).  Now we are able to predict how $Q$ will be adjusted into the future, it will add $1$ to the denominator for each match, and $1$ to the numerator if the match was a draw.  So the expected odds after the first match are:
$$(1+\frac{n+\beta_Q-k+1}{k+\alpha_Q})\frac{n-k+\beta_Q}{n+\alpha_Q+\beta_Q}+(1+\frac{n+\beta_Q-k}{k+\alpha_Q+1})\frac{k+\alpha_Q}{n+\alpha_Q+\beta_Q}$$
$$=1+\frac{n+\beta_Q-k}{k+\alpha_Q}\left(1+\frac{2}{(2n+N)(k+\alpha_Q+1)}\right)\approx 1+\frac{n+\beta_Q-k}{k+\alpha_Q}$$
That is the odds won't change much over the season.  Using this approximation, we get the expected return over the remainder of the season as:
$$(N-n)\frac{Q(k+1)-n-2}{n+2}$$
But remember that this is based on the overly simplistic model of a draw (note: this does not necessarily mean that it will be a "crap" predictor).  There can be no unique answer to your question, because there has been no specified model, and no specified prior information (e.g. how many people use this bookie? what is the bookie's turnover? how will my bets influence the odds they price?).  The only thing which has been specified is the data from one season, and that for "some unspecified model" the probabilities are inconsistent with those implied by the odds pricing.
Answer: Bookmakers use an overround so they don't actually care what the result is because they win whatever. That is why you never meet a poor bookie. If a bookmaker is mispricing draws your ability to make profit would depend on the odds the bookmaker was offering and whether the profits generated would cover the times you lose.
Comment: This may be true, but mostly irrelevant, because the question asks for the expected return of the gambler, not the expected return of the bookie
Comment: @probability So what *is* the gambler's expected return?  I couldn't find it in your reply :-).


Dificuldades no menu e no submenu

Question: Olá camaradas estou desenvolvendo um software e estou com pequenas dificuldades no menu e no submenu.
As opções do Submenu ficam se alinhando a direita, porem queria que elas abrissem para baixo, eu irei demonstrar o código a seguir:

body {
  background-color: rgb(0, 132, 255);
}

nav#titulos h1 {
  color: white;
  font-size: 30px;
  margin-top: -2px;
  text-align: center;
}

nav#titulos h2 {
  color: white;
  padding: 5px;
  font-size: 30px;
  text-align: center;
}

.dropbtn {
  background-color: darkblue;
}

.dropdow {
  float: left;
  overflow: hidden;
}

.dropdow .dropbtn {
  font-size: 16px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: darkblue;
  font-family: inherit;
  margin: 0;
}

.navbar a:hover,
.dropdown:hover .dropbtn {
  background-color: rgb(10, 214, 241);
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: darkblue;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgb(10, 214, 241);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: darkblue;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: darkblue;
}

.dropdown:hover .dropdown-content {
  display: flex;
  justify-content: space-between;
}

hr {
  border-color: white;
  margin-top: -20px;
}

nav#menu {
  display: flex;
  overflow: hidden;
  margin-top: -10px;
  background-color: darkblue;
  float: none;
  text-align: left;
  padding: 0px 0px 10px 0px;
}

nav#menu ul {
  margin: -5px 0;
  padding: 0;
  background-color: darkblue;
  overflow: hidden;
  right: auto;
  float: left;
}

nav#menu li {
  display: flex;
  border: none;
}

nav#menu ul li {
  display: inline;
  padding: -10px;
}

nav#menu li a {
  display: inline-block;
  color: white;
  padding: 19px 39px;
  margin: none;
  text-decoration: none;
  transition: background-color 1s;
}

nav#menu li a:hover {
  background-color: rgb(10, 214, 241);
}

nav#menu li.active {
  background-color: rgb(10, 214, 241);
  ;
}

h1 {
  color: white;
  text-align: center;
}

p {
  color: white;
  text-align: center;
}

p {
  text-align: center;
}

h2 {
  color: gold;
  text-align: center;
  text-decoration: none;
}

a {
  color: gold;
}

#imgpos {
  position: absolute;
  left: 5px;
  top: 10px;
}

nav#menu ul {
  width: 100%;
  display: table;
}

nav#menu ul li {
  display: table-cell;
  list-style: none;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>TesT</title>
  <link rel="stylesheet" href="testilo.css">

Teste 2

 Desenvolvendo Menu

HOME

        <button class="dropbtn">

Mêses

                   </button>

Nissan

Iyar

Sivan

Tamuz

Av

Elul

Tishrei

Cheshvan

Kislêv

Tevêt

Shevat

Adar

As 12 Tribos

Árvore da Vida

Alfabeto Hebraico

Banco de Mapas

Se poderem me ajudar ficarei grato.
Answer: Vc colocou a UL com display: table, o que não é muito recomendado, já que os filhos dessa UL não possuem display: table-cell, table-row, etc...
A minha sugestão é colocar display: flex nessa UL e flex-direction: column, assim elas vão abrir na vertical como vc quer

<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TesT</title>
<link rel="stylesheet" href="testilo.css">

Teste 2

 Desenvolvendo Menu

HOME

        <button class="dropbtn">

Mêses

        </button>

Nissan

Iyar

Sivan

Tamuz

Av

Elul

Tishrei

Cheshvan

Kislêv

Tevêt

Shevat

Adar

As 12 Tribos

Árvore da Vida

Alfabeto Hebraico

Banco de Mapas

Comment: @Tantara se vc acha que a resposta resolveu o problema lembre de marcara a resposta como assista, basta clicar nesse icon e ✔ abaixo das setinhas ao lado da resposta
Comment: Então camarada, eu fiz isso, porém o menu todo está ficando na vertical.
Comment: @Tantara vc tem que por isso só na UL que esta dentro da outra UL, e não na UL principal onde esta o primeiro menu
Comment: Consegui meu caro, só tenho a lhe agradecer camarada.
Comment: Sabe como faço para deixar esse submenu uns centímetros abaixo do botão?
Comment: E como faço para ele só aparecer quando clicado as opções?
Comment: @Tantara fala camarada. Acredito já ter respondido o que foi perguntado nessa a sua pergunta, e vc não teve o mínimo de simpatia para marca-la como sugeri, ou dar um voto positivo já que vc diz ter ajudado... Mas vc vem e pede para resolver mais 2 problemas. Essa não eh a camaradagem que esperamos, então se vc quer outras respostas abra outra perguntas, e que sabe outra pessoa te responde
Comment: Vou marcar agora camarada, ainda sou novo nesse portal, não tinha dado a marcação pois não sabia aonde era, acabei de dar.
Desculpe a demora por dar ela, ela foi excelente.

Dificuldades no menu e no submenu


How can i make this code work?,im using beautifulsoup4 and im not able scrape that value to csv file

Question: Im sorry im new to coding but im really trying to learn.Im not able to pass the value i want, wich in this case is just a number i want to scrape from the web.
The problem it's that im not able no pass the value i scrape with beatifulsoup to a csv file,can any kind person help me with this?
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import csv

req = Request('https://www.infodolar.com.mx/tipo-de-cambio-dof-diario-oficial-de-la-federacion.aspx', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'})
html_page = urlopen(req).read()

soup = BeautifulSoup(html_page,'html.parser')

Dollar = soup.find('td','colCompraVenta')

print (Dollar.text)

file=open('New.csv', 'wb')
writer = csv.writer(file)

writer.writerows([Dollar.encode('utf-8')])

file.close()

Comment: Does this answer your question? [TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3](https://stackoverflow.com/questions/33054527/typeerror-a-bytes-like-object-is-required-not-str-when-writing-to-a-file-in)
Comment: To help you out, you must *include debugging details in your question.* Notably, the error you get: `TypeError: a bytes-like object is required, not 'str'` If you had put this, it would have suggested the above duplicate, or you could google the error.
Comment: Thanks men some already answer my question, the prblem was in this line of code,file=open('New.csv', 'w') , i was using 'wb' instead of 'w' now i understand that i need this to use external data from web in order to pass it correctly to a cvs file.
Answer: change this line to file=open('New.csv', 'wb') to file=open('New.csv', 'w')
your code will looks like the following
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import csv

req = Request('https://www.infodolar.com.mx/tipo-de-cambio-dof-diario-oficial-de-la-federacion.aspx', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'})
html_page = urlopen(req).read()

soup = BeautifulSoup(html_page,'html.parser')
Dollar = soup.find('td','colCompraVenta')
print (Dollar.text)

file=open('New.csv', 'w')
writer = csv.writer(file)

writer.writerows([Dollar.encode('utf-8')])
file.close()

Comment: Thanks man now the proggram runs with no issues on the prompt command, but the only thing i need no find now its to use the writer.writerows([Dollar.encode('utf-8')]) correctly for the proggram to be able to write that value to the cvs, thank you so much by the way for the directions men, it was frustating cause i didn't knew what i was doing wrong on with that specific problem,God bless you men i hope i can tackle this challenge, and i hope your reputation as a good programer grows up, Thanks man.
Comment: It's usually a good idea to _explain why_ this will fix the problem, otherwise people will just copy-paste without understanding... Notably: https://stackoverflow.com/questions/2665866/what-does-wb-mean-in-this-code-using-python
Comment: I'm sorry didn't about that question


Route to understanding and implementing statistical timing models

Question: The research paper Forecasting NBA Player Performance by Douglas Hwang describes a method for predicting player performance by utilizing a statistical timing model and a 'Weibull-Gamma' distribution.
I'm approaching this from a rudimentary understanding of descriptive statistics and Bayesian inference, and would like to get some background to better appreciate, and potentially implement a similar approach to predicting individual performance (outside of the sports arena).

What branch of statistics encompasses this sort of analysis?
What is the usual route students/practitioners follow in learning how to design and implement these analysis?
Any suggestions on books or resources (as applied as possible)?  Or open-source libraries that provide implementations of this sort of thing?
Answer: The ASA has a section on statistics in sports.  It cosponsors conferences like the one where you found Hwang's paper.  There are sessions and a luncheon talk every year at the JSM. There is now a journal on quantitative analysis in sports.  Serious articles for the layperson can be found in Chance Magazine and Significance Magazine.  I was chair of the sections program at the JSM in 2002.  Michael Schell has written two very serious books on baseball both published by Princeton University Press.  One is about greatest hitters of all time (adjusting for era and ballpark effects) and the other is about home run hitting (where the ballpark effect is taken int account).  Wizardry by Humphreys is an analysis of fielding skill in baseball.  Michael Lewis' Moneyball that was very popular and made into a movie is about how usign sabermetrics allowed a low market team like the Oakland As get talent to form a winning team without paying out the big bucks.
Baseball is rich with data especially in the major leagues and now data is being collected and analyzed about every pitch and every park of the ballpark where a ball is hit.
You will also find another statistician Jim Albert has written popular books on baseball including one he coauthored called Curve Ball.  There are now jobs in major league baseball for people like Bill James as well as for professionally trained statisticians.
Bud Goode was one of the pioneers to consult with the Dallas Cowboys and other NFL teams years ago on football strategy based on simple regression methods.
There are hired statisticians in the NBA, NFL and MLB and the use of statistics in sports is growing.  I have seen papers on tennis, golf, soccer and even cricket.  I have spanned the gamut of my knowledge on this.  I hope this has addressed your question.
Comment: Thanks Michael, good background.  The application I had in mind isn't necessarily specific to sports, but more predicting individual performance over time statistically.  To get there I need a better understanding of the statistics underlying this kind of analysis...do you think the Jim Albert books get me there?
Comment: Jim writes very well and may help with concepts. He also teaches statistics at Bowling Green University in Ohio. I know he teaches the elementary service courses and uses sports examples to motivate the methodology. I think that he has some elementary statistics books that he has written that may also be helpful and he does a lot of implimentation of methods using R.


How to scope out Services that implement interface X in standard MS DI?

Question: I'm using a lib that is based around standard MS DI stuff (which I see for the first time and not familiar with). So far it wasnt anything complicated, I build Service Provider:
var services = new ServiceCollection()
                   .AddSingleton<StartupService>()
                   .AddSingleton<Service2>()
                   .AddSingleton<Service3>()
                   .AddSingleton<Service4>()
                   .BuildServiceProvider();

Then I start the app via StartupService
await services.GetService<StartupService>().InitAsync();

And I inject services via ctor in all the modules or other services that dependent on these:
private readonly Service1 service1;
private readonly Service2 service2;

public OtherService(Service1 s1, Service2 s2)
{
    service1 = s1;
    service2 = s2;
}

It is nothing special so far but as number of services grew and some of them required "warm up" my StartupService started to looked grim:
public async Task InitAsync()

{
    Service1.WarmUp();
    Service2.WarmUp();
    Service3.WarmUp();
    ...
}

So my ~~brilliant~~ dumb idea was to implement IWarmUp interface and just, like, iterate over service collection man:
foreach (var service in services.GetServices<IWarmUp>())
        service.WarmUp();

Obviously it didnt work.
Is there a simple solution to that without making some complicated system or rewriting all my existing ctors that already use injection? How can I get the services that implement specific interface so I can make them do contract job?
Comment: can't you do WarmUp in the service1 constructor?
Comment: No, my ctors are absent of any logic (it only used for easy DI) because some of that logic is pretty heavy and too ugly for ctor like DB load or async http data request. You wont be doing this stuff in ctor but it needs to be done during startup. Since quite a few services require it I decided to make it a pattern and use a `warmup` for some services instead of having a mess where one half is in `ctor` and another is in separate method and then you have headache reading it.
Answer: You can register multiple implementations to a single service type - see here. So, you could use reflection to find all the types implementing IWarmUp, then loop through them and register each type to that service type.
foreach( var warmUpType in myListOfTypesImplementingIWarmUp )
    serviceCollection.AddTransient( typeof(IWarmUp), warmUpType )

And then in InitAsync ask your IServiceProvider for an IEnumerable<IWarmUp> and loop through calling WarmUp on each object.
You can still register each type against itself like AddSingleton<Service2>() and then request it from DI as you're doing currently.
Comment: `.AddTransient` -- "Transient components are created every time they are requested and are never shared."  Sorry I must be missing something - if all my services work as a singleton (one instance) - how would it make sense to make transient instance of each if singleton ones that I inject are different instances? I need to warm up the existing services since they are intended to be permanent through app life.
Comment: Ah. Right. Well then you can just create the instances where you build up your `ServiceCollection` and call a different overload of AddSingleton -> `AddSingleton(sp => mySingletonOne)`. Then do the same for each as in my answer above where `myListOfTypesImplementingIWarmUp ` is created like `new List{ mySingletonOne, mySingletonTwo }`.
Comment: Think you can edit your answer to reflect what do you mean in some detail?


How to get argument names using reflection

Question: I would like to do some fairly heavy-duty reflection in Ruby. I want to create a function that returns the names of the arguments of various calling functions higher up the call stack (just one higher would be enough but why stop there?). I could use Kernel.caller, go to the file and parse the argument list but that would be ugly and unreliable.
The function that I would like would work in the following way:
module A
  def method1( tuti, fruity)
    foo
  end
  def method2(bim, bam, boom)
    foo
  end
  def foo
    print caller_args[1].join(",") #the "1" mean one step up the call stack
  end

end

A.method1
 #prints "tuti,fruity"
A.method2
 #prints "bim, bam, boom"

I would not mind using ParseTree or some similar tool for this task but looking at Parsetree, it is not obvious how to use it for this purpose. Creating a C extension like this is another possibility but it would be nice if someone had already done it for me.
I can see that I'll probably need some kind of C extension. I suppose that means my question is what combination of C extension would work most easily. I don't think caller+ParseTree would be enough by themselves.
As far as why I would like to do this goes, rather than saying "automatic debugging", perhaps I should say that I would like to use this functionality to do automatic checking of the calling and return conditions of functions:
def add x, y
  check_positive
  return x + y
end

Where check_positive would throw an exception if x and y weren't positive. Obviously, there would be more to it than that but hopefully this gives enough motivation.
Comment: It looks like you want to determine execution order and arguments.  Is there a reason you can't use logging?  You could probably even do some metaprogramming to open up all the methods in the class and automatically log the arguments to do what you want.
Answer: In Ruby 1.9.2, you can trivially get the parameter list of any Proc (and thus of course also of any Method or UnboundMethod) with Proc#parameters:
A.instance_method(:method1).parameters # => [[:req, :tuti], [:req, :fruity]]

The format is an array of pairs of symbols: type (required, optional, rest, block) and name.
For the format you want, try
A.instance_method(:method1).parameters.map(&:last).map(&:to_s)
  # => ['tuti', 'fruity']

Of course, that still doesn't give you access to the caller, though.
Comment: Default values are evaluated dynamically, you cannot get static information about them. What should `def foo(par = rand()); method(:foo).parameters` return?
Comment: This also doesn't return default values. For example: `def person(name: "calvin")`. `method.parameters` will give `[[:key, :name]]`.
Comment: what does `instance_method` mean here?
Comment: @fraxture A bit late, but a method of the class `A`'s instance. Equivalent of doing: `A.new.methods` rather than `A.methods`
Answer: I suggest you take a look at Merb's action-args library.
require 'rubygems'
require 'merb'

include GetArgs

def foo(bar, zed=42)
end

method(:foo).get_args # => [[[:bar], [:zed, 42]], [:zed]]

If you don't want to depend on Merb, you can choose and pick the best parts from the source code in github.
Answer: I have a method that is quite expensive and only almost works.
 $shadow_stack = []

 set_trace_func( lambda {
   |event, file, line, id, binding, classname|
   if event == "call"
     $shadow_stack.push( eval("local_variables", binding) )
   elsif event == "return"
     $shadow_stack.pop
   end
 } )

 def method1( tuti, fruity )
   foo
 end
 def method2(bim, bam, boom)
   foo
   x = 10
   y = 3
 end

 def foo
   puts $shadow_stack[-2].join(", ")
 end

 method1(1,2)
 method2(3,4,4)

Outputs
 tuti, fruity
 bim, bam, boom, x, y

I'm curious as to why you'd want such functionality in such a generalized manner.
I'm curious how you think this functionality would allow for automatic debugging? You'd still need to inject calls to your "foo" function. In fact, something based on set_trace_func is more able to be automatic, as you don't need to touch existing code. Indeed this is how debug.rb is implemented, in terms of set_trace_func.
The solutions to your precise question are indeed basically, as you outlined. use caller + parsetree, or open the file and grab the data that way. There is no reflection capability that I am aware of that will let you get the names of arguments. You can approve upon my solution by grabbing the associated method object and calling #arity to then infer what of local_variables are arguments, but though it appears the result of that function is ordered, I'm not sure it is safe to rely on that. If you don't mind me asking, once you have the data and the interface you describe, what are you going to do with it? Automatic debugging was not what initially came to mind when I imagined uses for this functionality, although perhaps it is failing of imagination on my part.

Aha!
I would approach this differently then. There are several ruby libraries for doing design by contract already, including ruby-contract, rdbc, etc.
Another option is to write something like:
 def positive
   lambda { |x| x >= 0 }
 end

 def any
   lambda { |x| true }
 end

 class Module
   def define_checked_method(name, *checkers, &body)
     define_method(name) do |*args|
       unless checkers.zip(args).all? { |check, arg| check[arg] }
         raise "bad argument"
       end
       body.call(*args)
     end
   end
 end

 class A
   define_checked_method(:add, positive, any) do |x, y|
     x + y
   end
 end

 a = A.new
 p a.add(3, 2)
 p a.add(3, -1)
 p a.add(-4, 2)

Outputs
 5
 2
 checked_rb.rb:13:in `add': bad argument (RuntimeError)
         from checked_rb.rb:29

Of course this can be made much more sophisticated, and indeed that's some of what the libraries I mentioned provided, but perhaps this is a way to get you where you want to go without necessarily taking the path you planned to use to get there?
Comment: In fact, the method you describe clearly fails to distinguish arguments from local variables while also failing to work automatically
Comment: Well, that works for doing design by contract but it seems more than a little klunky compared to just having a single function you could call. The ideal is to be able *easily* add and remove the checks.
Answer: if you want the value for the default values, too, there's the "arguments" gem
$ gem install rdp-arguments
$ irb
>> require 'arguments'
>> require 'test.rb' # class A is defined here
>> Arguments.names(A, :go)

Answer:
In fact, the method you describe clearly fails to distinguish arguments from local variables while also failing to work automatically

That's because what you're trying to do is not something which is supported. It's possible (everything is possible in ruby), but there's no documented or known way to do it.
Either you can eval the backtrace like what logan suggested, or you can bust out your C compiler and hack sourcecode for ruby. I'm reasonably confident there aren't any other ways to do this.