text:
Q: How can I make just one page of a Word document horizontal? I'm using Microsoft Word 2010. How do I set only the last page of my document to be horizontal? All other pages have to remain vertical.

A: You need to insert "Section Breaks" to do that. Then you can change the layout in each section without touching the other ones. There are multiple ways to archive this.
Go to the ribbon Page Layout, click on Break and insert a Section Break on the Next Page.
In the new section, you can change Layout, without affecting preceding pages. Afterwards, insert another Section Break, and change the Layout again for the succeeding pages.
If you are afraid of braking the layout of your existing document, first insert the section breaks before and after your designated landscape page than change it's layout.

Be warned, that section breaks can cause some strange behaviour to pagination, footers and headers. Sometimes it's easier to create the Landscape pages in a separate document and merge it after printing...

A: If you want the document to start with the landscape page, go to the end of the desired landscape page, click Page Layout > Breaks > Next Page. This will add a section break after the current page.
Then, turn click anywhere on your desired landscape page again, and click Page Layout > Orientation > Landscape.
If you want to start with Portrait, and another page being landscape, do the same as above, but when making the section break, click on the page that is before the page you want to change the orientation of.
Section Break:

You will end up with something like:

If your 'odd' page is in between 2 normal pages (like above), then repeat the process but this time at the end of that page.

A: Go to the last page you want to keep vertical (Portrait) then select Page Layout | Breaks | Next Page.

Now click anywhere in the page where you want to have the horizontal page (Landscape) and go to Page Layout | Orientation and select Landscape
Do the same steps for the following page, the one after the landscaped one, but this time choose Portrait. Only do this if you want to restore the Portrait orientation back to normal.


text:
Q: how to create a function that enqueues an entire structure and not just an integer 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);
    }
}

A: 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) ;

redpajama_set_name: RedPajamaStackExchange


text:
Q: iterate through colors in javascript I want to make a list of all colors used in css, however they seem to be stored in a base 16 format.  I thought something like this might work, but it does not do what I want,
for(x; x< 100; x++)
{
   color = x.toString(16);
}

A: In JavaScript you can use "0x" before a number to make it hexadecimal and "0" to make it octal. Using this method, this should be the best code. This will probably crash your web browser, as there are 16,581,375 different possible hexadecimal colors in all of CSS. That's more than there are bytes in a megabyte (about 1 million), or how many years it would take to crack a 17-lowercase letter password.
var colors = new Array();
for(col=0x0;col<=0xFFFFFF;col++) {
  colors.push("#" + col);
}

A: Colors used in CSS 3 include 8 bits of each of red, green, blue, and an alpha channel that I believe is 8 bits (but is defined as a decimal number, so it's harder to tell). It's possible to represent these colors as rgba or hsla. With hexadecimal you can only represent 100% opaque colors. Iterating through eight bits of one color is easy enough:
for (var i=0; i<256; i++) {
    var redChan = i;
}

To iterate through all the colors is possibly by nesting this loop four levels deep, but that makes some assumptions about exactly what direction you want to iterate in. It will also be quite a longwinded operation.
// This is not intended to be the best solution, just to demonstrate the basic algorithm.
for (var r=0; r<256; r++) {
    for (var g=0; g<256; g++) {
        for (var b=0; b<256; b++) {
            // Assume we have 8 bits of alpha to use.
            for (var a=0; a<256; a++) {
                console.log('rgba(' + [r,g,b,a/255].join(',') + ')');
            }
        }
    }
}

A: Colours in CSS are usually described by their red, green and blue values (as integers between 0-255), and sometimes an alpha value for transparency.
If you're not interested in the alpha value, you write colours in CSS in the #RRGGBB hexadecimal format.
If we forget that we're using groupings for red, green and blue, it can be seen that we're writing a number between 000000 (0) and FFFFFF (16777215). Therefore, you could describe every RGB colour as an integer in this range.
var i = 0, colour;
for (; i < 16777216; ++i) { // this is a BIG loop, will freeze/crash a browser!
    colour = '#' + ('00000' + i.toString(16)).slice(-6); // pad to 6 digits
    // #000000
    // #000001
    // ... #000100 ...
    // #FFFFFE
    // #FFFFFF
}

The above code loops over all 16777216 colours, so I'd advise against running such a loop, but you can see how it changes the integer in the range to a unique hex colour.


text:
Q: Ubuntu 15.10 - some mouse events register only after movement or 1 second delay My Logitech wireless mouse behaves oddly with Ubuntu 15.10.
The mouse scroll and left click event gets registered in the below cases:
- immediately IF moving the mouse (even for one pixel). If not moving the mouse, if gets registered in the following case
- after 1 second of waiting without moving the mouse.
Not every scroll event gets registered immediately. One in 3 scrolls gets delayed (as well as clicks). This happens clearly on web pages, but it is also obvious in tabbed windows with icons on it (found in the settings page of Thunderbird). The issue is more evident with KDE than with Unity.
The issue occurs on Ubuntu 15.10 after the regular updates have been made. I'm not sure if it involves the Intel microcode as well. Tried disabling Intel video driver and it crashed my Desktop Manager (SDDM: black screen upon startup).
My configuration is:

*

*Lenovo G770 laptop

*Processor: Intel® Core™ i5-2430M CPU @ 2.40GHz × 4

*Memory: 4GB

*Ubuntu 15.10 - Unity DM

*Graphics: AMD Radeon 6600M and 6700M Series

*Mouse: Logitech M705 wireless mouse with Unifying receiver

*Synaptics touchpad (I think)

Please tell me what else information do i need to post here.
I've used Kubuntu 15.10 (Plasma 5) when I first observed the behavior, then moved to Ubuntu with Unity Desktop, then tried 14.04 LTS. On 14.04 the mouse works fine but I've had an issue with "Wireless and mouse not working after updates", so I installed 15.10 again. Same behavior on Unity 15.10. For the past 4 days, I installed at least 8 times (due to the additional Intel/ATI video issues as well).
I've also tried unloading the mouse kernel module (sudo rmmod psmouse), but it has no effect. I've also tried modifying the mouse parameters in xorg.conf, but to no effect as well.
Please help in some way.

A: Semi-solution to this issue: Disabling the proprietary ATI drivers and reverting to the default ("X.Org X Server -- AMD/ATI display driver wrapper...") driver solved the issue. The system and the graphics around the GUI is now much smoother.


text:
Q: i want to pass a variable from one class to another and use it in Label widget using python and tkinter I want to pass variable n from startpage to page1. Then put the variable into a label widget called label_country. How can I do this within tkinter? I tried calling the variable by the class and I also used the n.get() method.
import tkinter as tk
from tkinter import ttk

class tkinterApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self, height=1000, width=1000, bg="gray")
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.frames = {}

        for F in (StartPage, Page1):
            frame = F(container, self)
            self.frames[F] = frame
            frame.place(relx=0, rely=0, relwidth=1, relheight=1)

        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, bg="gray")

        style = ttk.Style()
        style.configure('W.TButton', foreground='black', background='white'
                        )
        button = ttk.Button(self, text="slect a country ", style='W.TButton',
                            command=lambda: [ controller.show_frame(Page1)])
        button.place(relx=0.66, rely=0.05, relwidth=0.2, relheight=0.07)

        ttk.Label(self, text="country slect:").place(relx=0.14, rely=0.05, relwidth=0.5, relheight=0.07)

        n = tk.StringVar()

        country_choice = ttk.Combobox(self, width=27, textvariable=n)
        country_choice["values"] = ([x for x in df["Country"].unique()])
        country_choice.place(relx=0.14, rely=0.05, relwidth=0.5, relheight=0.07)
        country_choice.current()
        text_box = tk.Text(self, height=28, width=30, bg="white")
        text_box.insert(tk.INSERT, "INFORMATIONT ABOUT THE PROGRAM")
        text_box.config(state="disabled")
        text_box.place(relx=0.14, rely=0.15, )

class Page1(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, bg="gray")

        label_country = tk.Label(self, text= StartPage.n, bg = "white")
        label_country.place(relx=0.795, rely=0.13, relwidth=0.0755, relheight=0.03)

app = tkinterApp()
app.mainloop()


text:
Q: Strange javascript issue if statement test = true but won't execute? In this click handler code:
$('#save').click(function () {
            if (overAllStatus == 'red') {
                rows[lastRowClicked].cells[0].innerHTML = '';
            }
            else if (overAllStatus == "yellow") {
                rows[lastRowClicked].cells[0].innerHTML = '';
                console.log('Over all status is yellow.');
            }
            else if (overAllStatus == 'greenR') {
                rows[lastRowClicked].cells[0].innerHTML = '';
            }
            else if (overAllStatus == 'greenN') {
                rows[lastRowClicked].cells[0].innerHTML = '';
            }
            comments = $('#comments').val();
            $("body").trigger(esc);
            $("#save1").trigger('click');
            redListSize = 0;
            yellowListSize = 0;
            console.log("save clicked");
        });

when the value of the variable overAllStatus is yellow as tested in the JS console and I see this in the console just before I click the 'save' button:
> overAllStatus
"yellow"
> overAllStatus == 'yellow'
true

I only see "save clicked" printed in the console. It seems like the code in the test condition (overAllStatus == "yellow") doesn't execute. I don't understand why.

A: try this replace your code with this one and see what value does "overAllStatus" has within your 'click' callback
$('#save').click(function () {
            console.log("overAllStatus", overAllStatus);  //use this to check the value of overAllStatus

            if (overAllStatus == 'red') {
                rows[lastRowClicked].cells[0].innerHTML = '';
            }
            else if (overAllStatus == "yellow") {
                rows[lastRowClicked].cells[0].innerHTML = '';
                console.log('Over all status is yellow.');
            }
            else if (overAllStatus == 'greenR') {
                rows[lastRowClicked].cells[0].innerHTML = '';
            }
            else if (overAllStatus == 'greenN') {
                rows[lastRowClicked].cells[0].innerHTML = '';
            }
            comments = $('#comments').val();
            $("body").trigger(esc);
            $("#save1").trigger('click');
            redListSize = 0;
            yellowListSize = 0;
            console.log("save clicked");
        });


text:
Q: C++ Boost SSL Challenge-Response I'm developing a C++ application that should transmit some data securely.
I want to use SSL over connection, and i decided to ue Boost SSL library.
My question is:
For authentication, i should write myself the challenge-response code ? Or the Boost will do this for me ?
I tried the examples but i don't know if is secure enough.
Also, i should provide the public key ( the .pem file ) ?
boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23);
ctx.load_verify_file("ca.pem");


text:
Q: How to show displayName of contact as text? I want to pick a random number from contact list and show it as Text. Below is what I came up with but when I insert showNext() somewhere on main.dart as text, I get Closure: () => Future from Function 'showNext': static.() instead of a number. How do I show a number?
Future<void> showNext() async {
  var status = await Permission.contacts.status;
    if (status.isGranted) {
  var contacts = await ContactsService.getContacts;
  var list = contacts;
    list.shuffle();
  randomNum= (list.first.phones?.first.value ?? '');
  Text('$randomNum');

A:   Future<Widget> showNext() async {
  var status = await Permission.contacts.status;
  if (status.isGranted) {
     final Iterable<Contact> contacts = (await ContactsService.getContacts(withThumbnails: false));
     var list = contacts.toList();
     list=list.shuffle();
     randomNum= (list.first.phones?.first.value ?? '');
     return Text('$randomNum');
  }

when you want use:
FutureBuilder<String>(
          future: showNext(),
          builder: (context, snapShot) {
            if (!snapShot.hasData) {
              return Container();
            }
            return snapShot.data;
          },
        )


text:
Q: Unity 5.6 Mac 2D Project Build Won't Run I have a Unity 5.6 2D project that I've created on my Mac (macOS Sierra).  The game plays fine when I run it inside of Unity.  However, when I "build and run", it appears to build fine (it creates the application), but it never runs.  I have sent the project to another user who is able to successfully build his projects, but he has the same issue when trying to build mine.  I've tried both an x86x64 and Universal build, but I have the same results.  Application doesn't show in Activity Monitor either.
HELP - I need to turn this in for a class!!!!
Thanks!

A: Thank you @Programmer and @Coolq B for all your help. I was able to get it to work by exporting everything out of my project, and import it into a new project.  Clearly, there was something corrupt in the original project.


text:
Q: XSLT: output unmatched elements from two pieces of xml The two sample xmls are given below:
xml1:
<Root>
  <Child1/>
  <Child2/>
  <Child3/>
</Root>

xml2:
<Root>
  <Child0>xml2value</Child0>
  <Child2/>
  <Child3>xml2value</Child3>
  <Child4>xml2value</Child4>
</Root>

I have got these two xmls in two variables. Now I want to filter from xml2 those elements which do not exist in xml1, i.e., the resulting variable should look like below:
<Child0>xml2value</Child0>
<Child4>xml2value</Child4>

How can it be done with xslt?

A: XSLT 2.0:
<xsl:key name="el-by-name" match="Root/*" use="node-name(.)"/>

<xsl:variable name="xml1" select="document('file1.xml')"/>
<xsl:variable name="xml2" select="document('file2.xml')"/>

<xsl:copy-of select="$xml2/Root/*[not(key('el-by-name', node-name(.), $xml1))]"/>

With XSLT 1.0:
<xsl:key name="el-by-name" match="Root/*" use="name()"/>

<xsl:variable name="xml1" select="document('file1.xml')"/>
<xsl:variable name="xml2" select="document('file2.xml')"/>

<xsl:for-each select="$xml2/Root/*">
  <xsl:variable name="child" select="."/>
  <xsl:for-each select="$xml1">
    <xsl:if test="not(key('el-by-name', name($child)))">
      <xsl:copy-of select="$child"/>
    </xsl:if>
  </xsl:for-each>
</xsl:for-each>

A: I have solved the problem with the below code:
               <xsl:variable name="output">
                <xsl:for-each select="$xml2/Root/*">
                  <xsl:variable name="cur" select="local-name(.)"/>
                  <xsl:if test="not($xml1/Root/*[local-name(.)=$cur])">
                    <xsl:copy-of select="."/>
                  </xsl:if>
                </xsl:for-each>
               </xsl:variable>


text:
Q: Failed to specialize function template in threads I'm trying to implement a Thread in c++ wich it will be used to control when I take a picture, but this simple code is giving me a strange error, which I can't understand. This is my code:
#include <iostream>
#include <fstream>
#include <thread>
    using namespace std;

    void counter(int seconds, bool &flagTakePhoto, bool &flagThreadStart);

int main() {
    bool takePhoto, threadStart;

    int seconds = 1;

    thread t(counter, seconds, takePhoto, threadStart);
    //Some code here
}

void counter(int seconds, bool &flagTakePhoto, bool &flagThreadStart) {
    while (flagThreadStart) {
        this_thread::sleep_for(chrono::seconds(seconds));
        flagTakePhoto = true;
    }
    terminate();
}

This is the error:
1>------ Build started: Project: Proyecto para pruebas OPENCV, Configuration:
Release x64 ------
1>  Main.cpp
1>Main.cpp(46): warning C4244: 'initializing': conversion from '__int64' to 'int', possible loss of data
1>C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(238): error C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'
1>  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(238): note: With the following template arguments:
1>  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(238): note: '_Callable=void (__cdecl *)(int,bool &,bool &)'
1>  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(238): note: '_Types={int, bool, bool}'
1>  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(247): note: see reference to function template instantiation 'void std::_LaunchPad<_Target>::_Execute<0x00,0x01,0x02,0x03>(std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool> &,std::integer_sequence<_Ty,0x00,0x01,0x02,0x03>)' being compiled
1>          with
1>          [
1>              _Target=std::unique_ptr<std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool>,std::default_delete<std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool>>>,
1>              _Ty=size_t
1>          ]
1>  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(247): note: see reference to function template instantiation 'void std::_LaunchPad<_Target>::_Execute<0x00,0x01,0x02,0x03>(std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool> &,std::integer_sequence<_Ty,0x00,0x01,0x02,0x03>)' being compiled
1>          with
1>          [
1>              _Target=std::unique_ptr<std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool>,std::default_delete<std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool>>>,
1>              _Ty=size_t
1>          ]
1>  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(242): note: while compiling class template member function 'void std::_LaunchPad<_Target>::_Run(std::_LaunchPad<_Target> *) noexcept'
1>          with
1>          [
1>              _Target=std::unique_ptr<std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool>,std::default_delete<std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool>>>
1>          ]
1>  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(230): note: see reference to function template instantiation 'void std::_LaunchPad<_Target>::_Run(std::_LaunchPad<_Target> *) noexcept' being compiled
1>          with
1>          [
1>              _Target=std::unique_ptr<std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool>,std::default_delete<std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool>>>
1>          ]
1>  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thr/xthread(256): note: see reference to class template instantiation 'std::_LaunchPad<_Target>' being compiled
1>          with
1>          [
1>              _Target=std::unique_ptr<std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool>,std::default_delete<std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool>>>
1>          ]
1>  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\thread(52): note: see reference to function template instantiation 'void std::_Launch<std::unique_ptr<std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool>,std::default_delete<std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool>>>>(_Thrd_t *,_Target &&)' being compiled
1>          with
1>          [
1>              _Target=std::unique_ptr<std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool>,std::default_delete<std::tuple<void (__cdecl *)(int,bool &,bool &),int,bool,bool>>>
1>          ]
1>  Main.cpp(136): note: see reference to function template instantiation 'std::thread::thread<void(__cdecl &)(int,bool &,bool &),int&,bool&,bool&,void>(_Fn,int &,bool &,bool &)' being compiled
1>          with
1>          [
1>              _Fn=void (__cdecl &)(int,bool &,bool &)
1>          ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

What is more strange about this is that I have a similar code in other program and compile with no errors!
Does anyone knows what's wrong with this code?
Thanks!

A: The std::thread constructor will construct all of its objects and call the function as if by:
template <class T>
typename decay<T>::type decay_copy(T&& v) {
    return std::forward<T>(v);
}

That makes the argument types of
thread t(counter, seconds, takePhoto, threadStart);

be int, bool, bool. Since you cannot call counter(int, bool, bool) (it takes lvalue references), that constructor is ill-formed.
In order to pass references, you need to wrap your arguments in std::reference_wrapper<T>. That type is implicitly convertible to T&, so calling counter(int, std::reference_wrapper<bool>, std::reference_wrapper<bool>) is valid. For short-hand, the standard provides std::ref, so you can just do the following:
thread t(counter, seconds, std::ref(takePhoto), std::ref(threadStart));


text:
Q: Is it possible to create alerts for multiple requests from the same IP Address in Azure App Service? I have spotted multiple request from the same IP address against my App Service Site, by inspecting the web logs.
Is it possible to set up an alert so when this happens I get an email or SMS etc?
Thanks.

A: I assume that you want to config dynamic ip restriction in Azure App, If it is that case you could config it in the web.config file.
The following is demo code. For more information please refer to this tutorial.
<system.webServer>
   <security>
      <dynamicIpSecurity enableLoggingOnlyMode="true">
         <denyByConcurrentRequests enabled="true" maxConcurrentRequests="10" />
         <denyByRequestRate enabled="true" maxRequests="30"
            requestIntervalInMilliseconds="300" />
      </dynamicIpSecurity>
   </security>
</system.webServer>

Is it possible to set up an alert so when this happens I get an email or SMS etc?

Yes, you could set the weblog store in the blob and you could sum the requets group by IP, according to the requests number to decide whether send mail or SMS not.
For more information about Azure function timetrigger, please refer to this tutorial.


text:
Q: INSTALL_FAILED_EAS_POLICY_REJECTED_PERMISSION? Everytime i try to launch my APP Im getting this error in the Console
[2014-03-09 10:26:47 - GeocachePlacer] ------------------------------
[2014-03-09 10:26:47 - GeocachePlacer] Android Launch!
[2014-03-09 10:26:47 - GeocachePlacer] adb is running normally.
[2014-03-09 10:26:47 - GeocachePlacer] Performing dk.rocologo.geocacheplacer.MainActivity activity launch
[2014-03-09 10:27:16 - GeocachePlacer] Uploading GeocachePlacer.apk onto device 'eb0b0006'
[2014-03-09 10:27:17 - GeocachePlacer] Installing GeocachePlacer.apk...
[2014-03-09 10:27:19 - GeocachePlacer] Installation error: INSTALL_FAILED_EAS_POLICY_REJECTED_PERMISSION
[2014-03-09 10:27:19 - GeocachePlacer] Please check logcat output for more details.
[2014-03-09 10:27:19 - GeocachePlacer] Launch canceled!
[2014-03-09 10:36:32 - GeocachePlacer] ------------------------------

I dont know what this error means and what to do to resolve it. I have tried Google "INSTALL_FAILED_EAS_POLICY_REJECTED_PERMISSION" but I have only found one who had the same problem when we wanted to root his phone.
I don't want that, I'm just trying to install and run my app, to test if it works?
I would appreciate if anyone could tell me in what direction I should look!

A: I have found the solution: I tried to export the APK file and discovered that it was my Corporate Email which was the problem. When I install my Corporate Email (Outlook / Exchange activesync) the phone / tablet get some a security policy from my company which disables "Unknown sources" in the Security settings. "Unknown sources" was greyed out so I could not enable it.
To solve this I removed my corporate email account from the device and the policy and THEN I was able to enable "Unknown Sources" and THEN I could finally install my APP directly from Eclipse or manually export and install the APK file.
This gives me a new problem. Now I can't read corporate email on my phone :-( If I install the policy again, then I cant install APK files on my phone :-(
You might have the same problem if you use KNOX which is standard on new Samsung Galaxy Devices.


text:
Q: Get file name when uploading file using ajax in Struts2 I am trying  fileupload using ajax in a struts2 framework webapp. I am using the "fileupload" interceptor  in the action mapping, i am getting the file content in the action, but not the uploaded fileName i.e.,
private File file; // + its setters & getters methods.
private String fileName; // + its setter & getters methods.

System.Out.println(file.getName()); //prints some .tmp file

The fileName variable is null.
Do i have to specify any file Details while making an ajax call to get the FileName of the uploaded file ?
--
Thanks

A: It should be like this
if the "name" attribute of the  on your page is "xxx"
private File xxx;
private String xxxContentType;
private String xxxFileName;

A: FileUpload Interceptor
You should provide setter method appropriately. Follow naming convention carefully. Refer above link
Struts2 FileUpload Example


text:
Q: While implementing VARMAX model in python, the error comes that leading minor is not positive definite I am working on time series VARMAX model in python with 18000 rows of data and 6 parameters. Repeatedly while fitting the VARMAX model, it says " leading minor is not positive definite" or "matrix is not positive definite". Can somebody help in recognizing the problem?

A: The error suggests that there are linear dependencies among your variables. You can investigate these linear relationships using the correlation matrix df.corr() and/or PCA.


text:
Q: Switching to high-resolution text modes on PC I would like to write a text editor running on text screen. In modern PC 1280x1024 (160x64 char) screen would be good for flat panel. For safety reason I am working on a i865 based P4 motherboard. VESA bios sets the resolution but in graphics mode; additionally, the VGA registers shows the original DOS screen values. I need help how to program i865 to text mode.

A: 1280x1024 is not a VGA resolution. You will need to use VESA/VBE if you want to use these high-resolution modes. And, with one exception (that does not meet your requirement), there are no standard modes defined by VESA. You need to interrogate the video card and pick one of the supported modes. Use VBE function 00h to get a full list of supported modes, and function 01h to check the attributes for each of these supported modes to see if it meets your requirements.
Once you've found the mode you want, function 02h will set that mode, and then you are basically done. Well, except for the hard part of writing code that puts text on the screen!
This is all documented in the standard. Sample code in C is available on the OSDev Wiki.


text:
Q: Incorrectly Linking Javascript File? I'm working on installing a PhoneGap plugin on an iPhone.  The page for the plugin I am attempting to install can be seen here:  https://github.com/phonegap/phonegap-plugins/tree/master/iPhone/MessageBox.
I believe I have narrowed down my problem to incorrectly working with the JavaScript file.  I am including it on my HTML page like so:
<script language="javascript" type="text/javascript" src="MessageBox.js"></script>

The rest of my HTML page is this:
<script type="text/javascript">
alert("test1");
var messageBox = window.plugins.messageBox;
alert("test2");
messageBox.alert('Title', 'Message', function(button) { console.warn('alert', [this, arguments]); });
</script>

I see an alert saying test1, but not the second alert.  This makes me think that the error is on the line:
var messageBox = window.plugins.messageBox;

However, I'm not quite sure what I should be doing differently.  From what I can tell, I've done all the necessary steps as described on the plugin's documentation page, seen here:
https://github.com/phonegap/phonegap-plugins/blob/master/iPhone/MessageBox/README.md
(As expected, I also do not see the output of the messageBox.alert... line when viewing this through the iOS simulator.)
I would appreciate any help with this issue, thanks!
NOTE: my initial thread regarding this topic can be seen here: Trouble Installing PhoneGap Plugin
EDIT: I should also add that I have the exact same problem when trying to install a different (but similar) plugin, known as "Prompt"
EDIT2: Here's my index.html:
    <script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
    <script type="text/javascript" src="MessageBox.js"></script>
    <script type="text/javascript">

    function onBodyLoad()
    {
        document.addEventListener("deviceready", onDeviceReady, false);
    }

    function onDeviceReady()
    {
        navigator.notification.alert("PhoneGap is working");
        window.location.href="otherpage.html";
    }
    </script>

A: The problem is that when you try to create your MessageBox, PhoneGap is not ready yet.
You just need to wait for PhoneGap to be ready before you execute your code :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>

    <script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
    <script type="text/javascript" charset="utf-8">
        document.addEventListener("deviceready", onDeviceReady, false);

        function onDeviceReady() {
            window.location="otherpage.html";
        }
    </script>
</head>
<body>
</body>
</html>

Then, on otherpage.html :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
    <script type="text/javascript" charset="utf-8" src="MessageBox.js"></script>

</head>
<body onload="onLoad()">
    <script type="text/javascript" charset="utf-8">

        function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
        }

        // PhoneGap is loaded and it is now safe to make calls PhoneGap methods
        //
        function onDeviceReady() {
            console.log("onLoad");
            var messageBox = window.plugins.messageBox;
            messageBox.alert('Title', 'Message', function(button) { console.warn('alert', [this, arguments]); });
        }
    </script>
</body>
</html>

I tested it on PhoneGap 1.4.1


text:
Q: Указатели на функции и возвращаемый тип Изучаю C++. остановился на теме "Указатели на функции".
Есть код работающий.
#include <iostream>

using namespace std;

double add(double, double);
double multi(double, double);
double divorce(double, double);

const double* calculate(double, double, double (*pr[3])(double, double));

double  (*pf[3])(double, double) = {&add, &multi, &divorce};

int main()
{
    const double* q = calculate(2.5, 10.4, pf);

    cout << endl;

    for (int i = 0; i < 3; ++i)
    {
        cout << q[i] << endl;
    }

    return 0;
}

double add(double x, double y)
{
    return x + y;
}

double multi(double x, double y)
{
    return x * y;
}

double divorce(double x, double y)
{
    return x / y;
}

const double* calculate(double x, double y, double (*pr[3])(double, double))
{
    auto* ptr = new double[3];

    for (int i = 0; i < 3; ++i)
    {
        ptr[i] = (*pr[i])(x, y);
    }

    return ptr;
}

Если поменять строки
double add(double, double);
double multi(double, double);
double divorce(double, double);

на
const double add(double, double);
const double multi(double, double);
const double divorce(double, double);

то тогда выражение
double  (*pf[3])(double, double) = {&add, &multi, &divorce};
нужно поменять на
double  (*pf[3])(double, double) = {add, multi, divorce};
Почему?
Да и еще один вопрос.
Объясните разницу между
const double (*pf[3])(double, double)
и double (*pf[3])(double, double)

A: Менять необходимо, так как сигнатура функции double add(double, double); не соответствует сигнатуре функции const double add(double, double);. Различие заключается в наличии const-квалификатора для возвращаемого значения. Причем для простых типов наличие этого const-квалификатора вообще-то не имеет смысла, а для объектов может быть большая разница, например если возвращать просто std::string x(void), то можно написать вот так x().append("oops");.

A: У Вас в коде два разных типа, с одной стороны Вы объявляете массив, в который можно помещать объекты такого типа: double(*)(double, double), с другой Вы пытаетесь поместить в этот массив функцию add (к примеру), а тип этого выражения будет такой: const double(*)(double, double). Разумеется, что это два разных типа, и Вы не можете просто взять и поместить объект одного типа в массив, который содержит объекты другого типа.
Можно использовать reinterpret_cast, если уж очень хочется, но последствия такого решения всегда лежат на программисте.


text:
Q: Python: strange enum subclass behaviour with json serialization I'm experiencing a strange behaviour while trying to serialize some data to send as argument to a remote procedure using Nameko and rabbitmq to a microservice:
A semplification of the problem structured into 3 files under a dir named project:
serializer.py, the custom json encoding/decoding objects
from enum import Enum
import json
from project.service import CustomEnum

class CustomEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, CustomEnum):
            #  return {'__enum__': str(o)}
            return {'__enum__': o.name}
        return {'__{}__'.format(o.__class__.__name__): o.__dict__}

class CustomDecoder(json.JSONDecoder):
    def __init__(self, *args, **kwargs):
        json.JSONDecoder.__init__(self,
                                  object_hook=self.object_hook,
                                  *args, **kwargs)

    def object_hook(self, o):
        if '__enum__' in o:
            return CustomEnum[o['__enum__']]
            # name, member = o['__enum__'].split('.')
            # return getattr(ENUMS[name], member)
        return o

service.py, the basic microservice
from enum import Enum
from nameko.rpc import rpc
import json

from project.serializer import CustomDecoder

class CustomEnum(Enum):
    A = 0
    B = 1

class Service(object):
    name = "service"

    @rpc
    def get_enum(self, enum_type):
        enum_type = json.loads(enum_type, cls=CustomDecoder)
        if enum_type == CustomEnum.A:
            return "A"
        elif enum_type == CustomEnum.B:
            return "B"
        return "NO ENUM"

Nameko shell to try out, after starting a rabbitMQ docker instance and nameko run of the service by following these steps:

*

*$ docker run -d --hostname rabbit --name my-rabbit -p 15672:15672 -p 5672:5672 rabbitmq:3-management

*$ nameko run project.service --broker amqp://guest:guest@localhost

*$ nameko shell --broker amqp://guest:guest@localhost
Here the shell output after testing it:
In [1]: import json
In [2]: from project.serializer import CustomEncoder
In [3]: from project.service import CustomEncoder
In [4]: serialized = json.dumps(CustomEnum.A, cls=CustomEncoder)
In [5]: n.rpc.service.get_enum(serialized)
NO ENUM

It seems that after being deserialized on the remote procedure type(enum_type) == type(CustomEnum) gives False, while trying it out in the nameko shell it perfectly serialized and deserialize the enum subclass type.
Could it have something to do with the serialization of already serialized data by nameko itself? I know I should register the custom serializer to the kombu.serialization.register but I'm stuck to this and I'd like to know why this happen.


text:
Q: Iniciar sesión en Google, Error 403: dissalowed_useragent Estoy desarrolando una web y esa web tiene un login con Google.
Esa web, tiene una App de Expo que lo único que hace es conectarse a la web desde la App, pero cuando intento hacer login desde Google, salta el siguiente error:
Error 403: disallowed_useragent

¿Cómo soluciono ese error?


text:
Q: Want to use print option in windows 8.1 app store I want to print the document with system.print but its not working in windows store app. Can anyone help me, how can the print will work.
I am using XAML for user interface.


text:
Q: Onde colocar os métodos de requisição assíncrona seguindo os padrões ASP.NET MVC? Eu sempre coloquei no Controller da View, é a maneira mais correta de se fazer? me veio a duvida pois percebi que estou enchendo minha view de métodos assíncronos, e gostaria de deixar isso tudo separado para eu não me perder.
Nunca li nada sobre boas praticas de onde colocar esses métodos, gostaria de saber qual o padrão de desenvolvimento relacionado a métodos para requisição assíncrona.

A: Sim, é no Controller da view que os métodos se requisição devem ficar, sejam síncronos ou assíncronos.
Seguindo a premissa de SoC (Separation of Concerns), sua Controller deve conter apenas os métodos de requisição (Action/ActionResult), o assíncronismo é só um detalhe do funcionamento neste caso.
O importante é que métodos que realmente exponham como o serviço é feito, como chamadas ao banco de dados e manipulação de dados, que configuraria uma camada de acesso ao banco ou serviços sejam colocados em outro projeto e apenas chamados pelo seu projeto Web para que ele não fique muito carregado e confuso.
Adicionar o sufixo Async aos nomes dos métodos assíncronos também é uma boa prática.
Um exemplo claro de como seria um método de requisição assíncrono seria esse:
public async Task<ActionResult> GetReportsAsync(ReportsViewModel model)
{
    if (ModelState.IsValid)
    {
        // Toda lógica é feita aqui.
        ReportingResult result = await reportingService.GenerateReport(model);
        if (result.Success)
        {
            return Redirect("~/home");
        }
        else
        {
            // View de erro
        }
    }

    return View(model);
}

Limpo e claro (e assíncrono). Expõem apenas o necessário e não deixa o código sujo.
Detalhe importante sobre assíncronismo:
Nunca utilize o método Task.Run na controller, o assíncronismo deve começar de dentro para fora, ou seja, nas camadas mais interiores você identifica operações que necessitam ser assíncronas, como chamadas ao banco de dados, aí então pode expor o método como Task ou async Task e na sua Controller chamar o método com await, igual ao meu exemplo. Esse é uma ótima prática de implementação assíncrona ensinada por Stephen Cleary.
Segue um post da Microsoft(em inglês) que fala sobre requisição assíncrona, performance e alguns dos recursos oferecidos pelo ASP.NET MVC: https://docs.microsoft.com/en-us/aspnet/mvc/overview/performance/using-asynchronous-methods-in-aspnet-mvc-4


text:
Q: What is the best way open/edit a data Stream if all I have is a MIME type I am in a Windows Desktop application and I have a data stream and a mime type in the database. Is there a better way than writing it to a temp folder and launching the default editor for it?
If I have to use the temp folder how can I get the file extension from the MIME type in a C# Windows Desktop application?

A: Lookup the MIME type in HKEY_CLASSES_ROOT\MIME\Database\Content Type to find out the corresponding file extension and go from there. Some starter links:

*

*http://msdn.microsoft.com/en-us/library/ms775147(VS.85).aspx

*http://bitworking.org/news/Atom_Auto_Sub_How_To
If that is not enough, maybe libmagic (used by the file command line tool) or its database can be of use to you, even though it is quite UNIX:y.

A: It depends on what you want to do with that data stream.  If all you want to do is open the default program for that file type, writing a temp file and calling Process.Start on it isn't a bad way to go.  If you're looking to perform other operations on the data... well, it depends what operations you had in mind.


text:
Q: What does a good "definition of done" for a mature team look like? When looking at examples of definitions of done in various sources, they usually include points like

*

*code completed

*unit tests run

*code peer-reviewed or paired

*code checked in

*documentation updated

*…

In our team, we have a similar list, but nobody ever looks at it because those points seem so blatantly obvious that it wouldn't occur to anyone to skip any of these steps. So we were wondering whether that's mainly a tool for teams transitioning to an agile process and whether we shouldn't just get rid of it.
On the other hand, lots of literature claims that all high-performing teams have a strong definition of done. This kind of hints that we might miss an opportunity to improve here.
So what are examples of strong definitions of done of a mature team? What kind of points do they include typically?

A: The guidelines are there for everyone. In a mature team, as you mentioned, everyone is doing it, so it does not mean there is no place for it. Suppose, a new member joins, who has not been exposed to this methodology before. Having the structure in place, would be vital for him. He wouldn't have to bother other members, or wouldn't "forget" a deliverable.
In my opinion, List everything, including the obvious. Perhaps, have a "short cheat list" for non-obvious ones if it helps those who want a shorter list, but consider the case of new members hopping on.
It is an iterative process, every time you see something you can improve, add it in the definition of done. Overtime, you will develop a list which is relevant to your company. Anann has already mentioned some which are worthwhile.

A: Just because the points are blatantly obvious doesn't mean that people will always carry them out. Let's take two other examples - pilots and surgeons. A cockpit of a commercial airliner or an operating room has multiple people, with a good deal of education and experience between them. However, things still go wrong - steps are done out of order, something is forgotten, something is done incorrectly. I've seen a number of sources site that a large number (up to 70%) of aircraft incidents attributed to pilot error could have been prevented with a checklist. In the medical world, up to 29% of malpractice lawsuits in the Netherlands could have been prevented with the use of a checklist, according to researchers. Although these people have been trained, and in hindsight would probably easily identify what they did wrong, something happened that caused them to lapse. I haven't read it yet, but The Checklist Manifesto is supposed to be relevant. It's written from a medical profession, but the advantages of making a checklist or flowchart visible as a reminder of what to do are applicable to any profession.
So, step one would be to create a list of things that are part of your definition of done and make it visible. It doesn't matter how obvious that task is, if it needs to be complete for the story to be considered done, it needs to be on that list. The list needs to be somewhere visible to the team. Note that it doesn't have to be anything fancy or formal - perhaps just a series of questions that everyone needs to ask themselves before a story can be called done.
Step two is to decide what goes on that checklist for your definition of done. Everything that you need to do to complete a task should be specific, unambiguous, acceptable, and realistic. It also needs to be within a context of time for consideration of done. For example, you don't need to include "modify code" or "modify design" in a definition of done - if you didn't need to change a work product, there was no need for the story.
I would suspect that a good checklist to serve as a basis for a definition of done would be:

*

*Have all associated unit, integration, system, and acceptance tests been updated?

*Has the work product been transformed into its releasable form? For example, code built, documentation in the exportable file format, etc.

*Have all associated work products been peer-reviewed? Examples of work products include source code (production and test), comments, design documents, test procedures, and user manuals.

*Have all associated tests (at all levels of testing) been executed and pass?

*Has the code been merged into the integration repository?

Of course, you'll need to come up with a good definition of done that includes any other activities that your team and your customer feel add value. If it's on the checklist, it should be something that needs to be done to add value to someone (the team, the customer, the user). By clearly enumerating what you do, you can also identify and eliminate extraneous activities to improve the process.

A: This actually sounds like you are one lucky guy:

In our team, we have a similar list, but nobody ever looks at it
  because those points seem so blatantly obvious

Your team is already "mature" ;-). But there is always room for improvement!
To your question:

So what are examples of strong definitions of done of a mature team?
  What kind of points do they include typically?

On top of your list, you could add:
Various code quality metrics:
 - Instability, Abstraction
 - LOC vs DLOC (documented)
 - etc...
The rule of thumb could be that the metric should not get worse with your commit.
On top you could formulate a "done:withExcellence" if someone actually makes the metrics get way better. Although this (metrics getting better) is usually not part of development phases (new features) but refactoring phases.
In one of my past companies we had a definition of "done" that said that your metrics need to stay below certain thresholds, if you go above, you are not done yet. (Cyclomatic Complexity should never go above 15, unless you have a very very very good excuse, like complicated calcs.)
Same goes for Checkstyle type of violations, especially if you have a custom rule-set to check on your teams code-style. If you are in violation of the coding standard, your are not done yet.
Then you could not only execute UnitTest, you could measure code coverage. If not at least 50% are covered, you are not done. Although this is kind of a flaky defintion of done, since you should have tests for the core/main/critical methods, and not necessarily for 100% of your code base.
Oh yea... and if you have (you should) a CI server with automated branch integration... you are only done if your commit in the DEV Branch merged with the current LIVE-Branch and causes no errors either. (Unit Tests, etc.)
hmmm... that's all I can remember right know from past companies/projects, which hasn't been mentioned in your list.
I hope that gave you some ideas ;-)
Cheers,
anann

A: In a TDD/BDD environment, the definition of "done" (technically "Code Complete", as Matt S's definition of "really 'done'" is correct) is pretty simple:

*

*All automated tests pass (those automated tests should include new ones written for the story in question to verify the required functionality or behavior exists and works)

*Code review passed (at least one senior dev on the team is content to let your work become part of the codebase, and that you didn't "cheat" or "hack" your way through the story)

*Commit successful (including the build bot passing all automated tests, code coverage metrics, style cop checks, etc)

At this point, you can move on. These three points are critical, but they're all that the average team coder must be concerned with. Written or unwritten, they are inviolable in a TDD environment. Documentation, when the coders are the ones doing the documenting, is an additional point. In my last Agile team, documentation was handled by the BAs/QAs; they knew what the client wanted, had run the UATs, and thus were best able to document the new feature in a way that was meaningful to the client, so documentation was not part of the coder's definition of "done", though it was part of the team's definition.


text:
Q: Laravel naming convention with similar Model names This is a very basic question but trying to wrap my head around the preferred naming conventions for models/tables with similar names.
A model 'Task' can have many 'Comments' so the tables would be
- tasks
- comments (with a foreign key for task_id)
However, I have another model 'Post' which will also need a 'Comments' which is of course separate from the Comments for Tasks
In this scenario, does one generally go with
- Task & TaskComment (model) / tasks & task_comments (database table)
- Post & PostComment (model) / posts & post_comments (database table)
or some other convention?

A: What you want for this is polymorphism.
Follow the example on https://laravel.com/docs/5.4/eloquent-relationships#polymorphic-relations . It's really close to what you are trying to do, so hopefully it will be enough. If you get stuck let me know and i'll help you along

A: If you use polymorphic relations you can even make a Comments has its own comments (like a reply system).
In the model you want to have comments you need to add a method like this:
public function comments() {
    return $this->morphMany(Comment::class, 'commentable');
}

Then in your Comment model, you just add
public function commentable() {
    return $this->morphTo();
}

Notice how important it is that your method name in Comment matches with the second parameter passed to the morpMany() function.
Last but not least, the model in which you morph to needs to have special fields in its schema:
You must place them at the end of the traditional schema structure:
// Your comment dedicated schema
$table->integer('commentable_id');
$table->string('commentable_type');

I really don't know if it is important but notice how the field prefix matches with the method name in which we are morphing.


text:
Q: Installing printers drivers in Windows 7 clients with Win server 2003 AD Dears,
I've an issue with installing drivers on windows 7 which keep asking for permission to add the printer driver on other hand i haven't faced this issue with XP clients.
My AD is windows server 2003 I've disabled point and print restrictions from the group policy User Configuration\Policies\Administrative Templates\Control Panel\Printers and deployed it on windows 7 clients but without any success. same, elevation prompts keep showing up.
Note that i don't have the following option on my AD policy :
Computer Configuration\Policies\Administrative Templates\Printers : Point and Print Restrictions
Thank you for your time. :)

A: You need to disable point and print restrictions in the policy you mentioned above. Open the group policy management console from a machine with Windows Vista/2008 or later and the policy will be there.
As an aside, it's been almost a year that 2003 has been out of support, and almost two years for XP. It's really time to upgrade.

A: I agree with MDMarra and you need to disable ( disallow installation of printers using kernel-mode drivers).
you can read Allowing Standard Users to Install Network Printers and Configure GPO

A: Thank you guys for helping. I've used RSAT (Microsoft Remote Server Administration Tools) to got what I want and it did solve my issue.
Now the following option is available for me to disable even though with Win Server 2003:
Computer Configuration\Policies\Administrative Templates\Printers : Point and Print Restrictions


text:
Q: C help: Compiler gives me a "makes pointer from integer without cast" when using strlen() Here is my code. The code is supposed to get the string from a user and output a the length of the string. I am using pointers because I was trying to get the code to work before having to move it to a function.
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{
    //init variables
    char *userInput = malloc(sizeof(20)) ;
    int stringLength;

    //input
    printf("Hello. Please enter a string: \n");
    fgets(userInput,20,stdin);

    //Calculations & Function Calls
    size_t stringLength = strlen(userInput);

    //output
    printf("This is your input:, %s \n", userInput);
    printf("Length: %d \n", stringLength);
    return 0;
}

When using strlen() my compiler is giving me a conversion error. I've tried type casting to int and other methods but no luck. I'm using GCC compiler if that changes anything.
Thanks for the help!

A: You are declaring the variable stringLength twice:
int main()
{
    //init variables
    char *userInput = malloc(20);                      // see explications below
    int stringLength;                                  // <<<<<< here

    //input
    printf("Hello. Please enter a string: \n");
    fgets(userInput,20,stdin);

    //Calculations & Function Calls
    size_t stringLength = strlen(userInput);           // <<<<<< and here

    //output
    printf("This is your input:, %s \n", userInput);
    printf("Length: %d \n", stringLength);
    return 0;
}

Replace
size_t stringLength = strlen(userInput);

by
stringLength = strlen(userInput);

and beforehand declare
size_t stringLength;

instead of
int stringLength;

or just remove int stringLength;
And malloc(sizeof(20)) should be malloc(20). You want to allocate 20 bytes.
sizeof(20) is actually the size of an int, most likely 4 or 8 depending on the platform.

A: C allows only one type declaration for one variable.
As your code you tried to declare again already declared stringLength identifier.
So your code would be
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{
    //init variables
    char *userInput = malloc(sizeof(20)) ;
    unsigned int stringLength;

    //input
    printf("Hello. Please enter a string: \n");
    fgets(userInput,20,stdin);

    //Calculations & Function Calls
    stringLength = strlen(userInput);

    //output
    printf("This is your input:, %s \n", userInput);
    printf("Length: %u \n", stringLength);
    return 0;
}

A: Your program tries to declare variable stringLength twice.
One time as
int stringLength;

and second time as:
   size_t stringLength = strlen(userInput);

This is not allowed in C language. And compiler can catch it.
Please also make sure that you allocate enough memory for your string. This can give you run time problem since you will overwrite memory for strings longer then length the of allocated memory. The sizeof(20) is 4. Your intention was to allocate 20 bytes.
#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{
    //init variables
    char *userInput = malloc(20 * sizeof(char)) ;

    size_t stringLength;

    //input
    printf("Hello. Please enter a string: \n");

    fgets(userInput,20,stdin);

    //Calculations & Function Calls

    stringLength = strlen(userInput);

    //output
    printf("This is your input: %sand it has length: %zu. The sizeof(20) is %zu \n", userInput, stringLength, sizeof(20));

    return 0;
}

Output:
12345
Hello. Please enter a string:
This is your input: 12345
and it has length: 6. The sizeof(20) is 4


text:
Q: How to select checkbox using selenium web driver In my web-page (or popup), there are multiple input-boxes and checkbox. Input boxes and check-boxes are in separate div tag. Here is my html code:

        <form class="form-horizontal form-sections">

                Username*

                    <input name="userId" class="form-control custom-form-control" type="text" placeholder="Username" value="">

                Email*

                    <input name="email" class="form-control custom-form-control" type="text" placeholder="Email" value="">

            .....
        </form>

        <form class="form-horizontal">Note: Optional

Select permissions

                                <input type="checkbox" id="permissions1565851434728" name="permissions">
                                Select all

                                        <input type="checkbox" id="371565851434728" name="permissions" value="Add/Update Network Security">
                                        Add/Update Network Security

                                        <input type="checkbox" id="111565851434728" name="permissions" value="Add/Update Permissions">
                                        Add/Update Permissions

                                    .....

Select roles

                            <input type="checkbox" id="roles1565851434730" name="roles">
                            Select all

                                    <input type="checkbox" id="role-c98974c6-a4b1-4428-9d9e-7df9f00acd351565851434730" name="roles" value="test">
                                    test

                                .....

        </form>

When I come to this page, I'm successfully able to enter text in input fields. When it comes to select checkbox, I have to give complete xpath to that checkbox. Like, if I want to select checkbox Select all, I am giving xpath as
"/html/body/div[@id='app']/div[@class='_loading-overlay']/main/div[@class='container-fluid search_table_container']/div[1]/div[@class='identity-management']/div[@class='row identity-list']/div/div[@class='filter-head col-md-12']/div[@class='search_right']/div[@class='modal fade in']/div[@class='modal-dialog modal-lg']/div[@class='modal-content']/div[@class='modal-body-large']/div[@class='col-md-12 step-forms custom-tab-content'][2]/form[@class='form-horizontal']/div[@class='col-md-6'][1]/div/div[@class='form-sections']/ul/li[2]/label"

My concern is there any alternate to do this?

A: You could use the text of the uncle element. To get Select all under Select permissions you can use
//li[contains(., 'Select permissions')]/following-sibling::li/label

A: You can use xpath, and use WebDriverWait for make the element exist then use Actions, try this :
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@type='checkbox' and contains(@id,'permissions')]")));
WebElement elmnt = driver.findElement(By.xpath("//*[@type='checkbox' and contains(@id,'permissions')]"));
Actions act = new Actions(driver);
act.moveToElement(elmnt).click().build().perform();

Or
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("(//*[@type='checkbox'])[1]")));
WebElement elmnt = driver.findElement(By.xpath("(//*[@type='checkbox'])[1]"));
Actions act = new Actions(driver);
act.moveToElement(elmnt).click().build().perform();

Change the [1] to [2] etc, if you want another checkbox.

A: Selecting a checkbox is similar to clicking a button. I see there is id for all the checkboxes and also value field for some checkboxes. So you can use the following methods to accomplish what you need.
Select checkbox using id by passing it to the XPath,
driver.findElement(By.xpath(".//*[@id='permissions1565851434728']")).sendKeys(Keys.SPACE);

You can click checkbox instead of sending keys like the following,
WebElement checkBox = driver.findElement(By.id("permissions1565851434728"));
checkBox.click();

Select checkbox using value by passing it to the CSSSelector,
WebElement checkBox = driver.findElement(By.cssSelector("input[value='Add/Update Network Security']"));
checkBox.click();

And if there are 2 checkboxes you can use as follows,
driver.FindElements(By.xpath("(//input[@type='checkbox'])[1]"));
driver.FindElements(By.xpath("(//input[@type='checkbox'])[2]")); ...

Selenium WebDriver uses the native methods of browsers to interact with the web components. Be that as it may, some times the web components do not react to these native methods. In such cases, your most solid option is JavaScript.
So you can try the following JavaScript to interact with the web element,
WebElement element = driver.findElement(By.cssSelector("input[value='Add/Update Network Security']"));

((JavascriptExecutor)driver).executeScript("arguments[0].click();", element);

And also you can try with WebDriverWait said by DebanjanB.

A: *

*For Select Roles checkbox:
//li[text()='Select roles']/following-sibling::li/input

*For Select Permissions checkbox the same approach:
//li[text()='Select permissions']/following-sibling::li/input

*following-sibling is XPath Axis returning the next node having the same parent and text() is XPath function matching node text content

A: To click() on the check box associated with the  as Select all as the desired element is within a Modal Dialog you have to induce WebDriverWait for the elementToBeClickable() and you can use the following Locator Strategy:

*

*xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//li[text()='Select permissions']//following::li[1]//label"))).click();


text:
Q: Send filtered data using django via email i want filter the student data by the skills in the vacancy and then send it to the company who posted the requirements in vacancy via email.does anyone have idea about this.
** The Model**
class Student(models.Model):

    name = models.CharField(max_length=50)
    skills = models.ManyToManyField(Skill)
    passout = models.ManyToManyField(Passout)
    email = models.EmailField(max_length=254 ,null = True)
    resume = models.ImageField(upload_to='media/resume', height_field=None, width_field=None, max_length=None , null=True)
    create_date = models.DateTimeField('created date',auto_now_add=True)

    def __str__(self):
        return self.name

class Company(models.Model):

    comp_name = models.CharField(max_length=50)
    loc = models.CharField(max_length=50)
    hr_name = models.CharField(max_length=50)
    hr_email = models.EmailField(max_length=254)

    def __str__(self):
        return self.comp_name

class Vacanccy(models.Model):

    com_name = models.ForeignKey(Company, on_delete=models.CASCADE)
    skillreq = models.ManyToManyField(Skill)
    yearofpass = models.ManyToManyField(Passout)
    title = models.CharField(max_length=255)
    expiry_date = models.CharField(max_length=50)

    def __str__(self):
        return str(self.com_name)

the above image 1st tabel is student , 2nd is  company, 3rd is vacancy
In Vacancy table two companies posted their requirements. The 1st company have matching profile of rini , also 2nd remya
If we filter the data and it should send to the corresponding company like rini details to dell and remya details to redmi

A: Could be a better way! but tried.
and this block of code will mail the path of the resume file, not the Actual File(you have to implement that thing).
from django.core.mail import send_mass_mail
from django.http.response import JsonResponse

#its support function to convert queryset into dict
def get_dict_from_quryset(key, val, records):
    dict = {}
    for record in records:
        dict[record[key]] = record[val]

    return dict

def your_function_name(request):
    mail_data = []
    vacancies = Vacanccy.objects.all().values("com_name_id", "com_name__comp_name", "skillreq", "skillreq__name", "yearofpass__year")
    skills_ids = list(vacancies.values_list("skillreq", flat=True))
    comp_ids = list(set(vacancies.values_list("com_name_id", flat=True)))
    pass_years = list(vacancies.values_list("yearofpass", flat=True))
    comp_details = {}
    companies = Company.objects.filter(id__in=comp_ids).values("id","hr_email")
    dict_companies = get_dict_from_quryset("id", "hr_email", companies)
    vacancy_dict = {}
    for data in vacancies:
        vacancy_dict[data['skillreq']] = data['com_name_id']

    applicable_student_data = Student.objects.filter(skills__in=skills_ids, passout__in=pass_years).values("id","name", "resume", 'skills')

    repeat_student_id = []
    for student in applicable_student_data:
        if student['skills'] in vacancy_dict and student['id'] not in repeat_student_id:
            company_id = vacancy_dict[student['skills']]
            if company_id in dict_companies:
                email_id_hr = dict_companies[company_id]
                mail_content = ('Subject', student['resume'], 'yourrrr.from@gmail.com', [email_id_hr])
                mail_data.append(
                        mail_content
                )
                repeat_student_id.append(student['id'])
                continue

    tupple_mail_data = tuple(mail_data)

    if tupple_mail_data:
        send_mass_mail(tupple_mail_data, fail_silently=False)
    return JsonResponse({"status": "Succeed"})


text:
Q: A regex to trim URL down to a simple #id Could someone suggest a regex that will find every instance of
http://example.com/dokuwiki/doku.php/folder:page?do=export_xhtml#id

where

*

*section is a, variable, folder/section in the Wiki

*page is a page in that folder/section

*id refers to the HTML id attribute of div on that page

so it just reads #id?  The end result will be replacing a fully qualified URL to an internal link on that page from

to just

The context here is modifying the exported contents from the Wiki, dokuwiki, to make it suitable for distribution via a CDN.  The absolute links that go into the exported markup you get via export_xhtml are not necessray and are no good for the CDN since as soon as the user touches such a link he/she will end up visiting the full blown wiki.

A: This should serve you well:
/http:\/\/example.com\/([^\/]+\/[^\/]+)\/([^\?]+)[^#]+#(\d+)/

I assume that the id is a digit.
From your example URL this will match:

*

*dokuwiki/doku.php

*folder:page

*56 (the id)

To just get the id it would be easiest to do:
/#\d+$/


text:
Q: maven dependency convergence error I am getting this weird maven error running mvn clean install command for one of our projects ( lets call it A , and version 1.0.0-SNAPSHOT) :
Dependency convergence error for C:3.2.6-SNAPSHOT paths to dependency are
+-A:1.0.0-SNAPSHOT
  +-B:3.2.4
    +-C:3.2.6-SNAPSHOT

and
 +-A:1.0.0-SNAPSHOT
   +-B:3.2.4
     +-C:3.2.3

What I dont understand is that how can the same version of B ( 3.2.4 ) transitively bring Different versions of the jar C ( 3.2.6-SN  and 3.2.3 )

A: It can't. Check your artifact names, and take a look at this:
Multiple versions of the same dependency in Maven


text:
Q: How to cbind objects from the.GlobalEnv with certain string pattern? I have a bunch of objects in my Environment and I would like to cbind them into a data frame based on some string pattern. For Example:
A.LLB<-c(1,2,3,4)
A.LBW<-c(2,3,4,5)
A.L2B<-c(5,33,6,7)
A.F2G<-c(5,33,6,7)

I would like to bind A.LLB and A.L2B and F2G only. I tried the following:
obj.list <- eapply(.GlobalEnv,function(x) if(is.vector(x)) x)

Test<-as.data.frame(do.call(cbind, obj.list))

which binds all objects together. So I added:
obj.list <- eapply(.GlobalEnv,function(x) if(is.vector(x)) x & grepl('LLB','L2B', 'F2G'))

But thats seems wrong.


text:
Q: php ffmpeg flv conversion error I am trying to convert mp4 file to flv but i am getting 0 size flv files,
can you please help me out on this

array(45) { [0]=string(72) "FFmpeg version SVN-r26402, Copyright (c)
2000-2011 the FFmpeg developers" [1]=string(74) " built on Jan 12
2012 16:07:49 with gcc 4.1.2 20080704 (Red Hat 4.1.2-51)" [2]=>
string(98) " configuration: --enable-libmp3lame --enable-gpl
--enable-libvorbis --disable-mmx --enable-shared" [3]=string(35) " libavutil 50.36. 0 / 50.36. 0" [4]=string(35) " libavcore 0.16. 1 /
0.16. 1" [5]=string(37) " libavcodec 52.108. 0 / 52.108. 0" [6]=string(35) " libavformat 52.93. 0 / 52.93. 0" [7]=string(35) "
libavdevice 52. 2. 3 / 52. 2. 3" [8]=string(35) " libavfilter 1.74.
0 / 1.74. 0" [9]=string(35) " libswscale 0.12. 0 / 0.12. 0" [10]=>
string(0) "" [11]=string(101) "Seems stream 0 codec frame rate
differs from container frame rate: 30000.00 (30000/1) -15.00 (15/1)"
[12]=string(106) "Input #0, mov,mp4,m4a,3gp,3g2,mj2, from
'16112007069.mp4':"
[13]=string(11) " Metadata:" [14]=string(26) " major_brand : mp42"
[15]=string(23) " minor_version : 0" [16]=string(35) "
compatible_brands: mp423gp4isom" [17]=string(41) " creation_time :
2007-11-16 15:44:57" [18]=string(59) " Duration: 00:00:32.64, start:
0.000000, bitrate: 562 kb/s" [19]=string(115) " Stream #0.0(und): Video: mpeg4, yuv420p, 352x288 [PAR 1:1 DAR 11:9], 512 kb/s, 15 fps,
15 tbr, 30k tbn, 30k tbc" [20]=string(13) " Metadata:" [21]=>
string(43) " creation_time : 2007-11-16 15:44:57" [22]=string(62) "
Stream #0.1(und): Audio: aac, 16000 Hz, mono, s16, 48 kb/s" [23]=>
string(13) " Metadata:" [24]=string(43) " creation_time : 2007-11-16
15:44:58" [25]=string(87) "WARNING: The bitrate parameter is set too
low. It takes bits/s as argument, not kbits/s" [26]=string(47)
"[buffer @ 0x94a9de0] w:352 h:288 pixfmt:yuv420p" [27]=string(98)
"[libmp3lame @ 0x94a9560] flv does not support that sample rate,
choose from (44100, 22050, 11025)." [28]=string(85) "Output #0, flv,
to '16112007069.flv':" [29]=string(11) " Metadata:" [30]=string(26) " major_brand : mp42"
[31]=string(23) " minor_version : 0" [32]=string(35) "
compatible_brands: mp423gp4isom" [33]=string(41) " creation_time :
2007-11-16 15:44:57" [34]=string(33) " encoder : Lavf52.93.0" [35]=>
string(103) " Stream #0.0(und): Video: flv, yuv420p, 352x288 [PAR 1:1
DAR 11:9], q=2-31, 200 kb/s, 1k tbn, 15 tbc" [36]=string(13) "
Metadata:" [37]=string(43) " creation_time : 2007-11-16 15:44:57"
[38]=string(68) " Stream #0.1(und): Audio: libmp3lame, 16000 Hz,
mono, s16, 0 kb/s" [39]=string(13) " Metadata:" [40]=string(43) "
creation_time : 2007-11-16 15:44:58" [41]=string(15) "Stream
mapping:" [42]=string(21) " Stream #0.0 -#0.0" [43]=string(21) "
Stream #0.1 -#0.1" [44]=string(72) "Could not write header for
output file #0 (incorrect codec parameters ?)" }

ffmpeg: /usr/local/bin/ffmpeg file

path: 16112007069.mp4

srcAR: 16000

srcAB:48

dimention: 352 x 288 destFile: 16112007069.flv

coding part: :)
$srcFile = "/file destination/16112007069.mp4";
$destFile = "/file destination/16112007069.flv";
$ffmpegPath = "/usr/local/bin/ffmpeg";

$ffmpegObj = new ffmpeg_movie($srcFile);

$srcWidth = makeMultipleTwo($ffmpegObj->getFrameWidth());
$srcHeight = makeMultipleTwo($ffmpegObj->getFrameHeight());
$srcFPS = $ffmpegObj->getFrameRate();
$srcAB = intval($ffmpegObj->getAudioBitRate());
$srcAR => $ffmpegObj->getAudioSampleRate();

exec($ffmpegPath . " -i " . $srcFile . " -ar " . $srcAR . " -ab " . $srcAB . " -f flv -s " . $srcWidth . "x" . $srcHeight . " " . $destFile . " 2>&1", $output);

var_dump($output);

print "
ffmpeg: $ffmpegPath
"; print "file path: $srcFile
"; print "srcAR: $srcAR
"; print "srcAB: $srcAB
"; print
"dimention: $srcWidth x $srcHeight
"; print "destFile:
$destFile
";

function makeMultipleTwo ($value)  {
    $sType = gettype($value/2);
    if($sType == "integer")
    {
        return $value;
    } else {
        return ($value-1);
    }
}

Note I added:
if($srcAR<41000){ $srcAR = "41000"; }

Above and its working!

A: test this one :
ffmpeg -i src.avi -an dest.flv

A: try this $ffmpeg -i src.avi dest.flv


text:
Q: How to set-up calculations with max and average function for one category in moodle? I have three tests in a category in moodle. T1, T2 and T3.
The grade for this category is calculated as: maximum (T1, 10*average(T2,T3)). Is there any option to let moodle grade book do this calculation itself?
I tried the next combinations:
=max([[T1]], [[5*(T2+T3)]])
=max([[T1]], 5*(T2+T3))
=max([[T1]], 10*average(T2,T3))
=
a=10*average(T2,T3)
b=max([[T1]],[[a]])
but I'm getting this error: Formule is niet geldig
What am I doing wrong? Can sb help me pls?


text:
Q: NSCoding a c struct object which is property of a class I have a class called Account with 6 properties and one of the properties is a c struct.  I can't figure out how to use NSCoding to comply with the struct.  How would I go about encoding and decoding the c struct property.  The struct is the type app_config_t.
the struct
typedef struct app_config_t
{
    pj_pool_t               *pool;

    pjsua_config            cfg;
    pjsua_logging_config    log_cfg;
    pjsua_media_config      media_cfg;

    pjsua_transport_config  udp_cfg;
    pjsua_transport_config  rtp_cfg;

    pj_bool_t               ringback_on;
    pj_bool_t               ring_on;

    int                     ringback_slot;
    int                     ringback_cnt;
    pjmedia_port            *ringback_port;

    int                     ring_cnt;
    SystemSoundID           ring_id;
    CFRunLoopTimerRef       ring_timer;
} app_config_t;

An Objective-C class called 'Account' with property App_config
#pragma mark - NSCoding
- (void) encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.Username forKey:@"username"];
    [aCoder encodeObject:self.Password forKey:@"password"];
    [aCoder encodeObject:self.Server forKey:@"server"];

    [aCoder encodeInt:self.Account_id forKey:@"Account_id"];
    [aCoder encodeInt:self.Call_id forKey:@"Call_id"];

    //trying to save this object, is this even correct
    NSMutableData *data = [NSMutableData dataWithBytes:&_App_config length:sizeof(app_config_t)];
    NSKeyedArchiver *App_config_Archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [aCoder encodeObject:App_config_Archiver forKey:@"App_config"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init])
    {
        self.Username = [aDecoder decodeObjectForKey:@"username"];
        self.Password = [aDecoder decodeObjectForKey:@"password"];
        self.Server = [aDecoder decodeObjectForKey:@"server"];

        self.Account_id = [aDecoder decodeIntForKey:@"Account_id"];
        self.Call_id = [aDecoder decodeIntForKey:@"Call_id"];

        self.App_config = ?????????

    }

    return self;
}

A: You current encoding code has error. Mutable data you provide for NSKeyedArchiver is used by archiver to store encoded data. So copying app_config_t structure is useless.
You need to encode each field of your structure with NSKeyedArchiver. It has encoders for primitive types. Also in app_config_t structure I see fields that are not primitive types but complex types. So you need custom encoding for such fields too.
- (void) encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.Username forKey:@"username"];
    [aCoder encodeObject:self.Password forKey:@"password"];
    [aCoder encodeObject:self.Server forKey:@"server"];

    [aCoder encodeInt:self.Account_id forKey:@"Account_id"];
    [aCoder encodeInt:self.Call_id forKey:@"Call_id"];

    // this data will have encoded structure
    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *App_config_Archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

    // for all fields from structure you need to use such encoders
    [App_config_Archiver encodeBool:_App_config.ringback_on forKey:@"ringback_on"];

    // encode data itself
    [aCoder encodeObject:data forKey:@"App_config"];
}

A: You should be able to treat the struct as a memory buffer and use NSCoder's encodeBytes function to do this:
- (void)encodeBytes:(const void * _Nullable)byteaddr
             length:(NSUInteger)length


text:
Q: ¿Como detectar cambios de la base de datos en mi DataGridView C#? Tengo una consulta y es la siguiente:
Tengo un DataGridView que se llena desde una consulta de base de datos, lo que deseo hacer es como detectar cambios en la base de datos y se actualize en tiempo real en mi DataGridView y me mande un MessageBox cada vez que haya cambios en la base de datos.
He escuchado de SqlDependency pero no se como implementarlo.
Mi clase Conexión
public class Conexion
    {
        public SqlConnection getConexion()
        {
            SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
            return cn;
        }
    }

Mi clase Negocios
public class Negocios
    {
        Conexion objCon = new Conexion();

        public DataTable listarPersonas()
        {
            var cn = objCon.getConexion();
            SqlDataAdapter adapter = new SqlDataAdapter("select * from Persona", cn);
            DataTable dt = new DataTable();
            cn.Open();
            adapter.Fill(dt);
            cn.Close();
            return dt;
        }
    }

Mi Form
private void Form1_Load(object sender, EventArgs e)
        {
            dgListado.DataSource = objNegocios.listarPersonas();
            dgListado.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
        }

A: Si pudieras contarnos un poco más de lo que sucede en tu aplicación...pienso que tienes un formulario y un DGV en el mismo form y que al presionar un botón para enviar los datos, quieres que el DGV se actualice automáticamente. ¿Estoy en lo correcto? ¿O de que manera obtiene nuevos datos tu base de datos?


text:
Q: How do I filter so that I am only seeing the selected states? Having issues understanding why R wont compute my syntax. Given the sample df:
Name              Birth.State                 height    `Birth.State == "New Jersey"`
  <chr>             <chr>                       <chr>     <lgl>
1 George Washington "     Virginia"             74 inches FALSE
2 John Adams        "            Massachusetts" 67 inches FALSE
3 Thomas Jefferson  "      Virginia"            75 inches FALSE
4 James Madison     "         Virginia"         64 inches FALSE
5 James Monroe      "          Virginia"        72 inches FALSE

My goal is to just have data of presidents from New Jersey, I've tried the following but have been having issues.
str_detect(c$Birth.State, pattern = "New Jersey")
filter(c,grep('New Jersey',Birth.State))
parse_character(c$Birth.State)
is.character(c$Birth.State)

A: Demonstrating suggestions in the comments:
library(stringr)
df <- data.frame(name = "George Washington",
           state = "     Virginia")

No exact match because of white spaces
"Virginia" %in% df$state
#> [1] FALSE

Use pattern matching
str_detect(df$state, pattern = "Virginia")
#> [1] TRUE
df[str_detect(df$state, pattern = "Virginia"),"name"]
#> [1] "George Washington"

grepl("Virginia", df$state)
#> [1] TRUE
df[grepl("Virginia", df$state),"name"]
#> [1] "George Washington"

Or remove white space:
df$state2 <- trimws(df$state)
"Virginia" %in% df$state2
#> [1] TRUE
df[df$state2 == "Virginia", "name"]
#> [1] "George Washington"

Created on 2021-09-23 by the reprex package (v2.0.1)


text:
Q: __LINE__ feature in Groovy It is possible to get current line number by __LINE__ in Ruby or Perl.
For example:
print "filename: #{__FILE__}, line: #{__LINE__}"

Is there the same feature in Groovy?

A: Not directly, but you can get it through an Exception (or Throwable) stack trace.  For example:
 StackTraceElement getStackFrame(String debugMethodName) {
     def ignorePackages = [
         'sun.',
         'java.lang',
         'org.codehaus',
         'groovy.lang'
     ]
     StackTraceElement frame = null
     Throwable t = new Throwable()
     t.stackTrace.eachWithIndex { StackTraceElement stElement, int index ->
         if (stElement.methodName.contains(debugMethodName)) {
             int callerIndex = index + 1
             while (t.stackTrace[callerIndex].isNativeMethod() ||
                    ignorePackages.any { String packageName ->
                        t.stackTrace[callerIndex].className.startsWith(packageName)
                    }) {
                 callerIndex++
             }
             frame = t.stackTrace[callerIndex]
             return
         }
     }
     frame
 }

 int getLineNumber() {
     getStackFrame('getLineNumber')?.lineNumber ?: -1
 }

 String getFileName() {
     getStackFrame('getFileName')?.fileName
 }

 String getMethodName() {
     getStackFrame('getMethodName')?.methodName
 }

 def foo() {
     println "looking at $fileName:$lineNumber ($methodName)"
 }

 foo()

 // ==> looking at test.groovy:39 (foo)

A word of caution though: getting the line number, file name, or method like this is very slow.

A: I'm not an expert in Groovy, but I don't think so. I know that Java and C# don't have it.
The __LINE__ feature really started to help with debugging in C. C doesn't have exceptions or many of the other features modern languages have, but it did have macros that the compiler could expand anywhere in the code, which is why we needed __FILE__, __LINE__, etc to let us know where we were when something bad happened. This is how assert works in C and C++. The JVM has very good debugging tools, and combined with assert and exceptions, you can very easily pinpoint where something went wrong (stack traces are way better than just a line number anyway).
I believe the reason Ruby and Perl have those macros is because they were created by C hackers. I've never used either of those languages enough to know the level of debugging support or how useful the macros really are.


text:
Q: difference between two dates in year month day I have a two dates :
Date startDate = "24/05/2020;
Date endDate = "21/09/2021";

How to calculate difference in year/month/day
Example:
1 year, 3 month,27 day

A: You can use LocalDate#until to get the Period object from which you can further derive the days, months, years etc.
Demo:
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.ENGLISH);
        LocalDate startDate = LocalDate.parse("24/05/2020", formatter);
        LocalDate endDate = LocalDate.parse("21/09/2021", formatter);
        Period period = startDate.until(endDate);
        System.out.println(period);
        System.out.println(formatPeriod(period));
    }

    static String formatPeriod(Period period) {
        return String.format("%d years %d months %d days", period.getYears(), period.getMonths(), period.getDays());
    }
}

Output:
P1Y3M28D
1 years 3 months 28 days


text:
Q: Count number of pixels satisfying different conditions in an online layer within a polygon Raster file-> Terrain: Slope in Degrees in ArcGIS Online, by ESRI
Shapefile-> US Census Tracts in Census 2000, downloaded from NHGIS
I would like to have more information about the distribution of slope within a certain census tract (each of them is a polygon). In particular, how many pixels satisfy different conditions (e.g. slope between 0-5%, between 5-10%, 10-15, >15) and also calculate the range of slope within the polygon.
I've done something like this before using Con and Zonal Statistics as Table but it meant having use the Python console to create a different raster for every possible category and that would take too long (also lots of HDD space). Also, I don't know how to do this with ArcGIS Online Layers since they are huge (this one is about 1.5TB), so maybe there is another option.

A: If someone else has the same question, this is what I ended up doing.
Instead of using Terrain: Slope in Degrees, I used the Land Surface Forms developed by the USGS, which basically categorizes each pixel by their slope and elevation range.
After this, the quickest (but memory intensive) option is to use the isectpolyrst command of the Geospatial Modelling Environment toolbox for ArcGIS 10.3. Unfortunately, my computer does not have that much memory (the raster is about 20gb) so I opted for using R instead.
In R you can use the extract() function to do the trick. The code is still running and I really hope it will deliver what I'm looking for (I'll post updates).


text:
Q: Change background button2 into button1 iPhone I am a beginner in Xcode, and I have a problem.
I have 2 buttons:
- (IBAction) HIGH1: (id) sender
- (IBAction) HIGH2: (id) sender

When the user clicks the HIGH1button, I want to change the background (with image) of the button HIGH2.
How can I achieve this?

A: You need to create IBOutlet for the buttons to change them.
Control+drag the buttons from Interface Builder to the .h file to create the outlets. Something like this:
@property (weak, nonatomic) IBOutlet UIButton *HIGH1;
@property (weak, nonatomic) IBOutlet UIButton *HIGH2;
//Dont forget to @synthesize

On the IBAction method you then call:
- (IBAction) HIGH1: (id) sender
{
    self.HIGH2 setBackgroundImage:[UIImage imageNamed:@"myButtonImage"] forState:UIControlStateNormal];
}

Make sure you have an image with the name you choose in your application bundle, and that the IBOutlet to the buttons is properly connected (The gray circle on the left size of the IBOutlet must have a small black circle inside it)

A: [HIGH1 addTarget:self
          action:@selector(buttonDidPushed)
forControlEvents:UIControlEventTouchUpInside];

then,
-(void)buttonDidPushed
{
       HIGH2.backgroundColor = [UIColor blackColor];
       [self.view addSubview:HIGH2];
}

I hope this code help you.

A: access your ivar from HIGH2 and set setBackgroundImage:forState: on HIGH1